forked from TurboWarp/extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-storage.js
More file actions
262 lines (239 loc) · 7.28 KB
/
local-storage.js
File metadata and controls
262 lines (239 loc) · 7.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Name: Local Storage
// ID: localstorage
// Description: Store data persistently. Like cookies, but better.
// License: MIT AND MPL-2.0
(function (Scratch) {
"use strict";
if (!Scratch.extensions.unsandboxed) {
throw new Error("Local Storage must be run unsandboxed");
}
const getNamespace = () =>
Scratch.vm.runtime.extensionStorage["localstorage"]?.namespace;
/**
* @param {string} newNamespace
*/
const setNamespace = (newNamespace) => {
Scratch.vm.runtime.extensionStorage["localstorage"] = {
namespace: newNamespace,
};
Scratch.vm.extensionManager.refreshBlocks("localstorage");
readFromStorage();
};
const STORAGE_PREFIX = "extensions.turbowarp.org/local-storage:";
const getStorageKey = () => `${STORAGE_PREFIX}${getNamespace()}`;
/**
* Cached in memory for performance.
* @type {Record<string, string|number|boolean>}
*/
let namespaceValues = Object.create(null);
const readFromStorage = () => {
namespaceValues = Object.create(null);
try {
// localStorage could throw if unsupported
const data = localStorage.getItem(getStorageKey());
if (data) {
// JSON.parse could throw if data is invalid
const parsed = JSON.parse(data);
if (parsed && parsed.data) {
// Remove invalid values from the JSON
for (const [key, value] of Object.entries(parsed.data)) {
if (
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
namespaceValues[key] = value;
}
}
}
}
} catch (error) {
console.error("Error reading from local storage", error);
}
};
const saveToLocalStorage = () => {
try {
if (Object.keys(namespaceValues).length > 0) {
localStorage.setItem(
getStorageKey(),
JSON.stringify({
// If we find that turbowarp.org is commonly running out of shared space in local storage,
// having a timestamp here makes it at least theoretically possible to delete storage based
// on last used time.
time: Math.round(Date.now() / 1000),
data: namespaceValues,
})
);
} else {
localStorage.removeItem(getStorageKey());
}
} catch (error) {
console.error("Error saving to local storage", error);
}
};
window.addEventListener("storage", (event) => {
if (
getNamespace() &&
event.key === getStorageKey() &&
event.storageArea === localStorage
) {
readFromStorage();
Scratch.vm.runtime.startHats("localstorage_whenChanged");
}
});
const generateRandomNamespace = () => {
// doesn't need to be cryptographically secure and doesn't need to have excessive length
// this has 16^16 = 18446744073709551616 possible namespaces which is plenty
const soup = "0123456789abcdef";
let id = "";
for (let i = 0; i < 16; i++) {
id += soup[Math.floor(Math.random() * soup.length)];
}
return id;
};
const generateRandomNamespaceIfMissing = () => {
if (!getNamespace()) {
setNamespace(generateRandomNamespace());
}
};
Scratch.vm.runtime.on("PROJECT_LOADED", () => {
generateRandomNamespaceIfMissing();
});
Scratch.vm.runtime.on("RUNTIME_DISPOSED", () => {
generateRandomNamespace();
});
generateRandomNamespaceIfMissing();
let lastNamespaceWarning = 0;
const validNamespace = () => {
const valid = !!getNamespace();
if (!valid && Date.now() - lastNamespaceWarning > 3000) {
alert(
Scratch.translate(
'Local Storage extension: project must run the "set storage namespace ID" block before it can use other blocks'
)
);
lastNamespaceWarning = Date.now();
}
return valid;
};
class LocalStorage {
getInfo() {
return {
id: "localstorage",
name: Scratch.translate("Local Storage"),
docsURI: "https://extensions.turbowarp.org/local-storage",
blocks: [
{
blockType: Scratch.BlockType.LABEL,
text: getNamespace()
? Scratch.translate(
{
default: "Namespace: {namespace}",
},
{
namespace: getNamespace(),
}
)
: Scratch.translate("No namespace set"),
},
{
opcode: "get",
blockType: Scratch.BlockType.REPORTER,
text: Scratch.translate("get [KEY] from storage"),
arguments: {
KEY: {
type: Scratch.ArgumentType.STRING,
defaultValue: Scratch.translate("score"),
},
},
},
{
opcode: "set",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("set [KEY] to [VALUE] in storage"),
arguments: {
KEY: {
type: Scratch.ArgumentType.STRING,
defaultValue: Scratch.translate("score"),
},
VALUE: {
type: Scratch.ArgumentType.STRING,
defaultValue: "1000",
},
},
},
{
opcode: "remove",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("delete [KEY] from storage"),
arguments: {
KEY: {
type: Scratch.ArgumentType.STRING,
defaultValue: Scratch.translate("score"),
},
},
},
{
opcode: "removeAll",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("delete storage"),
},
{
opcode: "whenChanged",
blockType: Scratch.BlockType.EVENT,
text: Scratch.translate("when another window changes storage"),
isEdgeActivated: false,
},
"---",
{
opcode: "setProjectId",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("set namespace to [ID]"),
arguments: {
ID: {
type: Scratch.ArgumentType.STRING,
defaultValue:
getNamespace() || Scratch.translate("project title"),
},
},
},
],
};
}
setProjectId({ ID }) {
setNamespace(Scratch.Cast.toString(ID));
}
get({ KEY }) {
if (!validNamespace()) {
return "";
}
KEY = Scratch.Cast.toString(KEY);
if (!Object.prototype.hasOwnProperty.call(namespaceValues, KEY)) {
return "";
}
return namespaceValues[KEY];
}
set({ KEY, VALUE }) {
if (!validNamespace()) {
return "";
}
namespaceValues[Scratch.Cast.toString(KEY)] = VALUE;
saveToLocalStorage();
}
remove({ KEY }) {
if (!validNamespace()) {
return "";
}
delete namespaceValues[Scratch.Cast.toString(KEY)];
saveToLocalStorage();
}
removeAll() {
if (!validNamespace()) {
return "";
}
namespaceValues = Object.create(null);
saveToLocalStorage();
}
}
Scratch.extensions.register(new LocalStorage());
})(Scratch);