@kubohiroya/turbowarp-plus-editor-project-folder 0.9.3 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,44 +1,6 @@
1
- // \0@oxc-project+runtime@0.156.0/helpers/esm/asyncIterator.js
2
- function _asyncIterator(r) {
3
- var n, t, o, e = 2;
4
- for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
5
- if (t && null != (n = r[t])) return n.call(r);
6
- if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
7
- t = "@@asyncIterator", o = "@@iterator";
8
- }
9
- throw new TypeError("Object is not async iterable");
10
- }
11
- function AsyncFromSyncIterator(r) {
12
- function AsyncFromSyncIteratorContinuation(r) {
13
- if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object."));
14
- var n = r.done;
15
- return Promise.resolve(r.value).then(function(r) {
16
- return {
17
- value: r,
18
- done: n
19
- };
20
- });
21
- }
22
- return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
23
- this.s = r, this.n = r.next;
24
- }, AsyncFromSyncIterator.prototype = {
25
- s: null,
26
- n: null,
27
- next: function next() {
28
- return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
29
- },
30
- "return": function _return(r) {
31
- var n = this.s["return"];
32
- return void 0 === n ? Promise.resolve({
33
- value: r,
34
- done: !0
35
- }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
36
- },
37
- "throw": function _throw(r) {
38
- var n = this.s["throw"];
39
- return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
40
- }
41
- }, new AsyncFromSyncIterator(r);
1
+ // node_modules/@kubohiroya/sb3-toolchain/dist/assert.js
2
+ function assert(condition, message) {
3
+ if (!condition) throw new Error(message);
42
4
  }
43
5
  // \0@oxc-project+runtime@0.156.0/helpers/esm/typeof.js
44
6
  function _typeof(o) {
@@ -96,6 +58,283 @@ function _objectSpread2(e) {
96
58
  }
97
59
  return e;
98
60
  }
61
+ // node_modules/@kubohiroya/sb3-toolchain/dist/block-palette.js
62
+ var blockPaletteFile = "block-palette.json";
63
+ var blockPaletteCommentMarker = " // _twplus_palette_";
64
+ var blockPaletteCommentReference = `block-palette:${blockPaletteFile}`;
65
+ var blockPaletteCommentMaxLength = 8e3;
66
+ var blockPaletteSpriteCommentHeader = "TurboWarp Plus Editor block palette for this sprite. You can delete this comment to reset the palette.";
67
+ var blockPaletteStageCommentHeader = "TurboWarp Plus Editor block palette for the stage. You can delete this comment to reset the palette.";
68
+ var markerToken = "// _twplus_palette_";
69
+ var groupIdPattern = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9_-]+)?$/u;
70
+ var setIdPattern = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
71
+ function isRecord(value) {
72
+ return typeof value === "object" && value !== null && !Array.isArray(value);
73
+ }
74
+ function assertOnlyKeys(value, allowed, description) {
75
+ for (const key of Object.keys(value)) assert(allowed.includes(key), `${description} has an unknown key: ${key}`);
76
+ }
77
+ function validateGroupList(value, description) {
78
+ assert(Array.isArray(value), `${description} must be an array of block group IDs.`);
79
+ const seen = /* @__PURE__ */ new Set();
80
+ for (const group of value) {
81
+ assert(typeof group === "string" && groupIdPattern.test(group), `${description} contains an invalid block group ID: ${JSON.stringify(group)}`);
82
+ assert(!seen.has(group), `${description} contains a duplicate block group ID: ${group}`);
83
+ seen.add(group);
84
+ }
85
+ return [...seen];
86
+ }
87
+ function validateTargetSetting(value, description) {
88
+ assert(isRecord(value), `${description} must be an object.`);
89
+ assertOnlyKeys(value, ["groups"], description);
90
+ return { groups: validateGroupList(value.groups, `${description} groups`) };
91
+ }
92
+ function validateSets(value, description) {
93
+ assert(isRecord(value), `${description} must be an object.`);
94
+ return Object.fromEntries(Object.entries(value).map(([setId, set]) => {
95
+ assert(setIdPattern.test(setId), `${description} has an invalid set ID: ${setId}`);
96
+ const setDescription = `${description}.${setId}`;
97
+ assert(isRecord(set), `${setDescription} must be an object.`);
98
+ assertOnlyKeys(set, ["name", "groups"], setDescription);
99
+ assert(typeof set.name === "string" && set.name.length > 0, `${setDescription} name must be a non-empty string.`);
100
+ return [setId, {
101
+ name: set.name,
102
+ groups: validateGroupList(set.groups, `${setDescription} groups`)
103
+ }];
104
+ }));
105
+ }
106
+ function canonicalDocument(parts) {
107
+ const document = { formatVersion: 1 };
108
+ if (parts.order !== void 0) document.order = parts.order;
109
+ if (parts.sets !== void 0) document.sets = parts.sets;
110
+ if (parts.stage !== void 0) document.stage = parts.stage;
111
+ if (parts.sprites !== void 0 && Object.keys(parts.sprites).length > 0) document.sprites = parts.sprites;
112
+ return document;
113
+ }
114
+ function hasBlockPaletteSettings(document) {
115
+ return document.order !== void 0 || document.sets !== void 0 || document.stage !== void 0 || document.sprites !== void 0 && Object.keys(document.sprites).length > 0;
116
+ }
117
+ function stageHasSettings(document) {
118
+ return document.order !== void 0 || document.sets !== void 0 || document.stage !== void 0;
119
+ }
120
+ /** Validate the shape of `block-palette.json` without looking at the project. */
121
+ function validateBlockPaletteDocument(value) {
122
+ const description = blockPaletteFile;
123
+ assert(isRecord(value), `${description} must contain an object.`);
124
+ assertOnlyKeys(value, [
125
+ "formatVersion",
126
+ "order",
127
+ "sets",
128
+ "stage",
129
+ "sprites"
130
+ ], description);
131
+ assert(value.formatVersion === 1, `Unsupported ${description} formatVersion: ${String(value.formatVersion)}`);
132
+ let sprites;
133
+ if (value.sprites !== void 0) {
134
+ assert(isRecord(value.sprites), `${description} sprites must be an object.`);
135
+ assert(Object.keys(value.sprites).length > 0, `${description} sprites must be omitted when it has no sprites.`);
136
+ sprites = Object.fromEntries(Object.entries(value.sprites).map(([name, setting]) => [name, validateTargetSetting(setting, `${description} sprites.${name}`)]));
137
+ }
138
+ const document = canonicalDocument({
139
+ order: value.order === void 0 ? void 0 : validateGroupList(value.order, "order"),
140
+ sets: value.sets === void 0 ? void 0 : validateSets(value.sets, `${description} sets`),
141
+ stage: value.stage === void 0 ? void 0 : validateTargetSetting(value.stage, `${description} stage`),
142
+ sprites
143
+ });
144
+ assert(hasBlockPaletteSettings(document), `${description} has no settings; remove it and use SB3 source format 1.`);
145
+ return document;
146
+ }
147
+ function serializeBlockPaletteDocument(document) {
148
+ return `${JSON.stringify(canonicalDocument(document), null, 2)}\n`;
149
+ }
150
+ /**
151
+ * List each target's comments. In strict mode, a malformed target or comment is an error;
152
+ * otherwise it is skipped so unpacking stays as permissive as it was in source format 1.
153
+ */
154
+ function targetComments(project, strict = true) {
155
+ if (!strict && !Array.isArray(project.targets)) return [];
156
+ assert(Array.isArray(project.targets), "Project targets must be an array.");
157
+ const targets = [];
158
+ for (const [index, target] of project.targets.entries()) {
159
+ var _target$comments;
160
+ if (!strict && !isRecord(target)) continue;
161
+ assert(isRecord(target), `Project target ${index} must be an object.`);
162
+ const comments = (_target$comments = target.comments) !== null && _target$comments !== void 0 ? _target$comments : {};
163
+ if (!strict && !isRecord(comments)) continue;
164
+ assert(isRecord(comments), `Project target ${index} comments must be an object.`);
165
+ const records = Object.fromEntries(Object.entries(comments).filter(([id, comment]) => {
166
+ assert(!strict || isRecord(comment), `Project target ${index} comment ${id} must be an object.`);
167
+ return isRecord(comment);
168
+ }));
169
+ targets.push({
170
+ comments: records,
171
+ isStage: target.isStage === true,
172
+ name: typeof target.name === "string" ? target.name : String(index)
173
+ });
174
+ }
175
+ return targets;
176
+ }
177
+ function isMarkedComment(comment) {
178
+ return typeof comment.text === "string" && comment.text.includes(markerToken);
179
+ }
180
+ function isReferenceComment(comment) {
181
+ return comment.text === blockPaletteCommentReference;
182
+ }
183
+ function canonicalCommentText(document, target) {
184
+ let payload;
185
+ if (target.isStage) {
186
+ payload = { formatVersion: 1 };
187
+ if (document.stage) payload.groups = document.stage.groups;
188
+ if (document.order) payload.order = document.order;
189
+ if (document.sets) payload.sets = document.sets;
190
+ } else {
191
+ var _document$sprites;
192
+ const setting = (_document$sprites = document.sprites) === null || _document$sprites === void 0 ? void 0 : _document$sprites[target.name];
193
+ assert(setting, `${blockPaletteFile} has no setting for sprite ${target.name}.`);
194
+ payload = {
195
+ formatVersion: 1,
196
+ groups: setting.groups
197
+ };
198
+ }
199
+ return `${target.isStage ? blockPaletteStageCommentHeader : blockPaletteSpriteCommentHeader}\n${JSON.stringify(payload)}${blockPaletteCommentMarker}`;
200
+ }
201
+ /**
202
+ * The canonical comment text for one sprite or the stage. Fails when the text is longer than
203
+ * 8000 characters, which Scratch 3 refuses to load.
204
+ */
205
+ function formatBlockPaletteComment(document, target) {
206
+ const text = canonicalCommentText(document, target);
207
+ const length = Array.from(text).length;
208
+ assert(length <= blockPaletteCommentMaxLength, `Block palette comment for ${target.isStage ? "the stage" : `sprite ${target.name}`} has ${length} characters; the limit is ${blockPaletteCommentMaxLength}.`);
209
+ return text;
210
+ }
211
+ function parseMarkedComment(comment, isStage) {
212
+ if (comment.extraText !== void 0) return {
213
+ ok: false,
214
+ reason: "the comment has extraText"
215
+ };
216
+ const markedLines = comment.text.split("\n").filter((line) => line.includes(markerToken));
217
+ if (markedLines.length !== 1) return {
218
+ ok: false,
219
+ reason: "the marker must appear on exactly one line"
220
+ };
221
+ const [line] = markedLines;
222
+ const json = line.slice(0, line.indexOf(markerToken)).trim();
223
+ let value;
224
+ try {
225
+ value = JSON.parse(json);
226
+ } catch (_unused) {
227
+ return {
228
+ ok: false,
229
+ reason: "the marked line is not valid JSON"
230
+ };
231
+ }
232
+ try {
233
+ assert(isRecord(value), "the JSON must be an object");
234
+ assertOnlyKeys(value, isStage ? [
235
+ "formatVersion",
236
+ "groups",
237
+ "order",
238
+ "sets"
239
+ ] : ["formatVersion", "groups"], "the JSON");
240
+ assert(value.formatVersion === 1, `unsupported formatVersion ${String(value.formatVersion)}`);
241
+ assert(isStage || value.groups !== void 0, "the JSON has no groups");
242
+ const parsed = {
243
+ order: value.order === void 0 ? void 0 : validateGroupList(value.order, "order"),
244
+ sets: value.sets === void 0 ? void 0 : validateSets(value.sets, "sets"),
245
+ stage: value.groups === void 0 ? void 0 : { groups: validateGroupList(value.groups, "groups") }
246
+ };
247
+ assert(parsed.order !== void 0 || parsed.sets !== void 0 || parsed.stage !== void 0, "the JSON has no settings");
248
+ return {
249
+ ok: true,
250
+ value: parsed
251
+ };
252
+ } catch (error) {
253
+ return {
254
+ ok: false,
255
+ reason: error instanceof Error ? error.message : String(error)
256
+ };
257
+ }
258
+ }
259
+ /**
260
+ * Move palette comments from an SB3 project into a `block-palette.json` document.
261
+ * The project is changed in place: each recognized comment keeps its ID, position, size,
262
+ * state and order, and its text becomes {@link blockPaletteCommentReference}.
263
+ */
264
+ function extractBlockPalette(project) {
265
+ const warnings = [];
266
+ const parts = {};
267
+ const sprites = [];
268
+ for (const target of targetComments(project, false)) {
269
+ const marked = Object.entries(target.comments).filter(([, comment]) => isMarkedComment(comment));
270
+ assert(Object.values(target.comments).filter(isReferenceComment).length === 0, `${target.isStage ? "The stage" : `Sprite ${target.name}`} has a comment whose text is reserved for block palette references: ${blockPaletteCommentReference}`);
271
+ assert(marked.length <= 1, `${target.isStage ? "The stage" : `Sprite ${target.name}`} has ${marked.length} block palette comments; only one is allowed.`);
272
+ if (marked.length === 0) continue;
273
+ const [[commentId, comment]] = marked;
274
+ const parsed = parseMarkedComment(comment, target.isStage);
275
+ if (!parsed.ok) {
276
+ warnings.push({
277
+ code: "block-palette-invalid",
278
+ commentId,
279
+ message: `Block palette comment ${commentId} on ${target.name} was kept as a plain comment and ignored: ${parsed.reason}.`,
280
+ target: target.name
281
+ });
282
+ continue;
283
+ }
284
+ if (target.isStage) Object.assign(parts, parsed.value);
285
+ else {
286
+ assert(!sprites.some(([name]) => name === target.name), `Duplicate sprite name with block palette settings: ${target.name}`);
287
+ sprites.push([target.name, parsed.value.stage]);
288
+ }
289
+ const canonicalText = canonicalCommentText(canonicalDocument(_objectSpread2(_objectSpread2({}, parts), {}, { sprites: Object.fromEntries(sprites) })), target);
290
+ if (comment.text !== canonicalText) warnings.push({
291
+ code: "block-palette-normalized",
292
+ commentId,
293
+ message: `Block palette comment ${commentId} on ${target.name} is not in the canonical form; it will be rewritten on build.`,
294
+ target: target.name
295
+ });
296
+ comment.text = blockPaletteCommentReference;
297
+ }
298
+ const document = canonicalDocument(_objectSpread2(_objectSpread2({}, parts), {}, { sprites: Object.fromEntries(sprites) }));
299
+ return {
300
+ document: hasBlockPaletteSettings(document) ? document : null,
301
+ warnings
302
+ };
303
+ }
304
+ /**
305
+ * Check that `project.source.json` and `block-palette.json` agree, and return the canonical
306
+ * comment text for each reference. `document` is null for source format 1.
307
+ */
308
+ function resolveBlockPaletteReferences(project, document) {
309
+ var _document$sprites2;
310
+ const resolved = [];
311
+ const targets = targetComments(project, document !== null);
312
+ if (document === null) {
313
+ for (const target of targets) assert(!Object.values(target.comments).some(isReferenceComment), `project.source.json refers to ${blockPaletteFile}, which requires SB3 source format 2.`);
314
+ return resolved;
315
+ }
316
+ const spriteNames = new Set(targets.filter(({ isStage }) => !isStage).map(({ name }) => name));
317
+ for (const name of Object.keys((_document$sprites2 = document.sprites) !== null && _document$sprites2 !== void 0 ? _document$sprites2 : {})) assert(spriteNames.has(name), `${blockPaletteFile} refers to an unknown sprite: ${name}`);
318
+ for (const target of targets) {
319
+ var _document$sprites3;
320
+ const label = target.isStage ? "The stage" : `Sprite ${target.name}`;
321
+ const references = Object.values(target.comments).filter(isReferenceComment);
322
+ const marked = Object.values(target.comments).filter(isMarkedComment);
323
+ const expected = target.isStage ? stageHasSettings(document) : ((_document$sprites3 = document.sprites) === null || _document$sprites3 === void 0 ? void 0 : _document$sprites3[target.name]) !== void 0;
324
+ assert(references.length <= 1, `${label} has ${references.length} block palette references; only one is allowed.`);
325
+ assert(references.length === 0 || marked.length === 0, `${label} has both a block palette reference and a block palette comment.`);
326
+ assert(references.length === (expected ? 1 : 0), expected ? `${label} has block palette settings in ${blockPaletteFile} but no comment that refers to it (${blockPaletteCommentReference}).` : `${label} has a block palette reference but no settings in ${blockPaletteFile}.`);
327
+ if (references.length === 1) resolved.push({
328
+ comment: references[0],
329
+ text: formatBlockPaletteComment(document, target)
330
+ });
331
+ }
332
+ return resolved;
333
+ }
334
+ /** Replace each reference comment in a cloned project with its canonical SB3 text. */
335
+ function applyBlockPaletteComments(project, document) {
336
+ for (const { comment, text } of resolveBlockPaletteReferences(project, document)) comment.text = text;
337
+ }
99
338
  // \0@oxc-project+runtime@0.156.0/helpers/esm/objectWithoutPropertiesLoose.js
