@kubohiroya/sb3-toolchain 0.24.0 → 0.25.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.25.0 - 2026-11-16
4
+
5
+ - ブロックパレットの設定を保つ展開ソース形式 v2 を追加した。設定は作品フォルダでは `block-palette.json` に、SB3 ではスプライト・背景ごとのコメントに入る。設定のない作品は今までどおり v1 で書く(#90)。
6
+ - 読み手は v1 と v2 を受け付け、それ以外の版は出力を変えずに拒否する。
7
+
3
8
  ## 0.24.0 - 2026-11-12
4
9
 
5
10
  - ブラウザーから SB3 を v1 作品フォルダのファイルに展開・検証する API を追加した。
package/README.ja.md CHANGED
@@ -34,7 +34,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
34
34
  再現可能なインストールのため、検証済みのnpmバージョンを固定します。
35
35
 
36
36
  ```bash
37
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.24.0
37
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.25.0
38
38
  ```
39
39
 
40
40
  ## クイックスタート
@@ -161,6 +161,7 @@ await unbundleSb3({
161
161
 
162
162
  - [`docs/ja/workflows.md`](docs/ja/workflows.md): SB3ソースと機能拡張を管理するワークフロー
163
163
  - [`docs/ja/source-format-v1.md`](docs/ja/source-format-v1.md): 展開ソース形式と決定的出力
164
+ - [`docs/ja/source-format-v2.md`](docs/ja/source-format-v2.md): ブロックパレットの設定を足した形式 v2
164
165
  - [`docs/ja/project-asset-additions.md`](docs/ja/project-asset-additions.md): `--project-assets`のJSON/YAML、backdrop、編集/strict lock仕様
165
166
  - [`docs/ja/extension-id-migration.md`](docs/ja/extension-id-migration.md): プロジェクトで使用中の機能拡張IDの移行
166
167
  - [`docs/ja/extension-api-compatibility.md`](docs/ja/extension-api-compatibility.md): 機能拡張更新時の任意の静的API互換性検査
package/README.md CHANGED
@@ -35,7 +35,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
35
35
  Pin the verified npm version for reproducible installation.
36
36
 
37
37
  ```bash
38
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.24.0
38
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.25.0
39
39
  ```
40
40
 
41
41
  ## Quick start
@@ -165,6 +165,7 @@ The browser API reports and omits unreferenced assets with hash-based filenames
165
165
 
166
166
  - [`docs/workflows.md`](docs/workflows.md): SB3 source and extension management workflows
167
167
  - [`docs/source-format-v1.md`](docs/source-format-v1.md): expanded source format and deterministic output
168
+ - [`docs/source-format-v2.md`](docs/source-format-v2.md): format v2, which adds block palette settings
168
169
  - [`docs/project-asset-additions.md`](docs/project-asset-additions.md): JSON/YAML `--project-assets`, backdrops, and editable or strict locks
169
170
  - [`docs/extension-id-migration.md`](docs/extension-id-migration.md): migration of extension IDs already used by a project
170
171
  - [`docs/extension-api-compatibility.md`](docs/extension-api-compatibility.md) ([日本語](docs/ja/extension-api-compatibility.md)): opt-in static API compatibility checks for extension updates
@@ -0,0 +1,60 @@
1
+ import { ProjectJson, UnknownRecord } from './types';
2
+ export declare const blockPaletteFormatVersion = 1;
3
+ export declare const blockPaletteFile = "block-palette.json";
4
+ export declare const blockPaletteCommentMarker = " // _twplus_palette_";
5
+ export declare const blockPaletteCommentReference = "block-palette:block-palette.json";
6
+ export declare const blockPaletteCommentMaxLength = 8000;
7
+ export declare const blockPaletteSpriteCommentHeader: string;
8
+ export declare const blockPaletteStageCommentHeader: string;
9
+ export interface BlockPaletteTargetSetting {
10
+ groups: string[];
11
+ }
12
+ export interface BlockPaletteSet {
13
+ name: string;
14
+ groups: string[];
15
+ }
16
+ export interface BlockPaletteDocument {
17
+ formatVersion: 1;
18
+ order?: string[];
19
+ sets?: Record<string, BlockPaletteSet>;
20
+ stage?: BlockPaletteTargetSetting;
21
+ sprites?: Record<string, BlockPaletteTargetSetting>;
22
+ }
23
+ export type BlockPaletteWarningCode = 'block-palette-normalized' | 'block-palette-invalid';
24
+ export interface BlockPaletteWarning {
25
+ code: BlockPaletteWarningCode;
26
+ commentId: string;
27
+ message: string;
28
+ target: string;
29
+ }
30
+ export declare function hasBlockPaletteSettings(document: BlockPaletteDocument): boolean;
31
+ /** Validate the shape of `block-palette.json` without looking at the project. */
32
+ export declare function validateBlockPaletteDocument(value: unknown): BlockPaletteDocument;
33
+ export declare function serializeBlockPaletteDocument(document: BlockPaletteDocument): string;
34
+ /**
35
+ * The canonical comment text for one sprite or the stage. Fails when the text is longer than
36
+ * 8000 characters, which Scratch 3 refuses to load.
37
+ */
38
+ export declare function formatBlockPaletteComment(document: BlockPaletteDocument, target: {
39
+ isStage: boolean;
40
+ name: string;
41
+ }): string;
42
+ /**
43
+ * Move palette comments from an SB3 project into a `block-palette.json` document.
44
+ * The project is changed in place: each recognized comment keeps its ID, position, size,
45
+ * state and order, and its text becomes {@link blockPaletteCommentReference}.
46
+ */
47
+ export declare function extractBlockPalette(project: ProjectJson): {
48
+ document: BlockPaletteDocument | null;
49
+ warnings: BlockPaletteWarning[];
50
+ };
51
+ /**
52
+ * Check that `project.source.json` and `block-palette.json` agree, and return the canonical
53
+ * comment text for each reference. `document` is null for source format 1.
54
+ */
55
+ export declare function resolveBlockPaletteReferences(project: ProjectJson, document: BlockPaletteDocument | null): {
56
+ comment: UnknownRecord;
57
+ text: string;
58
+ }[];
59
+ /** Replace each reference comment in a cloned project with its canonical SB3 text. */
60
+ export declare function applyBlockPaletteComments(project: ProjectJson, document: BlockPaletteDocument | null): void;
@@ -0,0 +1,295 @@
1
+ import { assert } from "./assert.js";
2
+ //#region src/block-palette.ts
3
+ /**
4
+ * Block palette settings (source format 2).
5
+ *
6
+ * In an SB3, each sprite or stage carries at most one comment whose second line ends with
7
+ * {@link blockPaletteCommentMarker}. In a source folder, those comments live in
8
+ * `block-palette.json`, and the comment text in `project.source.json` becomes
9
+ * {@link blockPaletteCommentReference}. This module is shared by the Node and browser builds,
10
+ * so it must not import Node built-ins.
11
+ */
12
+ var blockPaletteFormatVersion = 1;
13
+ var blockPaletteFile = "block-palette.json";
14
+ var blockPaletteCommentMarker = " // _twplus_palette_";
15
+ var blockPaletteCommentReference = `block-palette:${blockPaletteFile}`;
16
+ var blockPaletteCommentMaxLength = 8e3;
17
+ var blockPaletteSpriteCommentHeader = "TurboWarp Plus Editor block palette for this sprite. You can delete this comment to reset the palette.";
18
+ var blockPaletteStageCommentHeader = "TurboWarp Plus Editor block palette for the stage. You can delete this comment to reset the palette.";
19
+ var markerToken = "// _twplus_palette_";
20
+ var groupIdPattern = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9_-]+)?$/u;
21
+ var setIdPattern = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
22
+ function isRecord(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+ function assertOnlyKeys(value, allowed, description) {
26
+ for (const key of Object.keys(value)) assert(allowed.includes(key), `${description} has an unknown key: ${key}`);
27
+ }
28
+ function validateGroupList(value, description) {
29
+ assert(Array.isArray(value), `${description} must be an array of block group IDs.`);
30
+ const seen = /* @__PURE__ */ new Set();
31
+ for (const group of value) {
32
+ assert(typeof group === "string" && groupIdPattern.test(group), `${description} contains an invalid block group ID: ${JSON.stringify(group)}`);
33
+ assert(!seen.has(group), `${description} contains a duplicate block group ID: ${group}`);
34
+ seen.add(group);
35
+ }
36
+ return [...seen];
37
+ }
38
+ function validateTargetSetting(value, description) {
39
+ assert(isRecord(value), `${description} must be an object.`);
40
+ assertOnlyKeys(value, ["groups"], description);
41
+ return { groups: validateGroupList(value.groups, `${description} groups`) };
42
+ }
43
+ function validateSets(value, description) {
44
+ assert(isRecord(value), `${description} must be an object.`);
45
+ return Object.fromEntries(Object.entries(value).map(([setId, set]) => {
46
+ assert(setIdPattern.test(setId), `${description} has an invalid set ID: ${setId}`);
47
+ const setDescription = `${description}.${setId}`;
48
+ assert(isRecord(set), `${setDescription} must be an object.`);
49
+ assertOnlyKeys(set, ["name", "groups"], setDescription);
50
+ assert(typeof set.name === "string" && set.name.length > 0, `${setDescription} name must be a non-empty string.`);
51
+ return [setId, {
52
+ name: set.name,
53
+ groups: validateGroupList(set.groups, `${setDescription} groups`)
54
+ }];
55
+ }));
56
+ }
57
+ function canonicalDocument(parts) {
58
+ const document = { formatVersion: 1 };
59
+ if (parts.order !== void 0) document.order = parts.order;
60
+ if (parts.sets !== void 0) document.sets = parts.sets;
61
+ if (parts.stage !== void 0) document.stage = parts.stage;
62
+ if (parts.sprites !== void 0 && Object.keys(parts.sprites).length > 0) document.sprites = parts.sprites;
63
+ return document;
64
+ }
65
+ function hasBlockPaletteSettings(document) {
66
+ return document.order !== void 0 || document.sets !== void 0 || document.stage !== void 0 || document.sprites !== void 0 && Object.keys(document.sprites).length > 0;
67
+ }
68
+ function stageHasSettings(document) {
69
+ return document.order !== void 0 || document.sets !== void 0 || document.stage !== void 0;
70
+ }
71
+ /** Validate the shape of `block-palette.json` without looking at the project. */
72
+ function validateBlockPaletteDocument(value) {
73
+ const description = blockPaletteFile;
74
+ assert(isRecord(value), `${description} must contain an object.`);
75
+ assertOnlyKeys(value, [
76
+ "formatVersion",
77
+ "order",
78
+ "sets",
79
+ "stage",
80
+ "sprites"
81
+ ], description);
82
+ assert(value.formatVersion === 1, `Unsupported ${description} formatVersion: ${String(value.formatVersion)}`);
83
+ let sprites;
84
+ if (value.sprites !== void 0) {
85
+ assert(isRecord(value.sprites), `${description} sprites must be an object.`);
86
+ assert(Object.keys(value.sprites).length > 0, `${description} sprites must be omitted when it has no sprites.`);
87
+ sprites = Object.fromEntries(Object.entries(value.sprites).map(([name, setting]) => [name, validateTargetSetting(setting, `${description} sprites.${name}`)]));
88
+ }
89
+ const document = canonicalDocument({
90
+ order: value.order === void 0 ? void 0 : validateGroupList(value.order, "order"),
91
+ sets: value.sets === void 0 ? void 0 : validateSets(value.sets, `${description} sets`),
92
+ stage: value.stage === void 0 ? void 0 : validateTargetSetting(value.stage, `${description} stage`),
93
+ sprites
94
+ });
95
+ assert(hasBlockPaletteSettings(document), `${description} has no settings; remove it and use SB3 source format 1.`);
96
+ return document;
97
+ }
98
+ function serializeBlockPaletteDocument(document) {
99
+ return `${JSON.stringify(canonicalDocument(document), null, 2)}\n`;
100
+ }
101
+ /**
102
+ * List each target's comments. In strict mode, a malformed target or comment is an error;
103
+ * otherwise it is skipped so unpacking stays as permissive as it was in source format 1.
104
+ */
105
+ function targetComments(project, strict = true) {
106
+ if (!strict && !Array.isArray(project.targets)) return [];
107
+ assert(Array.isArray(project.targets), "Project targets must be an array.");
108
+ const targets = [];
109
+ for (const [index, target] of project.targets.entries()) {
110
+ if (!strict && !isRecord(target)) continue;
111
+ assert(isRecord(target), `Project target ${index} must be an object.`);
112
+ const comments = target.comments ?? {};
113
+ if (!strict && !isRecord(comments)) continue;
114
+ assert(isRecord(comments), `Project target ${index} comments must be an object.`);
115
+ const records = Object.fromEntries(Object.entries(comments).filter(([id, comment]) => {
116
+ assert(!strict || isRecord(comment), `Project target ${index} comment ${id} must be an object.`);
117
+ return isRecord(comment);
118
+ }));
119
+ targets.push({
120
+ comments: records,
121
+ isStage: target.isStage === true,
122
+ name: typeof target.name === "string" ? target.name : String(index)
123
+ });
124
+ }
125
+ return targets;
126
+ }
127
+ function isMarkedComment(comment) {
128
+ return typeof comment.text === "string" && comment.text.includes(markerToken);
129
+ }
130
+ function isReferenceComment(comment) {
131
+ return comment.text === blockPaletteCommentReference;
132
+ }
133
+ function canonicalCommentText(document, target) {
134
+ let payload;
135
+ if (target.isStage) {
136
+ payload = { formatVersion: 1 };
137
+ if (document.stage) payload.groups = document.stage.groups;
138
+ if (document.order) payload.order = document.order;
139
+ if (document.sets) payload.sets = document.sets;
140
+ } else {
141
+ const setting = document.sprites?.[target.name];
142
+ assert(setting, `${blockPaletteFile} has no setting for sprite ${target.name}.`);
143
+ payload = {
144
+ formatVersion: 1,
145
+ groups: setting.groups
146
+ };
147
+ }
148
+ return `${target.isStage ? blockPaletteStageCommentHeader : blockPaletteSpriteCommentHeader}\n${JSON.stringify(payload)}${blockPaletteCommentMarker}`;
149
+ }
150
+ /**
151
+ * The canonical comment text for one sprite or the stage. Fails when the text is longer than
152
+ * 8000 characters, which Scratch 3 refuses to load.
153
+ */
154
+ function formatBlockPaletteComment(document, target) {
155
+ const text = canonicalCommentText(document, target);
156
+ const length = Array.from(text).length;
157
+ assert(length <= blockPaletteCommentMaxLength, `Block palette comment for ${target.isStage ? "the stage" : `sprite ${target.name}`} has ${length} characters; the limit is ${blockPaletteCommentMaxLength}.`);
158
+ return text;
159
+ }
160
+ function parseMarkedComment(comment, isStage) {
161
+ if (comment.extraText !== void 0) return {
162
+ ok: false,
163
+ reason: "the comment has extraText"
164
+ };
165
+ const markedLines = comment.text.split("\n").filter((line) => line.includes(markerToken));
166
+ if (markedLines.length !== 1) return {
167
+ ok: false,
168
+ reason: "the marker must appear on exactly one line"
169
+ };
170
+ const [line] = markedLines;
171
+ const json = line.slice(0, line.indexOf(markerToken)).trim();
172
+ let value;
173
+ try {
174
+ value = JSON.parse(json);
175
+ } catch {
176
+ return {
177
+ ok: false,
178
+ reason: "the marked line is not valid JSON"
179
+ };
180
+ }
181
+ try {
182
+ assert(isRecord(value), "the JSON must be an object");
183
+ assertOnlyKeys(value, isStage ? [
184
+ "formatVersion",
185
+ "groups",
186
+ "order",
187
+ "sets"
188
+ ] : ["formatVersion", "groups"], "the JSON");
189
+ assert(value.formatVersion === 1, `unsupported formatVersion ${String(value.formatVersion)}`);
190
+ assert(isStage || value.groups !== void 0, "the JSON has no groups");
191
+ const parsed = {
192
+ order: value.order === void 0 ? void 0 : validateGroupList(value.order, "order"),
193
+ sets: value.sets === void 0 ? void 0 : validateSets(value.sets, "sets"),
194
+ stage: value.groups === void 0 ? void 0 : { groups: validateGroupList(value.groups, "groups") }
195
+ };
196
+ assert(parsed.order !== void 0 || parsed.sets !== void 0 || parsed.stage !== void 0, "the JSON has no settings");
197
+ return {
198
+ ok: true,
199
+ value: parsed
200
+ };
201
+ } catch (error) {
202
+ return {
203
+ ok: false,
204
+ reason: error instanceof Error ? error.message : String(error)
205
+ };
206
+ }
207
+ }
208
+ /**
209
+ * Move palette comments from an SB3 project into a `block-palette.json` document.
210
+ * The project is changed in place: each recognized comment keeps its ID, position, size,
211
+ * state and order, and its text becomes {@link blockPaletteCommentReference}.
212
+ */
213
+ function extractBlockPalette(project) {
214
+ const warnings = [];
215
+ const parts = {};
216
+ const sprites = [];
217
+ for (const target of targetComments(project, false)) {
218
+ const marked = Object.entries(target.comments).filter(([, comment]) => isMarkedComment(comment));
219
+ const references = Object.values(target.comments).filter(isReferenceComment);
220
+ assert(references.length === 0, `${target.isStage ? "The stage" : `Sprite ${target.name}`} has a comment whose text is reserved for block palette references: ${blockPaletteCommentReference}`);
221
+ assert(marked.length <= 1, `${target.isStage ? "The stage" : `Sprite ${target.name}`} has ${marked.length} block palette comments; only one is allowed.`);
222
+ if (marked.length === 0) continue;
223
+ const [[commentId, comment]] = marked;
224
+ const parsed = parseMarkedComment(comment, target.isStage);
225
+ if (!parsed.ok) {
226
+ warnings.push({
227
+ code: "block-palette-invalid",
228
+ commentId,
229
+ message: `Block palette comment ${commentId} on ${target.name} was kept as a plain comment and ignored: ${parsed.reason}.`,
230
+ target: target.name
231
+ });
232
+ continue;
233
+ }
234
+ if (target.isStage) Object.assign(parts, parsed.value);
235
+ else {
236
+ assert(!sprites.some(([name]) => name === target.name), `Duplicate sprite name with block palette settings: ${target.name}`);
237
+ sprites.push([target.name, parsed.value.stage]);
238
+ }
239
+ const canonicalText = canonicalCommentText(canonicalDocument({
240
+ ...parts,
241
+ sprites: Object.fromEntries(sprites)
242
+ }), target);
243
+ if (comment.text !== canonicalText) warnings.push({
244
+ code: "block-palette-normalized",
245
+ commentId,
246
+ message: `Block palette comment ${commentId} on ${target.name} is not in the canonical form; it will be rewritten on build.`,
247
+ target: target.name
248
+ });
249
+ comment.text = blockPaletteCommentReference;
250
+ }
251
+ const document = canonicalDocument({
252
+ ...parts,
253
+ sprites: Object.fromEntries(sprites)
254
+ });
255
+ return {
256
+ document: hasBlockPaletteSettings(document) ? document : null,
257
+ warnings
258
+ };
259
+ }
260
+ /**
261
+ * Check that `project.source.json` and `block-palette.json` agree, and return the canonical
262
+ * comment text for each reference. `document` is null for source format 1.
263
+ */
264
+ function resolveBlockPaletteReferences(project, document) {
265
+ const resolved = [];
266
+ const targets = targetComments(project, document !== null);
267
+ if (document === null) {
268
+ for (const target of targets) assert(!Object.values(target.comments).some(isReferenceComment), `project.source.json refers to ${blockPaletteFile}, which requires SB3 source format 2.`);
269
+ return resolved;
270
+ }
271
+ const spriteNames = new Set(targets.filter(({ isStage }) => !isStage).map(({ name }) => name));
272
+ for (const name of Object.keys(document.sprites ?? {})) assert(spriteNames.has(name), `${blockPaletteFile} refers to an unknown sprite: ${name}`);
273
+ for (const target of targets) {
274
+ const label = target.isStage ? "The stage" : `Sprite ${target.name}`;
275
+ const references = Object.values(target.comments).filter(isReferenceComment);
276
+ const marked = Object.values(target.comments).filter(isMarkedComment);
277
+ const expected = target.isStage ? stageHasSettings(document) : document.sprites?.[target.name] !== void 0;
278
+ assert(references.length <= 1, `${label} has ${references.length} block palette references; only one is allowed.`);
279
+ assert(references.length === 0 || marked.length === 0, `${label} has both a block palette reference and a block palette comment.`);
280
+ 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}.`);
281
+ if (references.length === 1) resolved.push({
282
+ comment: references[0],
283
+ text: formatBlockPaletteComment(document, target)
284
+ });
285
+ }
286
+ return resolved;
287
+ }
288
+ /** Replace each reference comment in a cloned project with its canonical SB3 text. */
289
+ function applyBlockPaletteComments(project, document) {
290
+ for (const { comment, text } of resolveBlockPaletteReferences(project, document)) comment.text = text;
291
+ }
292
+ //#endregion
293
+ export { applyBlockPaletteComments, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, extractBlockPalette, formatBlockPaletteComment, hasBlockPaletteSettings, resolveBlockPaletteReferences, serializeBlockPaletteDocument, validateBlockPaletteDocument };
294
+
295
+ //# sourceMappingURL=block-palette.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-palette.js","names":[],"sources":["../src/block-palette.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\n/**\n * Block palette settings (source format 2).\n *\n * In an SB3, each sprite or stage carries at most one comment whose second line ends with\n * {@link blockPaletteCommentMarker}. In a source folder, those comments live in\n * `block-palette.json`, and the comment text in `project.source.json` becomes\n * {@link blockPaletteCommentReference}. This module is shared by the Node and browser builds,\n * so it must not import Node built-ins.\n */\n\nimport {assert} from './assert';\nimport type {ProjectJson, UnknownRecord} from './types';\n\nexport const blockPaletteFormatVersion = 1;\nexport const blockPaletteFile = 'block-palette.json';\nexport const blockPaletteCommentMarker = ' // _twplus_palette_';\nexport const blockPaletteCommentReference = `block-palette:${blockPaletteFile}`;\nexport const blockPaletteCommentMaxLength = 8000;\nexport const blockPaletteSpriteCommentHeader =\n 'TurboWarp Plus Editor block palette for this sprite. ' +\n 'You can delete this comment to reset the palette.';\nexport const blockPaletteStageCommentHeader =\n 'TurboWarp Plus Editor block palette for the stage. ' +\n 'You can delete this comment to reset the palette.';\n\nconst markerToken = '// _twplus_palette_';\nconst groupIdPattern = /^[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9_-]+)?$/u;\nconst setIdPattern = /^[A-Za-z_][A-Za-z0-9_-]*$/u;\n\nexport interface BlockPaletteTargetSetting {\n groups: string[];\n}\n\nexport interface BlockPaletteSet {\n name: string;\n groups: string[];\n}\n\nexport interface BlockPaletteDocument {\n formatVersion: 1;\n order?: string[];\n sets?: Record<string, BlockPaletteSet>;\n stage?: BlockPaletteTargetSetting;\n sprites?: Record<string, BlockPaletteTargetSetting>;\n}\n\nexport type BlockPaletteWarningCode = 'block-palette-normalized' | 'block-palette-invalid';\n\nexport interface BlockPaletteWarning {\n code: BlockPaletteWarningCode;\n commentId: string;\n message: string;\n target: string;\n}\n\ninterface ProjectTargetComments {\n comments: Record<string, UnknownRecord>;\n isStage: boolean;\n name: string;\n}\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction assertOnlyKeys(value: UnknownRecord, allowed: string[], description: string): void {\n for (const key of Object.keys(value)) {\n assert(allowed.includes(key), `${description} has an unknown key: ${key}`);\n }\n}\n\nfunction validateGroupList(value: unknown, description: string): string[] {\n assert(Array.isArray(value), `${description} must be an array of block group IDs.`);\n const seen = new Set<string>();\n for (const group of value as unknown[]) {\n assert(\n typeof group === 'string' && groupIdPattern.test(group),\n `${description} contains an invalid block group ID: ${JSON.stringify(group)}`,\n );\n assert(!seen.has(group), `${description} contains a duplicate block group ID: ${group}`);\n seen.add(group);\n }\n return [...seen];\n}\n\nfunction validateTargetSetting(value: unknown, description: string): BlockPaletteTargetSetting {\n assert(isRecord(value), `${description} must be an object.`);\n assertOnlyKeys(value, ['groups'], description);\n return {groups: validateGroupList(value.groups, `${description} groups`)};\n}\n\nfunction validateSets(value: unknown, description: string): Record<string, BlockPaletteSet> {\n assert(isRecord(value), `${description} must be an object.`);\n return Object.fromEntries(\n Object.entries(value).map(([setId, set]) => {\n assert(setIdPattern.test(setId), `${description} has an invalid set ID: ${setId}`);\n const setDescription = `${description}.${setId}`;\n assert(isRecord(set), `${setDescription} must be an object.`);\n assertOnlyKeys(set, ['name', 'groups'], setDescription);\n assert(\n typeof set.name === 'string' && set.name.length > 0,\n `${setDescription} name must be a non-empty string.`,\n );\n return [\n setId,\n {name: set.name, groups: validateGroupList(set.groups, `${setDescription} groups`)},\n ];\n }),\n );\n}\n\nfunction canonicalDocument(parts: Omit<BlockPaletteDocument, 'formatVersion'>) {\n const document: BlockPaletteDocument = {formatVersion: blockPaletteFormatVersion};\n if (parts.order !== undefined) document.order = parts.order;\n if (parts.sets !== undefined) document.sets = parts.sets;\n if (parts.stage !== undefined) document.stage = parts.stage;\n if (parts.sprites !== undefined && Object.keys(parts.sprites).length > 0) {\n document.sprites = parts.sprites;\n }\n return document;\n}\n\nexport function hasBlockPaletteSettings(document: BlockPaletteDocument): boolean {\n return (\n document.order !== undefined ||\n document.sets !== undefined ||\n document.stage !== undefined ||\n (document.sprites !== undefined && Object.keys(document.sprites).length > 0)\n );\n}\n\nfunction stageHasSettings(document: BlockPaletteDocument): boolean {\n return (\n document.order !== undefined || document.sets !== undefined || document.stage !== undefined\n );\n}\n\n/** Validate the shape of `block-palette.json` without looking at the project. */\nexport function validateBlockPaletteDocument(value: unknown): BlockPaletteDocument {\n const description = blockPaletteFile;\n assert(isRecord(value), `${description} must contain an object.`);\n assertOnlyKeys(value, ['formatVersion', 'order', 'sets', 'stage', 'sprites'], description);\n assert(\n value.formatVersion === blockPaletteFormatVersion,\n `Unsupported ${description} formatVersion: ${String(value.formatVersion)}`,\n );\n let sprites: Record<string, BlockPaletteTargetSetting> | undefined;\n if (value.sprites !== undefined) {\n assert(isRecord(value.sprites), `${description} sprites must be an object.`);\n assert(\n Object.keys(value.sprites).length > 0,\n `${description} sprites must be omitted when it has no sprites.`,\n );\n sprites = Object.fromEntries(\n Object.entries(value.sprites).map(([name, setting]) => [\n name,\n validateTargetSetting(setting, `${description} sprites.${name}`),\n ]),\n );\n }\n const document = canonicalDocument({\n order: value.order === undefined ? undefined : validateGroupList(value.order, 'order'),\n sets: value.sets === undefined ? undefined : validateSets(value.sets, `${description} sets`),\n stage:\n value.stage === undefined\n ? undefined\n : validateTargetSetting(value.stage, `${description} stage`),\n sprites,\n });\n assert(\n hasBlockPaletteSettings(document),\n `${description} has no settings; remove it and use SB3 source format 1.`,\n );\n return document;\n}\n\nexport function serializeBlockPaletteDocument(document: BlockPaletteDocument): string {\n return `${JSON.stringify(canonicalDocument(document), null, 2)}\\n`;\n}\n\n/**\n * List each target's comments. In strict mode, a malformed target or comment is an error;\n * otherwise it is skipped so unpacking stays as permissive as it was in source format 1.\n */\nfunction targetComments(project: ProjectJson, strict = true): ProjectTargetComments[] {\n if (!strict && !Array.isArray(project.targets)) return [];\n assert(Array.isArray(project.targets), 'Project targets must be an array.');\n const targets: ProjectTargetComments[] = [];\n for (const [index, target] of (project.targets as unknown[]).entries()) {\n if (!strict && !isRecord(target)) continue;\n assert(isRecord(target), `Project target ${index} must be an object.`);\n const comments: unknown = target.comments ?? {};\n if (!strict && !isRecord(comments)) continue;\n assert(isRecord(comments), `Project target ${index} comments must be an object.`);\n const records = Object.fromEntries(\n Object.entries(comments).filter(([id, comment]) => {\n assert(\n !strict || isRecord(comment),\n `Project target ${index} comment ${id} must be an object.`,\n );\n return isRecord(comment);\n }),\n ) as Record<string, UnknownRecord>;\n targets.push({\n comments: records,\n isStage: target.isStage === true,\n name: typeof target.name === 'string' ? target.name : String(index),\n });\n }\n return targets;\n}\n\nfunction isMarkedComment(comment: UnknownRecord): boolean {\n return typeof comment.text === 'string' && comment.text.includes(markerToken);\n}\n\nfunction isReferenceComment(comment: UnknownRecord): boolean {\n return comment.text === blockPaletteCommentReference;\n}\n\nfunction canonicalCommentText(\n document: BlockPaletteDocument,\n target: {isStage: boolean; name: string},\n): string {\n let payload: UnknownRecord;\n if (target.isStage) {\n payload = {formatVersion: blockPaletteFormatVersion};\n if (document.stage) payload.groups = document.stage.groups;\n if (document.order) payload.order = document.order;\n if (document.sets) payload.sets = document.sets;\n } else {\n const setting = document.sprites?.[target.name];\n assert(setting, `${blockPaletteFile} has no setting for sprite ${target.name}.`);\n payload = {formatVersion: blockPaletteFormatVersion, groups: setting.groups};\n }\n const header = target.isStage ? blockPaletteStageCommentHeader : blockPaletteSpriteCommentHeader;\n return `${header}\\n${JSON.stringify(payload)}${blockPaletteCommentMarker}`;\n}\n\n/**\n * The canonical comment text for one sprite or the stage. Fails when the text is longer than\n * 8000 characters, which Scratch 3 refuses to load.\n */\nexport function formatBlockPaletteComment(\n document: BlockPaletteDocument,\n target: {isStage: boolean; name: string},\n): string {\n const text = canonicalCommentText(document, target);\n const length = Array.from(text).length;\n assert(\n length <= blockPaletteCommentMaxLength,\n `Block palette comment for ${target.isStage ? 'the stage' : `sprite ${target.name}`} has ` +\n `${length} characters; the limit is ${blockPaletteCommentMaxLength}.`,\n );\n return text;\n}\n\ntype ParsedComment =\n | {ok: true; value: Omit<BlockPaletteDocument, 'formatVersion' | 'sprites'>}\n | {ok: false; reason: string};\n\nfunction parseMarkedComment(comment: UnknownRecord, isStage: boolean): ParsedComment {\n if (comment.extraText !== undefined) {\n return {ok: false, reason: 'the comment has extraText'};\n }\n const lines = (comment.text as string).split('\\n');\n const markedLines = lines.filter((line) => line.includes(markerToken));\n if (markedLines.length !== 1) {\n return {ok: false, reason: 'the marker must appear on exactly one line'};\n }\n const [line] = markedLines;\n const json = line.slice(0, line.indexOf(markerToken)).trim();\n let value: unknown;\n try {\n value = JSON.parse(json);\n } catch {\n return {ok: false, reason: 'the marked line is not valid JSON'};\n }\n try {\n assert(isRecord(value), 'the JSON must be an object');\n assertOnlyKeys(\n value,\n isStage ? ['formatVersion', 'groups', 'order', 'sets'] : ['formatVersion', 'groups'],\n 'the JSON',\n );\n assert(\n value.formatVersion === blockPaletteFormatVersion,\n `unsupported formatVersion ${String(value.formatVersion)}`,\n );\n assert(isStage || value.groups !== undefined, 'the JSON has no groups');\n const parsed = {\n order: value.order === undefined ? undefined : validateGroupList(value.order, 'order'),\n sets: value.sets === undefined ? undefined : validateSets(value.sets, 'sets'),\n stage:\n value.groups === undefined\n ? undefined\n : {groups: validateGroupList(value.groups, 'groups')},\n };\n assert(\n parsed.order !== undefined || parsed.sets !== undefined || parsed.stage !== undefined,\n 'the JSON has no settings',\n );\n return {ok: true, value: parsed};\n } catch (error) {\n return {ok: false, reason: error instanceof Error ? error.message : String(error)};\n }\n}\n\n/**\n * Move palette comments from an SB3 project into a `block-palette.json` document.\n * The project is changed in place: each recognized comment keeps its ID, position, size,\n * state and order, and its text becomes {@link blockPaletteCommentReference}.\n */\nexport function extractBlockPalette(project: ProjectJson): {\n document: BlockPaletteDocument | null;\n warnings: BlockPaletteWarning[];\n} {\n const warnings: BlockPaletteWarning[] = [];\n const parts: Omit<BlockPaletteDocument, 'formatVersion'> = {};\n const sprites: [string, BlockPaletteTargetSetting][] = [];\n for (const target of targetComments(project, false)) {\n const marked = Object.entries(target.comments).filter(([, comment]) =>\n isMarkedComment(comment),\n );\n const references = Object.values(target.comments).filter(isReferenceComment);\n assert(\n references.length === 0,\n `${target.isStage ? 'The stage' : `Sprite ${target.name}`} has a comment whose text is ` +\n `reserved for block palette references: ${blockPaletteCommentReference}`,\n );\n assert(\n marked.length <= 1,\n `${target.isStage ? 'The stage' : `Sprite ${target.name}`} has ${marked.length} block ` +\n 'palette comments; only one is allowed.',\n );\n if (marked.length === 0) continue;\n const [[commentId, comment]] = marked;\n const parsed = parseMarkedComment(comment, target.isStage);\n if (!parsed.ok) {\n warnings.push({\n code: 'block-palette-invalid',\n commentId,\n message:\n `Block palette comment ${commentId} on ${target.name} was kept as a plain comment ` +\n `and ignored: ${parsed.reason}.`,\n target: target.name,\n });\n continue;\n }\n if (target.isStage) {\n Object.assign(parts, parsed.value);\n } else {\n assert(\n !sprites.some(([name]) => name === target.name),\n `Duplicate sprite name with block palette settings: ${target.name}`,\n );\n sprites.push([target.name, parsed.value.stage!]);\n }\n const document = canonicalDocument({...parts, sprites: Object.fromEntries(sprites)});\n const canonicalText = canonicalCommentText(document, target);\n if (comment.text !== canonicalText) {\n warnings.push({\n code: 'block-palette-normalized',\n commentId,\n message:\n `Block palette comment ${commentId} on ${target.name} is not in the canonical form; ` +\n 'it will be rewritten on build.',\n target: target.name,\n });\n }\n comment.text = blockPaletteCommentReference;\n }\n const document = canonicalDocument({...parts, sprites: Object.fromEntries(sprites)});\n return {document: hasBlockPaletteSettings(document) ? document : null, warnings};\n}\n\n/**\n * Check that `project.source.json` and `block-palette.json` agree, and return the canonical\n * comment text for each reference. `document` is null for source format 1.\n */\nexport function resolveBlockPaletteReferences(\n project: ProjectJson,\n document: BlockPaletteDocument | null,\n): {comment: UnknownRecord; text: string}[] {\n const resolved: {comment: UnknownRecord; text: string}[] = [];\n const targets = targetComments(project, document !== null);\n if (document === null) {\n for (const target of targets) {\n assert(\n !Object.values(target.comments).some(isReferenceComment),\n `project.source.json refers to ${blockPaletteFile}, which requires SB3 source format 2.`,\n );\n }\n return resolved;\n }\n const spriteNames = new Set(targets.filter(({isStage}) => !isStage).map(({name}) => name));\n for (const name of Object.keys(document.sprites ?? {})) {\n assert(spriteNames.has(name), `${blockPaletteFile} refers to an unknown sprite: ${name}`);\n }\n for (const target of targets) {\n const label = target.isStage ? 'The stage' : `Sprite ${target.name}`;\n const references = Object.values(target.comments).filter(isReferenceComment);\n const marked = Object.values(target.comments).filter(isMarkedComment);\n const expected = target.isStage\n ? stageHasSettings(document)\n : document.sprites?.[target.name] !== undefined;\n assert(\n references.length <= 1,\n `${label} has ${references.length} block palette references; only one is allowed.`,\n );\n assert(\n references.length === 0 || marked.length === 0,\n `${label} has both a block palette reference and a block palette comment.`,\n );\n assert(\n references.length === (expected ? 1 : 0),\n expected\n ? `${label} has block palette settings in ${blockPaletteFile} but no comment that ` +\n `refers to it (${blockPaletteCommentReference}).`\n : `${label} has a block palette reference but no settings in ${blockPaletteFile}.`,\n );\n if (references.length === 1) {\n resolved.push({comment: references[0], text: formatBlockPaletteComment(document, target)});\n }\n }\n return resolved;\n}\n\n/** Replace each reference comment in a cloned project with its canonical SB3 text. */\nexport function applyBlockPaletteComments(\n project: ProjectJson,\n document: BlockPaletteDocument | null,\n): void {\n for (const {comment, text} of resolveBlockPaletteReferences(project, document)) {\n comment.text = text;\n }\n}\n"],"mappings":";;;;;;;;;;;AAeA,IAAa,4BAA4B;AACzC,IAAa,mBAAmB;AAChC,IAAa,4BAA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AW,IAAI,IACtC,WACI,GAAG,MAAM,iCAAiC,iBAAiB,qCACxC,6BAA6B,MAChD,GAAG,MAAM,oDAAoD,iBAAiB,EACpF;EACA,IAAI,WAAW,WAAW,GACxB,SAAS,KAAK;GAAC,SAAS,WAAW;GAAI,MAAM,0BAA0B,UAAU,MAAM;EAAC,CAAC;CAE7F;CACA,OAAO;AACT;;AAGA,SAAgB,0BACd,SACA,UACM;CACN,KAAK,MAAM,EAAC,SAAS,UAAS,8BAA8B,SAAS,QAAQ,GAC3E,QAAQ,OAAO;AAEnB"}
package/dist/browser.d.ts CHANGED
@@ -1,9 +1,18 @@
1
+ import { BlockPaletteWarningCode } from './block-palette';
1
2
  export { Sb3SourceError } from './expand-archive';
2
3
  export type { Sb3SourceErrorCode } from './expand-archive';
3
4
  export { packageVersion } from './constants';
5
+ export { blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, serializeBlockPaletteDocument, validateBlockPaletteDocument, } from './block-palette';
6
+ export type { BlockPaletteDocument, BlockPaletteSet, BlockPaletteTargetSetting, } from './block-palette';
7
+ export { blockPaletteSourceFormatVersion, sourceFormatVersion, supportedSourceFormatVersions, } from './source-format';
4
8
  export interface UnpackWarning {
5
- code: 'directory-entry' | 'unreferenced-asset';
9
+ code: 'directory-entry' | 'unreferenced-asset' | BlockPaletteWarningCode;
10
+ /** The archive entry, or `project.json` for block palette comments. */
6
11
  path: string;
12
+ /** Present for block palette warnings. */
13
+ commentId?: string;
14
+ message?: string;
15
+ target?: string;
7
16
  }
8
17
  export interface UnpackedSb3 {
9
18
  files: Map<string, Uint8Array>;
package/dist/browser.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { assert, errorMessage } from "./assert.js";
2
+ import { blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, resolveBlockPaletteReferences, serializeBlockPaletteDocument, validateBlockPaletteDocument } from "./block-palette.js";
2
3
  import { validateArchiveEntryName } from "./archive.js";
3
- import { assertSameFileSet, collectSourceAssetReferences, isObject, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
4
+ import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
4
5
  import { packageVersion } from "./constants.js";
5
6
  import { Sb3SourceError, expandArchive, formatSourceFiles } from "./expand-archive.js";
6
7
  import { strFromU8 } from "fflate";
@@ -63,11 +64,18 @@ function validateSourceFiles(files) {
63
64
  if (!asset) throw new Sb3SourceError("missing-asset", `Referenced asset is missing for ${description}: ${filename}`);
64
65
  if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) throw new Sb3SourceError("invalid-asset", `Asset content hash mismatch for ${description}: ${filename}`);
65
66
  }
67
+ try {
68
+ const blockPalette = manifest.blockPalette === void 0 ? null : validateBlockPaletteDocument(json(manifest.blockPalette));
69
+ resolveBlockPaletteReferences(project, blockPalette);
70
+ } catch (cause) {
71
+ throw new Sb3SourceError("invalid-block-palette", errorMessage(cause), { cause });
72
+ }
66
73
  const extensionFiles = [];
67
74
  const expected = /* @__PURE__ */ new Set([
68
75
  "sb3-source.json",
69
76
  manifest.project,
70
77
  manifest.embeddedExtensions,
78
+ ...manifest.blockPalette === void 0 ? [] : [manifest.blockPalette],
71
79
  ...assetEntries.map((name) => `assets/${name}`)
72
80
  ]);
73
81
  for (const name of files.keys()) {
@@ -94,7 +102,10 @@ function unpackSb3(bytes) {
94
102
  const expanded = expandArchive(bytes, archiveLimits);
95
103
  const references = new Set(validatedAssetReferences(expanded.project).map(({ filename }) => filename));
96
104
  for (const name of references) if (!expanded.assets.has(name)) throw new Sb3SourceError("missing-asset", `Referenced asset is missing: ${name}`);
97
- const warnings = [];
105
+ const warnings = expanded.blockPaletteWarnings.map((warning) => ({
106
+ ...warning,
107
+ path: "project.json"
108
+ }));
98
109
  expanded.archiveEntries = expanded.archiveEntries.filter((name) => {
99
110
  if (name === "project.json" || references.has(name)) return true;
100
111
  if (name.endsWith("/")) warnings.push({
@@ -118,6 +129,6 @@ function unpackSb3(bytes) {
118
129
  };
119
130
  }
120
131
  //#endregion
121
- export { Sb3SourceError, packageVersion, unpackSb3, validateSourceFiles };
132
+ export { Sb3SourceError, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSourceFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, formatBlockPaletteComment, packageVersion, serializeBlockPaletteDocument, sourceFormatVersion, supportedSourceFormatVersions, unpackSb3, validateBlockPaletteDocument, validateSourceFiles };
122
133
 
123
134
  //# sourceMappingURL=browser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","names":[],"sources":["../src/browser.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {md5} from '@noble/hashes/legacy.js';\nimport {bytesToHex} from '@noble/hashes/utils.js';\nimport {strFromU8} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {expandArchive, formatSourceFiles, Sb3SourceError} from './expand-archive';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {ProjectJson} from './types';\n\nexport {Sb3SourceError} from './expand-archive';\nexport type {Sb3SourceErrorCode} from './expand-archive';\nexport {packageVersion} from './constants';\n\nexport interface UnpackWarning {\n code: 'directory-entry' | 'unreferenced-asset';\n path: string;\n}\n\nexport interface UnpackedSb3 {\n files: Map<string, Uint8Array>;\n warnings: UnpackWarning[];\n}\n\nconst archiveLimits = {\n maxArchiveBytes: 100 * 1024 * 1024,\n maxEntryBytes: 100 * 1024 * 1024,\n maxExpandedBytes: 512 * 1024 * 1024,\n maxEntries: 20_000,\n};\n\nfunction validateEditorProject(project: ProjectJson) {\n if (project.turboWarpPlus !== undefined) {\n throw new Sb3SourceError(\n 'unsupported-project',\n 'Plus extension manifests are not supported in project folders.',\n );\n }\n assert(Array.isArray(project.targets), 'Missing project targets.');\n const targetNames = new Set<string>();\n let stages = 0;\n for (const target of project.targets) {\n assert(\n isObject(target) && typeof target.isStage === 'boolean' && typeof target.name === 'string',\n 'Invalid project target.',\n );\n if (target.isStage) {\n stages++;\n } else {\n assert(!targetNames.has(target.name), `Duplicate sprite name: ${target.name}`);\n targetNames.add(target.name);\n }\n assert(target.blocks === undefined || isObject(target.blocks), 'Invalid target blocks.');\n assert(target.comments === undefined || isObject(target.comments), 'Invalid target comments.');\n }\n assert(stages === 1, 'Expected exactly one stage.');\n assert(\n project.extensionURLs === undefined ||\n (isObject(project.extensionURLs) &&\n Object.values(project.extensionURLs).every((url) => typeof url === 'string')),\n 'Invalid project extensionURLs.',\n );\n}\n\nfunction validatedAssetReferences(project: ProjectJson) {\n try {\n validateEditorProject(project);\n return collectSourceAssetReferences(project);\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n}\n\n/** Validate the layout and asset bytes of a project folder in memory. */\nexport function validateSourceFiles(files: ReadonlyMap<string, Uint8Array>): void {\n const json = (filename: string): unknown => {\n const bytes = files.get(filename);\n assert(bytes, `Missing source file: ${filename}`);\n return JSON.parse(strFromU8(bytes));\n };\n\n try {\n const manifest = json('sb3-source.json');\n validateSourceManifest(manifest);\n const project = json(manifest.project);\n assert(isObject(project), 'project.source.json must contain an object.');\n const references = validatedAssetReferences(project);\n\n const assetEntries = manifest.archiveEntries.filter((name) => name !== 'project.json');\n assertSameFileSet(\n assetEntries,\n references.map(({filename}) => filename),\n 'Asset manifest',\n );\n const seen = new Set<string>();\n for (const {filename, description} of references) {\n if (seen.has(filename)) continue;\n seen.add(filename);\n const asset = files.get(`assets/${filename}`);\n if (!asset) {\n throw new Sb3SourceError(\n 'missing-asset',\n `Referenced asset is missing for ${description}: ${filename}`,\n );\n }\n if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) {\n throw new Sb3SourceError(\n 'invalid-asset',\n `Asset content hash mismatch for ${description}: ${filename}`,\n );\n }\n }\n\n const extensionFiles: string[] = [];\n const expected = new Set([\n 'sb3-source.json',\n manifest.project,\n manifest.embeddedExtensions,\n ...assetEntries.map((name) => `assets/${name}`),\n ]);\n for (const name of files.keys()) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (name.startsWith('extensions/')) {\n extensionFiles.push(name.slice('extensions/'.length));\n } else {\n assert(expected.has(name), `Unexpected source file: ${name}`);\n }\n }\n try {\n validateExtensionLayout(json(manifest.embeddedExtensions), project, extensionFiles);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-source', errorMessage(cause), {cause});\n }\n}\n\n/** Expand an SB3 into files suitable for opening as an Editor project folder. */\nexport function unpackSb3(bytes: Uint8Array): UnpackedSb3 {\n const expanded = expandArchive(bytes, archiveLimits);\n const references = new Set(\n validatedAssetReferences(expanded.project).map(({filename}) => filename),\n );\n for (const name of references) {\n if (!expanded.assets.has(name)) {\n throw new Sb3SourceError('missing-asset', `Referenced asset is missing: ${name}`);\n }\n }\n const warnings: UnpackWarning[] = [];\n expanded.archiveEntries = expanded.archiveEntries.filter((name) => {\n if (name === 'project.json' || references.has(name)) return true;\n if (name.endsWith('/')) {\n warnings.push({code: 'directory-entry', path: name});\n } else if (/^[a-f0-9]{32}\\.[A-Za-z0-9]+$/u.test(name)) {\n expanded.assets.delete(name);\n warnings.push({code: 'unreferenced-asset', path: name});\n } else {\n throw new Sb3SourceError('unsupported-project', `Unsupported SB3 attachment: ${name}`);\n }\n return false;\n });\n const files = formatSourceFiles(expanded);\n validateSourceFiles(files);\n return {files, warnings};\n}\n"],"mappings":";;;;;;;;;AAgCA,IAAM,gBAAgB;CACpB,iBAAiB;CACjB,eAAe;CACf,kBAAkB;CAClB,YAAY;AACd;AAEA,SAAS,sBAAsB,SAAsB;CACnD,IAAI,QAAQ,kBAAkB,KAAA,GAC5B,MAAM,IAAI,eACR,uBACA,gEACF;CAEF,OAAO,MAAM,QAAQ,QAAQ,OAAO,GAAG,0BAA0B;CACjE,MAAM,8BAAc,IAAI,IAAY;CACpC,IAAI,SAAS;CACb,KAAK,MAAM,UAAU,QAAQ,SAAS;EACpC,OACE,SAAS,MAAM,KAAK,OAAO,OAAO,YAAY,aAAa,OAAO,OAAO,SAAS,UAClF,yBACF;EACA,IAAI,OAAO,SACT;OACK;GACL,OAAO,CAAC,YAAY,IAAI,OAAO,IAAI,GAAG,0BAA0B,OAAO,MAAM;GAC7E,YAAY,IAAI,OAAO,IAAI;EAC7B;EACA,OAAO,OAAO,WAAW,KAAA,KAAa,SAAS,OAAO,MAAM,GAAG,wBAAwB;EACvF,OAAO,OAAO,aAAa,KAAA,KAAa,SAAS,OAAO,QAAQ,GAAG,0BAA0B;CAC/F;CACA,OAAO,WAAW,GAAG,6BAA6B;CAClD,OACE,QAAQ,kBAAkB,KAAA,KACvB,SAAS,QAAQ,aAAa,KAC7B,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,GAC/E,gCACF;AACF;AAEA,SAAS,yBAAyB,SAAsB;CACtD,IAAI;EACF,sBAAsB,OAAO;EAC7B,OAAO,6BAA6B,OAAO;CAC7C,SAAS,OAAO;EACd,IAAI,iBAAiB,gBAAgB,MAAM;EAC3C,MAAM,IAAI,eAAe,mBAAmB,aAAa,KAAK,GAAG,EAAC,MAAK,CAAC;CAC1E;AACF;;AAGA,SAAgB,oBAAoB,OAA8C;CAChF,MAAM,Q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AM;EAEhE;EACA,IAAI;GACF,wBAAwB,KAAK,SAAS,kBAAkB,GAAG,SAAS,cAAc;EACpF,SAAS,OAAO;GACd,MAAM,IAAI,eAAe,qBAAqB,aAAa,KAAK,GAAG,EAAC,MAAK,CAAC;EAC5E;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,gBAAgB,MAAM;EAC3C,MAAM,IAAI,eAAe,kBAAkB,aAAa,KAAK,GAAG,EAAC,MAAK,CAAC;CACzE;AACF;;AAGA,SAAgB,UAAU,OAAgC;CACxD,MAAM,WAAW,cAAc,OAAO,aAAa;CACnD,MAAM,aAAa,IAAI,IACrB,yBAAyB,SAAS,OAAO,CAAC,CAAC,KAAK,EAAC,eAAc,QAAQ,CACzE;CACA,KAAK,MAAM,QAAQ,YACjB,IAAI,CAAC,SAAS,OAAO,IAAI,IAAI,GAC3B,MAAM,IAAI,eAAe,iBAAiB,gCAAgC,MAAM;CAGpF,MAAM,WAA4B,CAAC;CACnC,SAAS,iBAAiB,SAAS,eAAe,QAAQ,SAAS;EACjE,IAAI,SAAS,kBAAkB,WAAW,IAAI,IAAI,GAAG,OAAO;EAC5D,IAAI,KAAK,SAAS,GAAG,GACnB,SAAS,KAAK;GAAC,MAAM;GAAmB,MAAM;EAAI,CAAC;OAC9C,IAAI,gCAAgC,KAAK,IAAI,GAAG;GACrD,SAAS,OAAO,OAAO,IAAI;GAC3B,SAAS,KAAK;IAAC,MAAM;IAAsB,MAAM;GAAI,CAAC;EACxD,OACE,MAAM,IAAI,eAAe,uBAAuB,+BAA+B,MAAM;EAEvF,OAAO;CACT,CAAC;CACD,MAAM,QAAQ,kBAAkB,QAAQ;CACxC,oBAAoB,KAAK;CACzB,OAAO;EAAC;EAAO;CAAQ;AACzB"}
1
+ {"version":3,"file":"browser.js","names":[],"sources":["../src/browser.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {md5} from '@noble/hashes/legacy.js';\nimport {bytesToHex} from '@noble/hashes/utils.js';\nimport {strFromU8} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {resolveBlockPaletteReferences, validateBlockPaletteDocument} from './block-palette';\nimport type {BlockPaletteWarningCode} from './block-palette';\nimport {expandArchive, formatSourceFiles, Sb3SourceError} from './expand-archive';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {ProjectJson} from './types';\n\nexport {Sb3SourceError} from './expand-archive';\nexport type {Sb3SourceErrorCode} from './expand-archive';\nexport {packageVersion} from './constants';\nexport {\n blockPaletteCommentMarker,\n blockPaletteCommentMaxLength,\n blockPaletteCommentReference,\n blockPaletteFile,\n blockPaletteFormatVersion,\n blockPaletteSpriteCommentHeader,\n blockPaletteStageCommentHeader,\n formatBlockPaletteComment,\n serializeBlockPaletteDocument,\n validateBlockPaletteDocument,\n} from './block-palette';\nexport type {\n BlockPaletteDocument,\n BlockPaletteSet,\n BlockPaletteTargetSetting,\n} from './block-palette';\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\n\nexport interface UnpackWarning {\n code: 'directory-entry' | 'unreferenced-asset' | BlockPaletteWarningCode;\n /** The archive entry, or `project.json` for block palette comments. */\n path: string;\n /** Present for block palette warnings. */\n commentId?: string;\n message?: string;\n target?: string;\n}\n\nexport interface UnpackedSb3 {\n files: Map<string, Uint8Array>;\n warnings: UnpackWarning[];\n}\n\nconst archiveLimits = {\n maxArchiveBytes: 100 * 1024 * 1024,\n maxEntryBytes: 100 * 1024 * 1024,\n maxExpandedBytes: 512 * 1024 * 1024,\n maxEntries: 20_000,\n};\n\nfunction validateEditorProject(project: ProjectJson) {\n if (project.turboWarpPlus !== undefined) {\n throw new Sb3SourceError(\n 'unsupported-project',\n 'Plus extension manifests are not supported in project folders.',\n );\n }\n assert(Array.isArray(project.targets), 'Missing project targets.');\n const targetNames = new Set<string>();\n let stages = 0;\n for (const target of project.targets) {\n assert(\n isObject(target) && typeof target.isStage === 'boolean' && typeof target.name === 'string',\n 'Invalid project target.',\n );\n if (target.isStage) {\n stages++;\n } else {\n assert(!targetNames.has(target.name), `Duplicate sprite name: ${target.name}`);\n targetNames.add(target.name);\n }\n assert(target.blocks === undefined || isObject(target.blocks), 'Invalid target blocks.');\n assert(target.comments === undefined || isObject(target.comments), 'Invalid target comments.');\n }\n assert(stages === 1, 'Expected exactly one stage.');\n assert(\n project.extensionURLs === undefined ||\n (isObject(project.extensionURLs) &&\n Object.values(project.extensionURLs).every((url) => typeof url === 'string')),\n 'Invalid project extensionURLs.',\n );\n}\n\nfunction validatedAssetReferences(project: ProjectJson) {\n try {\n validateEditorProject(project);\n return collectSourceAssetReferences(project);\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n}\n\n/** Validate the layout and asset bytes of a project folder in memory. */\nexport function validateSourceFiles(files: ReadonlyMap<string, Uint8Array>): void {\n const json = (filename: string): unknown => {\n const bytes = files.get(filename);\n assert(bytes, `Missing source file: ${filename}`);\n return JSON.parse(strFromU8(bytes));\n };\n\n try {\n const manifest = json('sb3-source.json');\n validateSourceManifest(manifest);\n const project = json(manifest.project);\n assert(isObject(project), 'project.source.json must contain an object.');\n const references = validatedAssetReferences(project);\n\n const assetEntries = manifest.archiveEntries.filter((name) => name !== 'project.json');\n assertSameFileSet(\n assetEntries,\n references.map(({filename}) => filename),\n 'Asset manifest',\n );\n const seen = new Set<string>();\n for (const {filename, description} of references) {\n if (seen.has(filename)) continue;\n seen.add(filename);\n const asset = files.get(`assets/${filename}`);\n if (!asset) {\n throw new Sb3SourceError(\n 'missing-asset',\n `Referenced asset is missing for ${description}: ${filename}`,\n );\n }\n if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) {\n throw new Sb3SourceError(\n 'invalid-asset',\n `Asset content hash mismatch for ${description}: ${filename}`,\n );\n }\n }\n\n try {\n const blockPalette =\n manifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(json(manifest.blockPalette));\n resolveBlockPaletteReferences(project, blockPalette);\n } catch (cause) {\n throw new Sb3SourceError('invalid-block-palette', errorMessage(cause), {cause});\n }\n\n const extensionFiles: string[] = [];\n const expected = new Set([\n 'sb3-source.json',\n manifest.project,\n manifest.embeddedExtensions,\n ...(manifest.blockPalette === undefined ? [] : [manifest.blockPalette]),\n ...assetEntries.map((name) => `assets/${name}`),\n ]);\n for (const name of files.keys()) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (name.startsWith('extensions/')) {\n extensionFiles.push(name.slice('extensions/'.length));\n } else {\n assert(expected.has(name), `Unexpected source file: ${name}`);\n }\n }\n try {\n validateExtensionLayout(json(manifest.embeddedExtensions), project, extensionFiles);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-source', errorMessage(cause), {cause});\n }\n}\n\n/** Expand an SB3 into files suitable for opening as an Editor project folder. */\nexport function unpackSb3(bytes: Uint8Array): UnpackedSb3 {\n const expanded = expandArchive(bytes, archiveLimits);\n const references = new Set(\n validatedAssetReferences(expanded.project).map(({filename}) => filename),\n );\n for (const name of references) {\n if (!expanded.assets.has(name)) {\n throw new Sb3SourceError('missing-asset', `Referenced asset is missing: ${name}`);\n }\n }\n const warnings: UnpackWarning[] = expanded.blockPaletteWarnings.map((warning) => ({\n ...warning,\n path: 'project.json',\n }));\n expanded.archiveEntries = expanded.archiveEntries.filter((name) => {\n if (name === 'project.json' || references.has(name)) return true;\n if (name.endsWith('/')) {\n warnings.push({code: 'directory-entry', path: name});\n } else if (/^[a-f0-9]{32}\\.[A-Za-z0-9]+$/u.test(name)) {\n expanded.assets.delete(name);\n warnings.push({code: 'unreferenced-asset', path: name});\n } else {\n throw new Sb3SourceError('unsupported-project', `Unsupported SB3 attachment: ${name}`);\n }\n return false;\n });\n const files = formatSourceFiles(expanded);\n validateSourceFiles(files);\n return {files, warnings};\n}\n"],"mappings":";;;;;;;;;;AA6DA,IAAM,gBAAgB;CACpB,iBAAiB;CACjB,eAAe;CACf,kBAAkB;CAClB,YAAY;AACd;AAEA,SAAS,sBAAsB,SAAsB;CACnD,IAAI,QAAQ,kBAAkB,KAAA,GAC5B,MAAM,IAAI,eACR,uBACA,gEACF;CAEF,OAAO,MAAM,QAAQ,QAAQ,OAAO,GAAG,0BAA0B;CACjE,MAAM,8BAAc,IAAI,IAAY;CACpC,IAAI,SAAS;CACb,KAAK,MAAM,UAAU,QAAQ,SAAS;EACpC,OACE,SAAS,MAAM,KAAK,OAAO,OAAO,YAAY,aAAa,OAAO,OAAO,SAAS,UAClF,yBACF;EACA,IAAI,OAAO,SACT;OACK;GACL,OAAO,CAAC,YAAY,IAAI,OAAO,IAAI,GAAG,0BAA0B,OAAO,MAAM;GAC7E,YAAY,IAAI,OAAO,IAAI;EAC7B;EACA,OAAO,OAAO,WAAW,KAAA,KAAa,SAAS,OAAO,MAAM,GAAG,wBAAwB;EACvF,OAAO,OAAO,aAAa,KAAA,KAAa,SAAS,OAAO,QAAQ,GAAG,0BAA0B;CAC/F;CACA,OAAO,WAAW,GAAG,6BAA6B;CAClD,OACE,QAAQ,kBAAkB,KAAA,KACvB,SAAS,QAAQ,aAAa,KAC7B,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,OAAO,QAAQ,OAAO,QAAQ,QAAQ,GAC/E,gCACF;AACF;AAEA,SAAS,yBAAyB,SAAsB;CACtD,IAAI;EACF,sBAAsB,OAAO;EAC7B,OAAO,6BAA6B,OAAO;CAC7C,SAAS,OAAO;EACd,IAAI,iBAAiB,gBAAgB,MAAM;EAC3C,MAAM,IAAI,eAAe,mBAAmB,aAAa,KAAK,GAAG,EAAC,MAAK,CAAC;CAC1E;AACF;;AAGA,SAAgB,oBAAoB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C,MAAM;IAAsB,MAAM;GAAI,CAAC;EACxD,OACE,MAAM,IAAI,eAAe,uBAAuB,+BAA+B,MAAM;EAEvF,OAAO;CACT,CAAC;CACD,MAAM,QAAQ,kBAAkB,QAAQ;CACxC,oBAAoB,KAAK;CACzB,OAAO;EAAC;EAAO;CAAQ;AACzB"}
package/dist/cli.js CHANGED
@@ -708,6 +708,7 @@ async function runCli(arguments_, { fetch: fetchImplementation = globalThis.fetc
708
708
  const differenceMessage = result.differenceCounts ? ` Changes: +${result.differenceCounts.added} ~${result.differenceCounts.modified} -${result.differenceCounts.removed}.` : "";
709
709
  log(`Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} (${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` + differenceMessage);
710
710
  } else log(`Already up to date; no files changed: ${result.outputDirectory}`);
711
+ for (const warning of result.warnings) log(`Warning: ${warning.message}`);
711
712
  if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
712
713
  }
713
714
  //#endregion