100
339
  function _objectWithoutPropertiesLoose(r, e) {
101
340
  if (null == r) return {};
@@ -116,6 +355,48 @@ function _objectWithoutProperties(e, t) {
116
355
  }
117
356
  return i;
118
357
  }
358
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/asyncIterator.js
359
+ function _asyncIterator(r) {
360
+ var n, t, o, e = 2;
361
+ for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
362
+ if (t && null != (n = r[t])) return n.call(r);
363
+ if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
364
+ t = "@@asyncIterator", o = "@@iterator";
365
+ }
366
+ throw new TypeError("Object is not async iterable");
367
+ }
368
+ function AsyncFromSyncIterator(r) {
369
+ function AsyncFromSyncIteratorContinuation(r) {
370
+ if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object."));
371
+ var n = r.done;
372
+ return Promise.resolve(r.value).then(function(r) {
373
+ return {
374
+ value: r,
375
+ done: n
376
+ };
377
+ });
378
+ }
379
+ return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
380
+ this.s = r, this.n = r.next;
381
+ }, AsyncFromSyncIterator.prototype = {
382
+ s: null,
383
+ n: null,
384
+ next: function next() {
385
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
386
+ },
387
+ "return": function _return(r) {
388
+ var n = this.s["return"];
389
+ return void 0 === n ? Promise.resolve({
390
+ value: r,
391
+ done: !0
392
+ }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
393
+ },
394
+ "throw": function _throw(r) {
395
+ var n = this.s["throw"];
396
+ return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
397
+ }
398
+ }, new AsyncFromSyncIterator(r);
399
+ }
119
400
  // src/source.ts
120
401
  var _excluded = ["targets"];
121
402
  var _excluded2 = ["targets"];
@@ -123,6 +404,8 @@ var _excluded3 = ["targets"];
123
404
  var projectFile = "project.source.json";
124
405
  var manifestFile = "sb3-source.json";
125
406
  var extensionsFile = "embedded-extensions.json";
407
+ /** Block palette settings of source format 2. Format 1 folders have no such file. */
408
+ var paletteFile = blockPaletteFile;
126
409
  var embeddedReference = "embedded-extension:";
127
410
  var FolderError = class extends Error {
128
411
  constructor(code, detail) {
@@ -157,6 +440,34 @@ function parseProject(text) {
157
440
  if (stages !== 1) return unsupported("Expected one stage");
158
441
  return project;
159
442
  }
443
+ var palette = (action) => {
444
+ try {
445
+ return action();
446
+ } catch (error) {
447
+ if (error instanceof FolderError) throw error;
448
+ return unsupported(`Invalid block palette settings: ${error instanceof Error ? error.message : String(error)}`);
449
+ }
450
+ };
451
+ /** A copy of a folder project with each palette reference turned back into its comment text, as the VM loads it. */
452
+ var expandPalette = (project, document) => {
453
+ if (!document) return project;
454
+ const copy = structuredClone(project);
455
+ palette(() => applyBlockPaletteComments(copy, document));
456
+ return copy;
457
+ };
458
+ /**
459
+ * Moves palette comments from a project in the Editor's form into `block-palette.json` and returns the folder form
460
+ * of the project with the document, or a null document when no sprite or the stage has palette settings.
461
+ */
462
+ var collapsePalette = (project) => {
463
+ const copy = structuredClone(project);
464
+ const { document } = palette(() => extractBlockPalette(copy));
465
+ return {
466
+ project: copy,
467
+ document
468
+ };
469
+ };
470
+ var encodePalette = (document) => new TextEncoder().encode(serializeBlockPaletteDocument(document));
160
471
  var getFile = async (dir, name) => dir ? (await dir.getFileHandle(name)).getFile() : unsupported(`Missing folder for ${name}`);
161
472
  var fileVersion = (file) => `${file.size}:${file.lastModified}`;
162
473
  var fileBytes = async (file) => new Uint8Array(await file.arrayBuffer());
@@ -369,7 +680,15 @@ async function readFolder(directory, storage) {
369
680
  const project = parseProject(projectText);
370
681
  const manifest = readObject(decoder.decode(files.get(manifestFile)));
371
682
  const embedded = readObject(decoder.decode(files.get(extensionsFile)));
372
- if (manifest.formatVersion !== 1 || manifest.project !== "project.source.json" || manifest.embeddedExtensions !== "embedded-extensions.json" || manifest.assetsDirectory !== "assets" || !Array.isArray(manifest.archiveEntries)) return unsupported("Expected an sb3-toolchain v1 folder");
683
+ const formatVersion = manifest.formatVersion;
684
+ if (formatVersion !== 1 && formatVersion !== 2 || manifest.project !== "project.source.json" || manifest.embeddedExtensions !== "embedded-extensions.json" || manifest.assetsDirectory !== "assets" || !Array.isArray(manifest.archiveEntries) || (formatVersion === 1 ? manifest.blockPalette !== void 0 : manifest.blockPalette !== paletteFile)) return unsupported("Expected an sb3-toolchain v1 or v2 folder");
685
+ let paletteDocument = null;
686
+ if (formatVersion === 2) {
687
+ const [, paletteBytes] = await readEntry(directory, paletteFile);
688
+ files.set(paletteFile, paletteBytes);
689
+ paletteDocument = palette(() => validateBlockPaletteDocument(readObject(decoder.decode(paletteBytes))));
690
+ }
691
+ palette(() => resolveBlockPaletteReferences(project, paletteDocument));
373
692
  if (project.turboWarpPlus !== void 0) return unsupported("Plus extension manifests are not supported in project folders");
374
693
  const extensionManifest = validateExtensions(project, embedded);
375
694
  const references = projectAssets(project);
@@ -381,7 +700,8 @@ async function readFolder(directory, storage) {
381
700
  if (!sameNames(await readNames(assets), expected) || !sameNames(await readNames(extensions), scripts)) return unsupported("Unexpected or missing source files");
382
701
  const bytes = new Map(await Promise.all([...expected].map((name) => readEntry(assets, name, "assets/"))));
383
702
  const extensionBytes = new Map(await Promise.all(scripts.map((name) => readEntry(extensions, name, "extensions/"))));
384
- const loadText = extensionManifest.extensions.length ? JSON.stringify(_objectSpread2(_objectSpread2({}, project), {}, { extensionURLs: _objectSpread2(_objectSpread2({}, extensionURLs(project)), Object.fromEntries(extensionManifest.extensions.map((entry) => [entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`))]))) })) : projectText;
703
+ const loaded = expandPalette(project, paletteDocument);
704
+ const loadText = extensionManifest.extensions.length ? JSON.stringify(_objectSpread2(_objectSpread2({}, loaded), {}, { extensionURLs: _objectSpread2(_objectSpread2({}, extensionURLs(project)), Object.fromEntries(extensionManifest.extensions.map((entry) => [entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`))]))) })) : paletteDocument ? JSON.stringify(loaded) : projectText;
385
705
  const storageAssets = /* @__PURE__ */ new Map();
386
706
  for (const [name, kind] of references) {
387
707
  const [id, format] = name.split(".");
@@ -399,7 +719,8 @@ async function readFolder(directory, storage) {
399
719
  project,
400
720
  loadText,
401
721
  storageAssets,
402
- embedded: extensionManifest
722
+ embedded: extensionManifest,
723
+ palette: paletteDocument
403
724
  };
404
725
  }
405
726
  var sameBytes = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
@@ -414,7 +735,11 @@ async function readFolderUpdate(source, previous) {
414
735
  const [assetNames, extensionNames] = await Promise.all([readNames(assets), readNames(extensions)]);
415
736
  if (!sameNames(assetNames, source.bytes.keys()) || !sameNames(extensionNames, source.extensionBytes.keys())) return "structure";
416
737
  if ((await Promise.all([
417
- ...["sb3-source.json", "embedded-extensions.json"].map(async (name) => fileVersion(await getFile(directory, name)) === versions.get(name)),
738
+ ...[
739
+ "sb3-source.json",
740
+ "embedded-extensions.json",
741
+ ...source.files.has(paletteFile) ? [paletteFile] : []
742
+ ].map(async (name) => fileVersion(await getFile(directory, name)) === versions.get(name)),
418
743
  ...[...assetNames].map(async (name) => fileVersion(await getFile(assets, name)) === versions.get(`assets/${name}`)),
419
744
  ...[...extensionNames].map(async (name) => fileVersion(await getFile(extensions, name)) === versions.get(`extensions/${name}`))
420
745
  ])).includes(false)) return "structure";
@@ -553,6 +878,7 @@ var manifests = /* @__PURE__ */ new Set([
553
878
  manifestFile,
554
879
  extensionsFile
555
880
  ]);
881
+ var optionalManifests = /* @__PURE__ */ new Set([paletteFile]);
556
882
  var sourceDirectories = ["assets", "extensions"];
557
883
  var sourcePath = /^(?:assets\/[a-f0-9]{32}\.[A-Za-z0-9]+|extensions\/[A-Za-z0-9._-]+\.(?:js|manifest\.json))$/u;
558
884
  function missing(error) {
@@ -607,7 +933,7 @@ async function directoryEntries(directory) {
607
933
  /** Create and validate a project-folder snapshot in a directory chosen by the user. */
608
934
  async function createProjectFolder({ directory, files, storage, overwrite = false, current = () => true }) {
609
935
  for (const filename of manifests) if (!files.has(filename)) return unsupported(`Missing ${filename}`);
610
- for (const [filename, bytes] of files) if (!manifests.has(filename) && !sourcePath.test(filename) || !(bytes instanceof Uint8Array)) return unsupported(`Invalid project folder entry: ${filename}`);
936
+ for (const [filename, bytes] of files) if (!manifests.has(filename) && !optionalManifests.has(filename) && !sourcePath.test(filename) || !(bytes instanceof Uint8Array)) return unsupported(`Invalid project folder entry: ${filename}`);
611
937
  const assertCurrent = () => {
612
938
  if (!current()) throw new FolderError("conflict", "The project changed before the folder was saved");
613
939
  };
@@ -690,6 +1016,13 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
690
1016
  entries: children
691
1017
  });
692
1018
  }
1019
+ for (const name of optionalManifests) {
1020
+ const entry = existing.get(name);
1021
+ if (entry && !files.has(name)) {
1022
+ await remove(directory, entry);
1023
+ existing.delete(name);
1024
+ }
1025
+ }
693
1026
  const entries = [...files].sort(([a], [b]) => Number(manifests.has(a)) - Number(manifests.has(b)) || Number(a === "project.source.json") - Number(b === "project.source.json"));
694
1027
  for (const [filename, bytes] of entries) {
695
1028
  var _subdirectory$handle, _subdirectory$entries;
@@ -732,6 +1065,38 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
732
1065
  throw error;
733
1066
  }
734
1067
  }
1068
+ // src/explorer-state.ts
1069
+ /** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
1070
+ var editorDirectory = ".tw-plus";
1071
+ /** The screen state of the Editor, inside `editorDirectory`. */
1072
+ var screenStateFile = "workspace.json";
1073
+ var hiddenEntry = (name) => [".git", editorDirectory].includes(name.toLowerCase());
1074
+ var limit = 1e3;
1075
+ var states = /* @__PURE__ */ new WeakMap();
1076
+ var listeners = /* @__PURE__ */ new WeakMap();
1077
+ var validPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 1024 && value.split("/").every((part) => part && part !== "." && part !== ".." && !hiddenEntry(part) && !/[\\\u0000]/u.test(part));
1078
+ /** Read a tree state saved in a file, keeping only well-formed paths. */
1079
+ function parseExplorerState(value) {
1080
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return;
1081
+ const { expanded, selected } = value;
1082
+ if (!Array.isArray(expanded)) return;
1083
+ return _objectSpread2({ expanded: [...new Set(expanded.filter(validPath))].slice(0, limit) }, validPath(selected) && { selected });
1084
+ }
1085
+ var readExplorerState = (directory) => states.get(directory);
1086
+ /** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
1087
+ function writeExplorerState(directory, state, notify = false) {
1088
+ var _listeners$get;
1089
+ states.set(directory, state);
1090
+ if (notify) for (const listener of [...(_listeners$get = listeners.get(directory)) !== null && _listeners$get !== void 0 ? _listeners$get : []]) listener(state);
1091
+ }
1092
+ function subscribeExplorerState(directory, listener) {
1093
+ let set = listeners.get(directory);
1094
+ if (!set) listeners.set(directory, set = /* @__PURE__ */ new Set());
1095
+ set.add(listener);
1096
+ return () => {
1097
+ set.delete(listener);
1098
+ };
1099
+ }
735
1100
  // src/folder-registry.ts
736
1101
  var folders = /* @__PURE__ */ new WeakMap();
737
1102
  var registrations = /* @__PURE__ */ new Set();
@@ -770,4 +1135,4 @@ function followProjectFolder(vm, listener) {
770
1135
  unsubscribe();
771
1136
  };
772
1137
  }
773
- export { unsupported as C, _asyncIterator as E, sameBytes as S, _objectSpread2 as T, projectAssets as _, projectFolderOverwriteWarning as a, readFolder as b, assetKey as c, extensionsFile as d, fileVersion as f, planExtensionSave as g, parseProject as h, isProjectFolderEmpty as i, assetTypeFor as l, manifestFile as m, registerFolder as n, FolderError as o, isObject as p, createProjectFolder as r, assertFolderUnchanged as s, followProjectFolder as t, equal as u, projectChanges as v, _objectWithoutProperties as w, readFolderUpdate as x, projectFile as y };
1138
+ export { projectFile as A, isObject as C, planExtensionSave as D, parseProject as E, _asyncIterator as F, _objectWithoutProperties as I, _objectSpread2 as L, readFolderUpdate as M, sameBytes as N, projectAssets as O, unsupported as P, fileVersion as S, paletteFile as T, collapsePalette as _, parseExplorerState as a, expandPalette as b, subscribeExplorerState as c, isProjectFolderEmpty as d, projectFolderOverwriteWarning as f, assetTypeFor as g, assetKey as h, hiddenEntry as i, readFolder as j, projectChanges as k, writeExplorerState as l, assertFolderUnchanged as m, registerFolder as n, readExplorerState as o, FolderError as p, editorDirectory as r, screenStateFile as s, followProjectFolder as t, createProjectFolder as u, encodePalette as v, manifestFile as w, extensionsFile as x, equal as y };
package/dist/source.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { BlockPaletteDocument } from '@kubohiroya/sb3-toolchain/browser';
1
2
  export type Json = null | boolean | number | string | Json[] | {
2
3
  [key: string]: Json;
3
4
  };
@@ -14,6 +15,8 @@ type Target = JsonObject & {
14
15
  export declare const projectFile = "project.source.json";
15
16
  export declare const manifestFile = "sb3-source.json";
16
17
  export declare const extensionsFile = "embedded-extensions.json";
18
+ /** Block palette settings of source format 2. Format 1 folders have no such file. */
19
+ export declare const paletteFile = "block-palette.json";
17
20
  export declare class FolderError extends Error {
18
21
  code: 'conflict' | 'unsupported';
19
22
  constructor(code: FolderError['code'], detail?: string);
@@ -53,7 +56,20 @@ export type FolderSource = FolderFiles & {
53
56
  loadText: string;
54
57
  storageAssets: Map<string, Asset>;
55
58
  embedded: ExtensionManifest;
59
+ /** The folder's `block-palette.json`, or null for a format 1 folder. */
60
+ palette: BlockPaletteDocument | null;
56
61
  };
62
+ /** A copy of a folder project with each palette reference turned back into its comment text, as the VM loads it. */
63
+ export declare const expandPalette: (project: Project, document: BlockPaletteDocument | null) => Project;
64
+ /**
65
+ * Moves palette comments from a project in the Editor's form into `block-palette.json` and returns the folder form
66
+ * of the project with the document, or a null document when no sprite or the stage has palette settings.
67
+ */
68
+ export declare const collapsePalette: (project: Project) => {
69
+ project: Project;
70
+ document: BlockPaletteDocument | null;
71
+ };
72
+ export declare const encodePalette: (document: BlockPaletteDocument) => Uint8Array<ArrayBuffer>;
57
73
  export declare const fileVersion: (file: File) => string;
58
74
  export type AssetKind = 'costumes' | 'sounds' | 'fonts';
59
75
  export declare const assetTypeFor: (storage: Storage, kind: AssetKind, format: string) => AssetType;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.9.3",
3
+ "version": "0.11.0",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -55,7 +55,7 @@
55
55
  "@codemirror/view": "6.43.15",
56
56
  "@headless-tree/core": "1.8.0",
57
57
  "@headless-tree/react": "1.8.0",
58
- "@kubohiroya/sb3-toolchain": "0.22.0",
58
+ "@kubohiroya/sb3-toolchain": "0.25.1",
59
59
  "@kubohiroya/turbowarp-plus-editor-test-runtime": "0.1.0",
60
60
  "@lezer/highlight": "1.2.5",
61
61
  "@playwright/test": "1.64.1",
@@ -1,7 +1,9 @@
1
- import {extensionsFile, fileVersion, FolderError, manifestFile, projectFile, readFolder, sameBytes, unsupported} from './source.js';
1
+ import {extensionsFile, fileVersion, FolderError, manifestFile, paletteFile, projectFile, readFolder, sameBytes, unsupported} from './source.js';
2
2
  import type {Storage} from './source.js';
3
3
 
4
4
  const manifests = new Set<string>([projectFile, manifestFile, extensionsFile]);
5
+ // Present only in a format 2 snapshot; readFolder checks that the manifest agrees.
6
+ const optionalManifests = new Set<string>([paletteFile]);
5
7
  const sourceDirectories = ['assets', 'extensions'];
6
8
  const sourcePath = /^(?:assets\/[a-f0-9]{32}\.[A-Za-z0-9]+|extensions\/[A-Za-z0-9._-]+\.(?:js|manifest\.json))$/u;
7
9
 
@@ -39,7 +41,7 @@ export async function createProjectFolder({directory, files, storage, overwrite
39
41
  if (!files.has(filename)) return unsupported(`Missing ${filename}`);
40
42
  }
41
43
  for (const [filename, bytes] of files) {
42
- if ((!manifests.has(filename) && !sourcePath.test(filename)) || !(bytes instanceof Uint8Array)) {
44
+ if ((!manifests.has(filename) && !optionalManifests.has(filename) && !sourcePath.test(filename)) || !(bytes instanceof Uint8Array)) {
43
45
  return unsupported(`Invalid project folder entry: ${filename}`);
44
46
  }
45
47
  }
@@ -124,6 +126,14 @@ export async function createProjectFolder({directory, files, storage, overwrite
124
126
  }
125
127
  directories.set(name, {handle, entries: children});
126
128
  }
129
+ // A format 1 snapshot over a format 2 folder must not leave the old palette settings behind.
130
+ for (const name of optionalManifests) {
131
+ const entry = existing.get(name);
132
+ if (entry && !files.has(name)) {
133
+ await remove(directory, entry);
134
+ existing.delete(name);
135
+ }
136
+ }
127
137
  // Publish the project JSON last, after the files it refers to.
128
138
  const entries = [...files].sort(([a], [b]) => Number(manifests.has(a)) - Number(manifests.has(b)) ||
129
139
  Number(a === projectFile) - Number(b === projectFile));
@@ -1,3 +1,4 @@
1
+ import {hiddenEntry} from './explorer-state.js';
1
2
  type DirectoryEntries = FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>};
2
3
 
3
4
  export class ExplorerFileError extends Error {
@@ -11,7 +12,7 @@ export function parentPath(path: string) {
11
12
  }
12
13
 
13
14
  function validateName(name: string) {
14
- if (!name.trim() || name === '.' || name === '..' || name.toLowerCase() === '.git' || /[\\/\u0000]/u.test(name)) {
15
+ if (!name.trim() || name === '.' || name === '..' || hiddenEntry(name) || /[\\/\u0000]/u.test(name)) {
15
16
  throw new ExplorerFileError('invalidName');
16
17
  }
17
18
  }