@kubohiroya/sb3-toolchain 0.20.0 → 0.22.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.
@@ -8,6 +8,7 @@ var turboWarpCleanUpLayout = Object.freeze({
8
8
  startY: 64
9
9
  });
10
10
  var minimumBlockHeight = 48;
11
+ var compactBlockHeight = 64;
11
12
  var minimumBlockWidth = 160;
12
13
  var nestedStackIndent = 64;
13
14
  var nestedStackPadding = 24;
@@ -48,16 +49,16 @@ function inputDisplayTextLength(input, blocks) {
48
49
  }
49
50
  return 0;
50
51
  }
51
- function verticalChildIds(block, blocks) {
52
+ function measuredChildIds(block, blocks, compact) {
52
53
  const childIds = [];
53
54
  if (isObject(block.inputs)) for (const [inputName, input] of Object.entries(block.inputs)) {
54
55
  const childId = inputBlockId(input, blocks);
55
- if (childId && /^SUBSTACK/u.test(inputName)) childIds.push(childId);
56
+ if (childId && (compact || /^SUBSTACK/u.test(inputName))) childIds.push(childId);
56
57
  }
57
58
  if (typeof block.next === "string" && Object.hasOwn(blocks, block.next)) childIds.push(block.next);
58
59
  return childIds;
59
60
  }
60
- function measureStack(blockId, blocks) {
61
+ function measureStack(blockId, blocks, compact) {
61
62
  const measured = /* @__PURE__ */ new Map();
62
63
  const active = /* @__PURE__ */ new Set();
63
64
  const work = [{
@@ -76,7 +77,7 @@ function measureStack(blockId, blocks) {
76
77
  blockId: frame.blockId,
77
78
  finalize: true
78
79
  });
79
- const childIds = verticalChildIds(block, blocks);
80
+ const childIds = measuredChildIds(block, blocks, compact);
80
81
  for (let index = childIds.length - 1; index >= 0; index -= 1) {
81
82
  const childId = childIds[index];
82
83
  if (!active.has(childId) && !measured.has(childId)) work.push({
@@ -86,7 +87,7 @@ function measureStack(blockId, blocks) {
86
87
  }
87
88
  continue;
88
89
  }
89
- let height = minimumBlockHeight;
90
+ let height = compact ? compactBlockHeight : minimumBlockHeight;
90
91
  let width = Math.max(minimumBlockWidth, 80 + displayTextLength(block) * 8);
91
92
  if (isObject(block.inputs)) for (const [inputName, input] of Object.entries(block.inputs)) {
92
93
  const childId = inputBlockId(input, blocks);
@@ -97,7 +98,11 @@ function measureStack(blockId, blocks) {
97
98
  };
98
99
  height += nested.height + nestedStackPadding;
99
100
  width = Math.max(width, nested.width + nestedStackIndent);
100
- } else width += 24 + inputDisplayTextLength(input, blocks) * 8;
101
+ } else {
102
+ const reporter = compact && childId ? measured.get(childId) : void 0;
103
+ width += 24 + (reporter?.width ?? inputDisplayTextLength(input, blocks) * 8);
104
+ if (reporter) height = Math.max(height, reporter.height + 16);
105
+ }
101
106
  }
102
107
  if (typeof block.next === "string" && Object.hasOwn(blocks, block.next)) {
103
108
  const next = measured.get(block.next) ?? {
@@ -150,6 +155,7 @@ function findTopBlockId(blockId, blocks) {
150
155
  while (typeof currentId === "string" && !visited.has(currentId)) {
151
156
  visited.add(currentId);
152
157
  const block = blocks[currentId];
158
+ if (isReporterPrimitive(block)) return currentId;
153
159
  if (!isObject(block)) return null;
154
160
  if (block.topLevel === true || block.parent === null) return currentId;
155
161
  currentId = block.parent;
@@ -184,7 +190,96 @@ function attachedCommentWidths(target, blocks) {
184
190
  }
185
191
  return widths;
186
192
  }
187
- function cleanUpTarget(target, targetIndex) {
193
+ function isReporterPrimitive(value) {
194
+ return Array.isArray(value) && (value[0] === 12 || value[0] === 13) && value.length >= 5;
195
+ }
196
+ function commentBounds(comment) {
197
+ if (!isObject(comment) || !isFiniteNumber(comment.x) || !isFiniteNumber(comment.y) || !isFiniteNumber(comment.width) || !isFiniteNumber(comment.height) || comment.width < 0 || comment.height < 0) return void 0;
198
+ return {
199
+ x: comment.x,
200
+ y: comment.y,
201
+ width: comment.width,
202
+ height: comment.height
203
+ };
204
+ }
205
+ function compactPlacements(scripts, target, blocks) {
206
+ const { columnGap, rowGap, startX, startY } = turboWarpCleanUpLayout;
207
+ const items = scripts.map((script) => ({
208
+ script,
209
+ left: 0,
210
+ right: script.size.width,
211
+ top: 0,
212
+ bottom: script.size.height
213
+ }));
214
+ const byId = new Map(items.map((item) => [item.script.blockId, item]));
215
+ const obstacles = [];
216
+ if (isObject(target.comments)) for (const comment of Object.values(target.comments)) {
217
+ const bounds = commentBounds(comment);
218
+ if (!bounds || !isObject(comment)) continue;
219
+ const topBlockId = findTopBlockId(comment.blockId, blocks);
220
+ const item = topBlockId === null ? void 0 : byId.get(topBlockId);
221
+ if (!item) {
222
+ obstacles.push(bounds);
223
+ continue;
224
+ }
225
+ const x = bounds.x - item.script.originalX;
226
+ const y = bounds.y - item.script.originalY;
227
+ item.left = Math.min(item.left, x);
228
+ item.right = Math.max(item.right, x + bounds.width);
229
+ item.top = Math.min(item.top, y);
230
+ item.bottom = Math.max(item.bottom, y + bounds.height);
231
+ }
232
+ obstacles.sort((a, b) => compareNumbers(a.y, b.y));
233
+ const placements = [];
234
+ let bestScore = Infinity;
235
+ let bestRowCount = 1;
236
+ for (let rows = 1;; rows = Math.min(items.length, rows + Math.ceil(rows / 16))) {
237
+ let width = 0;
238
+ let height = 0;
239
+ for (let first = 0; first < items.length; first += rows) {
240
+ let left = 0;
241
+ let right = 0;
242
+ let columnHeight = 0;
243
+ for (const item of items.slice(first, first + rows)) {
244
+ left = Math.min(left, item.left);
245
+ right = Math.max(right, item.right);
246
+ columnHeight += item.bottom - item.top + rowGap;
247
+ }
248
+ width += right - left + columnGap;
249
+ height = Math.max(height, columnHeight - rowGap);
250
+ }
251
+ const score = Math.max((width - columnGap) / 1.5, height);
252
+ if (score < bestScore) {
253
+ bestScore = score;
254
+ bestRowCount = rows;
255
+ }
256
+ if (rows >= items.length) break;
257
+ }
258
+ let cursorX = startX;
259
+ for (let first = 0; first < items.length; first += bestRowCount) {
260
+ const column = items.slice(first, first + bestRowCount);
261
+ let left = 0;
262
+ let right = 0;
263
+ for (const item of column) {
264
+ left = Math.min(left, item.left);
265
+ right = Math.max(right, item.right);
266
+ }
267
+ const x = cursorX - Math.floor(left);
268
+ let cursorY = startY;
269
+ for (const item of column) {
270
+ for (const obstacle of obstacles) if (x + item.left < obstacle.x + obstacle.width + columnGap && x + item.right + columnGap > obstacle.x && cursorY < obstacle.y + obstacle.height + rowGap && cursorY + item.bottom - item.top + rowGap > obstacle.y) cursorY = obstacle.y + obstacle.height + rowGap;
271
+ placements.push({
272
+ script: item.script,
273
+ x,
274
+ y: cursorY - item.top
275
+ });
276
+ cursorY += item.bottom - item.top + rowGap;
277
+ }
278
+ cursorX = x + Math.ceil(right) + columnGap;
279
+ }
280
+ return placements;
281
+ }
282
+ function cleanUpTarget(target, targetIndex, compact) {
188
283
  if (target.blocks === void 0) return {
189
284
  movedCommentCount: 0,
190
285
  movedScriptCount: 0,
@@ -193,49 +288,66 @@ function cleanUpTarget(target, targetIndex) {
193
288
  assert(isObject(target.blocks), `Project target ${targetIndex} blocks must be an object.`);
194
289
  const blocks = target.blocks;
195
290
  const scripts = [];
196
- let inputOrder = 0;
197
291
  for (const [blockId, block] of Object.entries(blocks)) {
198
- if (!isObject(block) || block.topLevel !== true) continue;
199
- assert(isFiniteNumber(block.x) && isFiniteNumber(block.y), `Top-level block ${JSON.stringify(blockId)} in project target ${targetIndex} requires numeric x and y coordinates.`);
292
+ const primitive = compact && isReporterPrimitive(block);
293
+ if (!primitive && (!isObject(block) || block.topLevel !== true)) continue;
294
+ const x = Array.isArray(block) ? block[3] : block.x;
295
+ const y = Array.isArray(block) ? block[4] : block.y;
296
+ assert(isFiniteNumber(x) && isFiniteNumber(y), `Top-level block ${JSON.stringify(blockId)} in project target ${targetIndex} requires numeric x and y coordinates.`);
200
297
  scripts.push({
201
298
  block,
202
299
  blockId,
203
- inputOrder,
204
- originalX: block.x,
205
- originalY: block.y,
206
- size: measureStack(blockId, blocks)
300
+ inputOrder: scripts.length,
301
+ originalX: x,
302
+ originalY: y,
303
+ size: primitive ? {
304
+ height: minimumBlockHeight,
305
+ width: Math.max(minimumBlockWidth, 80 + String(block[1]).length * 8)
306
+ } : measureStack(blockId, blocks, compact)
207
307
  });
208
- inputOrder += 1;
209
308
  }
309
+ const columns = groupIntoColumns(scripts);
210
310
  const movements = /* @__PURE__ */ new Map();
211
- const commentWidths = attachedCommentWidths(target, blocks);
212
- let cursorX = turboWarpCleanUpLayout.startX;
213
- let movedScriptCount = 0;
214
- for (const column of groupIntoColumns(scripts)) {
215
- let cursorY = turboWarpCleanUpLayout.startY;
216
- let columnWidth = 0;
217
- for (const script of column.scripts) {
218
- const deltaX = cursorX - script.originalX;
219
- const deltaY = cursorY - script.originalY;
220
- script.block.x = cursorX;
221
- script.block.y = cursorY;
222
- movements.set(script.blockId, {
223
- deltaX,
224
- deltaY
225
- });
226
- if (deltaX || deltaY) movedScriptCount += 1;
227
- cursorY += script.size.height + turboWarpCleanUpLayout.rowGap;
228
- columnWidth = Math.max(columnWidth, script.size.width, commentWidths.get(script.blockId) ?? 0);
311
+ const moveScript = (script, x, y) => {
312
+ assert(isFiniteNumber(x) && isFiniteNumber(y), "Calculated SB3 layout coordinates must be finite.");
313
+ if (Array.isArray(script.block)) {
314
+ script.block[3] = x;
315
+ script.block[4] = y;
316
+ } else {
317
+ script.block.x = x;
318
+ script.block.y = y;
319
+ }
320
+ const deltaX = x - script.originalX;
321
+ const deltaY = y - script.originalY;
322
+ if (deltaX || deltaY) movements.set(script.blockId, {
323
+ deltaX,
324
+ deltaY
325
+ });
326
+ };
327
+ if (compact) {
328
+ const placements = compactPlacements(columns.flatMap((column) => column.scripts), target, blocks);
329
+ for (const { script, x, y } of placements) moveScript(script, x, y);
330
+ } else {
331
+ const commentWidths = attachedCommentWidths(target, blocks);
332
+ let cursorX = turboWarpCleanUpLayout.startX;
333
+ for (const column of columns) {
334
+ let cursorY = turboWarpCleanUpLayout.startY;
335
+ let columnWidth = 0;
336
+ for (const script of column.scripts) {
337
+ moveScript(script, cursorX, cursorY);
338
+ cursorY += script.size.height + turboWarpCleanUpLayout.rowGap;
339
+ columnWidth = Math.max(columnWidth, script.size.width, commentWidths.get(script.blockId) ?? 0);
340
+ }
341
+ cursorX += columnWidth + turboWarpCleanUpLayout.columnGap;
229
342
  }
230
- cursorX += columnWidth + turboWarpCleanUpLayout.columnGap;
231
343
  }
232
344
  return {
233
345
  movedCommentCount: moveAttachedComments(target, blocks, movements),
234
- movedScriptCount,
346
+ movedScriptCount: movements.size,
235
347
  scriptCount: scripts.length
236
348
  };
237
349
  }
238
- function cleanUpTurboWarpBlocks(project) {
350
+ function cleanUpTurboWarpBlocks(project, { compact = false } = {}) {
239
351
  assert(isObject(project), "TurboWarp project must be an object.");
240
352
  assert(Array.isArray(project.targets), "TurboWarp project targets must be an array.");
241
353
  const cleanedProject = structuredClone(project);
@@ -246,7 +358,7 @@ function cleanUpTurboWarpBlocks(project) {
246
358
  let targetCount = 0;
247
359
  for (const [targetIndex, target] of targets.entries()) {
248
360
  assert(isObject(target), `Project target ${targetIndex} must be an object.`);
249
- const result = cleanUpTarget(target, targetIndex);
361
+ const result = cleanUpTarget(target, targetIndex, compact);
250
362
  if (result.scriptCount > 0) targetCount += 1;
251
363
  movedCommentCount += result.movedCommentCount;
252
364
  movedScriptCount += result.movedScriptCount;
@@ -1 +1 @@
1
- {"version":3,"file":"turbowarp-clean-up.js","names":[],"sources":["../src/turbowarp-clean-up.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport type {ProjectJson, UnknownRecord} from './types';\n\nexport const turboWarpCleanUpLayout = Object.freeze({\n columnGap: 96,\n columnTolerance: 256,\n rowGap: 72,\n startX: 48,\n startY: 64,\n});\n\nconst minimumBlockHeight = 48;\nconst minimumBlockWidth = 160;\nconst nestedStackIndent = 64;\nconst nestedStackPadding = 24;\nconst nextBlockOverlap = 4;\n\ninterface BlockSize {\n height: number;\n width: number;\n}\n\ninterface Script {\n block: UnknownRecord;\n blockId: string;\n inputOrder: number;\n originalX: number;\n originalY: number;\n size: BlockSize;\n}\n\ninterface ScriptColumn {\n count: number;\n scripts: Script[];\n x: number;\n}\n\ninterface ScriptMovement {\n deltaX: number;\n deltaY: number;\n}\n\nexport interface TargetCleanUpResult {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n}\n\nexport interface TurboWarpCleanUpResult extends TargetCleanUpResult {\n project: ProjectJson;\n targetCount: number;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction compareNumbers(left: number, right: number): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction inputBlockId(input: unknown, blocks: UnknownRecord): string | null {\n if (!Array.isArray(input)) return null;\n for (const value of (input as unknown[]).slice(1)) {\n if (typeof value === 'string' && Object.hasOwn(blocks, value)) return value;\n }\n return null;\n}\n\nfunction displayTextLength(block: UnknownRecord): number {\n let length = typeof block.opcode === 'string' ? block.opcode.length : 0;\n if (isObject(block.fields)) {\n for (const field of Object.values(block.fields)) {\n if (Array.isArray(field) && field[0] !== undefined && field[0] !== null) {\n length += String(field[0]).length;\n }\n }\n }\n if (isObject(block.mutation) && typeof block.mutation.proccode === 'string') {\n length += block.mutation.proccode.length;\n }\n return length;\n}\n\nfunction inputDisplayTextLength(input: unknown, blocks: UnknownRecord): number {\n const childId = inputBlockId(input, blocks);\n if (childId) {\n const child = blocks[childId];\n return isObject(child) ? displayTextLength(child) : 0;\n }\n if (!Array.isArray(input)) return 0;\n for (const value of (input as unknown[]).slice(1)) {\n if (!Array.isArray(value) || value.length < 2) continue;\n const displayValue: unknown = value[1];\n if (\n typeof displayValue === 'string' ||\n typeof displayValue === 'number' ||\n typeof displayValue === 'boolean'\n ) {\n return String(displayValue).length;\n }\n }\n return 0;\n}\n\nfunction verticalChildIds(block: UnknownRecord, blocks: UnknownRecord): string[] {\n const childIds: string[] = [];\n if (isObject(block.inputs)) {\n for (const [inputName, input] of Object.entries(block.inputs)) {\n const childId = inputBlockId(input, blocks);\n if (childId && /^SUBSTACK/u.test(inputName)) childIds.push(childId);\n }\n }\n if (typeof block.next === 'string' && Object.hasOwn(blocks, block.next)) {\n childIds.push(block.next);\n }\n return childIds;\n}\n\nfunction measureStack(blockId: string, blocks: UnknownRecord): BlockSize {\n const measured = new Map<string, BlockSize>();\n const active = new Set<string>();\n const work: {blockId: string; finalize: boolean}[] = [{blockId, finalize: false}];\n\n while (work.length > 0) {\n const frame = work.pop();\n if (!frame) break;\n const block = blocks[frame.blockId];\n if (measured.has(frame.blockId) || !isObject(block)) continue;\n if (!frame.finalize) {\n if (active.has(frame.blockId)) continue;\n active.add(frame.blockId);\n work.push({blockId: frame.blockId, finalize: true});\n const childIds = verticalChildIds(block, blocks);\n for (let index = childIds.length - 1; index >= 0; index -= 1) {\n const childId = childIds[index];\n if (!active.has(childId) && !measured.has(childId)) {\n work.push({blockId: childId, finalize: false});\n }\n }\n continue;\n }\n\n let height = minimumBlockHeight;\n let width = Math.max(minimumBlockWidth, 80 + displayTextLength(block) * 8);\n if (isObject(block.inputs)) {\n for (const [inputName, input] of Object.entries(block.inputs)) {\n const childId = inputBlockId(input, blocks);\n if (childId && /^SUBSTACK/u.test(inputName)) {\n const nested = measured.get(childId) ?? {height: 0, width: 0};\n height += nested.height + nestedStackPadding;\n width = Math.max(width, nested.width + nestedStackIndent);\n } else {\n width += 24 + inputDisplayTextLength(input, blocks) * 8;\n }\n }\n }\n if (typeof block.next === 'string' && Object.hasOwn(blocks, block.next)) {\n const next = measured.get(block.next) ?? {height: 0, width: 0};\n height += Math.max(0, next.height - nextBlockOverlap);\n width = Math.max(width, next.width);\n }\n measured.set(frame.blockId, {height, width});\n active.delete(frame.blockId);\n }\n\n return measured.get(blockId) ?? {height: 0, width: 0};\n}\n\nfunction groupIntoColumns(scripts: Script[]): ScriptColumn[] {\n const columns: ScriptColumn[] = [];\n for (const script of scripts) {\n let bestColumn: ScriptColumn | null = null;\n let bestError = Number(turboWarpCleanUpLayout.columnTolerance);\n for (const column of columns) {\n const error = Math.abs(script.originalX - column.x);\n if (error < bestError) {\n bestColumn = column;\n bestError = error;\n }\n }\n if (bestColumn) {\n bestColumn.count += 1;\n bestColumn.x = (bestColumn.x * (bestColumn.count - 1) + script.originalX) / bestColumn.count;\n bestColumn.scripts.push(script);\n } else {\n columns.push({count: 1, scripts: [script], x: script.originalX});\n }\n }\n columns.sort((left, right) => compareNumbers(left.x, right.x));\n for (const column of columns) {\n column.scripts.sort(\n (left, right) =>\n compareNumbers(left.originalY, right.originalY) ||\n compareNumbers(left.inputOrder, right.inputOrder),\n );\n }\n return columns;\n}\n\nfunction findTopBlockId(blockId: unknown, blocks: UnknownRecord): string | null {\n const visited = new Set<string>();\n let currentId: unknown = blockId;\n while (typeof currentId === 'string' && !visited.has(currentId)) {\n visited.add(currentId);\n const block = blocks[currentId];\n if (!isObject(block)) return null;\n if (block.topLevel === true || block.parent === null) return currentId;\n currentId = block.parent;\n }\n return null;\n}\n\nfunction moveAttachedComments(\n target: UnknownRecord,\n blocks: UnknownRecord,\n movements: Map<string, ScriptMovement>,\n): number {\n if (!isObject(target.comments)) return 0;\n let movedCommentCount = 0;\n for (const comment of Object.values(target.comments)) {\n if (!isObject(comment) || typeof comment.blockId !== 'string') continue;\n const topBlockId = findTopBlockId(comment.blockId, blocks);\n const movement = topBlockId === null ? undefined : movements.get(topBlockId);\n if (!movement || (!movement.deltaX && !movement.deltaY)) continue;\n if (isFiniteNumber(comment.x)) comment.x += movement.deltaX;\n if (isFiniteNumber(comment.y)) comment.y += movement.deltaY;\n movedCommentCount += 1;\n }\n return movedCommentCount;\n}\n\nfunction attachedCommentWidths(target: UnknownRecord, blocks: UnknownRecord): Map<string, number> {\n const widths = new Map<string, number>();\n if (!isObject(target.comments)) return widths;\n for (const comment of Object.values(target.comments)) {\n if (\n !isObject(comment) ||\n typeof comment.blockId !== 'string' ||\n !isFiniteNumber(comment.x) ||\n !isFiniteNumber(comment.width)\n ) {\n continue;\n }\n const topBlockId = findTopBlockId(comment.blockId, blocks);\n if (!topBlockId) continue;\n const topBlock = blocks[topBlockId];\n if (!isObject(topBlock) || !isFiniteNumber(topBlock.x)) continue;\n const width = Math.max(comment.width, comment.x + comment.width - topBlock.x);\n widths.set(topBlockId, Math.max(widths.get(topBlockId) ?? 0, width));\n }\n return widths;\n}\n\nfunction cleanUpTarget(target: UnknownRecord, targetIndex: number): TargetCleanUpResult {\n if (target.blocks === undefined) {\n return {movedCommentCount: 0, movedScriptCount: 0, scriptCount: 0};\n }\n assert(isObject(target.blocks), `Project target ${targetIndex} blocks must be an object.`);\n const blocks = target.blocks;\n const scripts: Script[] = [];\n let inputOrder = 0;\n for (const [blockId, block] of Object.entries(blocks)) {\n if (!isObject(block) || block.topLevel !== true) continue;\n assert(\n isFiniteNumber(block.x) && isFiniteNumber(block.y),\n `Top-level block ${JSON.stringify(blockId)} in project target ${targetIndex} requires numeric x and y coordinates.`,\n );\n scripts.push({\n block,\n blockId,\n inputOrder,\n originalX: block.x,\n originalY: block.y,\n size: measureStack(blockId, blocks),\n });\n inputOrder += 1;\n }\n\n const movements = new Map<string, ScriptMovement>();\n const commentWidths = attachedCommentWidths(target, blocks);\n let cursorX: number = turboWarpCleanUpLayout.startX;\n let movedScriptCount = 0;\n for (const column of groupIntoColumns(scripts)) {\n let cursorY: number = turboWarpCleanUpLayout.startY;\n let columnWidth = 0;\n for (const script of column.scripts) {\n const deltaX = cursorX - script.originalX;\n const deltaY = cursorY - script.originalY;\n script.block.x = cursorX;\n script.block.y = cursorY;\n movements.set(script.blockId, {deltaX, deltaY});\n if (deltaX || deltaY) movedScriptCount += 1;\n cursorY += script.size.height + turboWarpCleanUpLayout.rowGap;\n columnWidth = Math.max(\n columnWidth,\n script.size.width,\n commentWidths.get(script.blockId) ?? 0,\n );\n }\n cursorX += columnWidth + turboWarpCleanUpLayout.columnGap;\n }\n\n return {\n movedCommentCount: moveAttachedComments(target, blocks, movements),\n movedScriptCount,\n scriptCount: scripts.length,\n };\n}\n\nexport function cleanUpTurboWarpBlocks(project: ProjectJson): TurboWarpCleanUpResult {\n assert(isObject(project), 'TurboWarp project must be an object.');\n assert(Array.isArray(project.targets), 'TurboWarp project targets must be an array.');\n const cleanedProject = structuredClone(project);\n const targets = cleanedProject.targets as unknown[];\n let movedCommentCount = 0;\n let movedScriptCount = 0;\n let scriptCount = 0;\n let targetCount = 0;\n\n for (const [targetIndex, target] of targets.entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n const result = cleanUpTarget(target, targetIndex);\n if (result.scriptCount > 0) targetCount += 1;\n movedCommentCount += result.movedCommentCount;\n movedScriptCount += result.movedScriptCount;\n scriptCount += result.scriptCount;\n }\n\n return {\n movedCommentCount,\n movedScriptCount,\n project: cleanedProject,\n scriptCount,\n targetCount,\n };\n}\n"],"mappings":";;AAKA,IAAa,yBAAyB,OAAO,OAAO;CAClD,WAAW;CACX,iBAAiB;CACjB,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV,CAAC;AAED,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AAsCzB,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,eAAe,OAAiC;CACvD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAC3D;AAEA,SAAS,eAAe,MAAc,OAAuB;CAC3D,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD;AAEA,SAAS,aAAa,OAAgB,QAAsC;CAC1E,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO;CAClC,KAAK,MAAM,SAAU,MAAoB,MAAM,CAAC,GAC9C,IAAI,OAAO,UAAU,YAAY,OAAO,OAAO,QAAQ,KAAK,GAAG,OAAO;CAExE,OAAO;AACT;AAEA,SAAS,kBAAkB,OAA8B;CACvD,IAAI,SAAS,OAAO,MAAM,WAAW,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U,QAAQ,oBAAoB;GAC1C,WAAW,OAAO,KAAK,SAAS,uBAAuB;GACvD,cAAc,KAAK,IACjB,aACA,OAAO,KAAK,OACZ,cAAc,IAAI,OAAO,OAAO,KAAK,CACvC;EACF;EACA,WAAW,cAAc,uBAAuB;CAClD;CAEA,OAAO;EACL,mBAAmB,qBAAqB,QAAQ,QAAQ,SAAS;EACjE;EACA,aAAa,QAAQ;CACvB;AACF;AAEA,SAAgB,uBAAuB,SAA8C;CACnF,OAAO,SAAS,OAAO,GAAG,sCAAsC;CAChE,OAAO,MAAM,QAAQ,QAAQ,OAAO,GAAG,6CAA6C;CACpF,MAAM,iBAAiB,gBAAgB,OAAO;CAC9C,MAAM,UAAU,eAAe;CAC/B,IAAI,oBAAoB;CACxB,IAAI,mBAAmB;CACvB,IAAI,cAAc;CAClB,IAAI,cAAc;CAElB,KAAK,MAAM,CAAC,aAAa,WAAW,QAAQ,QAAQ,GAAG;EACrD,OAAO,SAAS,MAAM,GAAG,kBAAkB,YAAY,oBAAoB;EAC3E,MAAM,SAAS,cAAc,QAAQ,WAAW;EAChD,IAAI,OAAO,cAAc,GAAG,eAAe;EAC3C,qBAAqB,OAAO;EAC5B,oBAAoB,OAAO;EAC3B,eAAe,OAAO;CACxB;CAEA,OAAO;EACL;EACA;EACA,SAAS;EACT;EACA;CACF;AACF"}
1
+ {"version":3,"file":"turbowarp-clean-up.js","names":[],"sources":["../src/turbowarp-clean-up.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport type {ProjectJson, UnknownRecord} from './types';\n\nexport const turboWarpCleanUpLayout = Object.freeze({\n columnGap: 96,\n columnTolerance: 256,\n rowGap: 72,\n startX: 48,\n startY: 64,\n});\n\nconst minimumBlockHeight = 48;\nconst compactBlockHeight = 64;\nconst minimumBlockWidth = 160;\nconst nestedStackIndent = 64;\nconst nestedStackPadding = 24;\nconst nextBlockOverlap = 4;\n\ninterface BlockSize {\n height: number;\n width: number;\n}\n\ninterface Script {\n block: UnknownRecord | unknown[];\n blockId: string;\n inputOrder: number;\n originalX: number;\n originalY: number;\n size: BlockSize;\n}\n\ninterface ScriptColumn {\n count: number;\n scripts: Script[];\n x: number;\n}\n\ninterface Bounds extends BlockSize {\n x: number;\n y: number;\n}\n\ninterface ScriptMovement {\n deltaX: number;\n deltaY: number;\n}\n\nexport interface TargetCleanUpResult {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n}\n\nexport interface TurboWarpCleanUpResult extends TargetCleanUpResult {\n project: ProjectJson;\n targetCount: number;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction compareNumbers(left: number, right: number): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction inputBlockId(input: unknown, blocks: UnknownRecord): string | null {\n if (!Array.isArray(input)) return null;\n for (const value of (input as unknown[]).slice(1)) {\n if (typeof value === 'string' && Object.hasOwn(blocks, value)) return value;\n }\n return null;\n}\n\nfunction displayTextLength(block: UnknownRecord): number {\n let length = typeof block.opcode === 'string' ? block.opcode.length : 0;\n if (isObject(block.fields)) {\n for (const field of Object.values(block.fields)) {\n if (Array.isArray(field) && field[0] !== undefined && field[0] !== null) {\n length += String(field[0]).length;\n }\n }\n }\n if (isObject(block.mutation) && typeof block.mutation.proccode === 'string') {\n length += block.mutation.proccode.length;\n }\n return length;\n}\n\nfunction inputDisplayTextLength(input: unknown, blocks: UnknownRecord): number {\n const childId = inputBlockId(input, blocks);\n if (childId) {\n const child = blocks[childId];\n return isObject(child) ? displayTextLength(child) : 0;\n }\n if (!Array.isArray(input)) return 0;\n for (const value of (input as unknown[]).slice(1)) {\n if (!Array.isArray(value) || value.length < 2) continue;\n const displayValue: unknown = value[1];\n if (\n typeof displayValue === 'string' ||\n typeof displayValue === 'number' ||\n typeof displayValue === 'boolean'\n ) {\n return String(displayValue).length;\n }\n }\n return 0;\n}\n\nfunction measuredChildIds(block: UnknownRecord, blocks: UnknownRecord, compact: boolean): string[] {\n const childIds: string[] = [];\n if (isObject(block.inputs)) {\n for (const [inputName, input] of Object.entries(block.inputs)) {\n const childId = inputBlockId(input, blocks);\n if (childId && (compact || /^SUBSTACK/u.test(inputName))) childIds.push(childId);\n }\n }\n if (typeof block.next === 'string' && Object.hasOwn(blocks, block.next)) {\n childIds.push(block.next);\n }\n return childIds;\n}\n\nfunction measureStack(blockId: string, blocks: UnknownRecord, compact: boolean): BlockSize {\n const measured = new Map<string, BlockSize>();\n const active = new Set<string>();\n const work: {blockId: string; finalize: boolean}[] = [{blockId, finalize: false}];\n\n while (work.length > 0) {\n const frame = work.pop();\n if (!frame) break;\n const block = blocks[frame.blockId];\n if (measured.has(frame.blockId) || !isObject(block)) continue;\n if (!frame.finalize) {\n if (active.has(frame.blockId)) continue;\n active.add(frame.blockId);\n work.push({blockId: frame.blockId, finalize: true});\n const childIds = measuredChildIds(block, blocks, compact);\n for (let index = childIds.length - 1; index >= 0; index -= 1) {\n const childId = childIds[index];\n if (!active.has(childId) && !measured.has(childId)) {\n work.push({blockId: childId, finalize: false});\n }\n }\n continue;\n }\n\n // Rendered statement blocks can be taller than the legacy cleanup estimate.\n let height = compact ? compactBlockHeight : minimumBlockHeight;\n let width = Math.max(minimumBlockWidth, 80 + displayTextLength(block) * 8);\n if (isObject(block.inputs)) {\n for (const [inputName, input] of Object.entries(block.inputs)) {\n const childId = inputBlockId(input, blocks);\n if (childId && /^SUBSTACK/u.test(inputName)) {\n const nested = measured.get(childId) ?? {height: 0, width: 0};\n height += nested.height + nestedStackPadding;\n width = Math.max(width, nested.width + nestedStackIndent);\n } else {\n const reporter = compact && childId ? measured.get(childId) : undefined;\n width += 24 + (reporter?.width ?? inputDisplayTextLength(input, blocks) * 8);\n if (reporter) height = Math.max(height, reporter.height + 16);\n }\n }\n }\n if (typeof block.next === 'string' && Object.hasOwn(blocks, block.next)) {\n const next = measured.get(block.next) ?? {height: 0, width: 0};\n height += Math.max(0, next.height - nextBlockOverlap);\n width = Math.max(width, next.width);\n }\n measured.set(frame.blockId, {height, width});\n active.delete(frame.blockId);\n }\n\n return measured.get(blockId) ?? {height: 0, width: 0};\n}\n\nfunction groupIntoColumns(scripts: Script[]): ScriptColumn[] {\n const columns: ScriptColumn[] = [];\n for (const script of scripts) {\n let bestColumn: ScriptColumn | null = null;\n let bestError = Number(turboWarpCleanUpLayout.columnTolerance);\n for (const column of columns) {\n const error = Math.abs(script.originalX - column.x);\n if (error < bestError) {\n bestColumn = column;\n bestError = error;\n }\n }\n if (bestColumn) {\n bestColumn.count += 1;\n bestColumn.x = (bestColumn.x * (bestColumn.count - 1) + script.originalX) / bestColumn.count;\n bestColumn.scripts.push(script);\n } else {\n columns.push({count: 1, scripts: [script], x: script.originalX});\n }\n }\n columns.sort((left, right) => compareNumbers(left.x, right.x));\n for (const column of columns) {\n column.scripts.sort(\n (left, right) =>\n compareNumbers(left.originalY, right.originalY) ||\n compareNumbers(left.inputOrder, right.inputOrder),\n );\n }\n return columns;\n}\n\nfunction findTopBlockId(blockId: unknown, blocks: UnknownRecord): string | null {\n const visited = new Set<string>();\n let currentId: unknown = blockId;\n while (typeof currentId === 'string' && !visited.has(currentId)) {\n visited.add(currentId);\n const block = blocks[currentId];\n if (isReporterPrimitive(block)) return currentId;\n if (!isObject(block)) return null;\n if (block.topLevel === true || block.parent === null) return currentId;\n currentId = block.parent;\n }\n return null;\n}\n\nfunction moveAttachedComments(\n target: UnknownRecord,\n blocks: UnknownRecord,\n movements: Map<string, ScriptMovement>,\n): number {\n if (!isObject(target.comments)) return 0;\n let movedCommentCount = 0;\n for (const comment of Object.values(target.comments)) {\n if (!isObject(comment) || typeof comment.blockId !== 'string') continue;\n const topBlockId = findTopBlockId(comment.blockId, blocks);\n const movement = topBlockId === null ? undefined : movements.get(topBlockId);\n if (!movement || (!movement.deltaX && !movement.deltaY)) continue;\n if (isFiniteNumber(comment.x)) comment.x += movement.deltaX;\n if (isFiniteNumber(comment.y)) comment.y += movement.deltaY;\n movedCommentCount += 1;\n }\n return movedCommentCount;\n}\n\nfunction attachedCommentWidths(target: UnknownRecord, blocks: UnknownRecord): Map<string, number> {\n const widths = new Map<string, number>();\n if (!isObject(target.comments)) return widths;\n for (const comment of Object.values(target.comments)) {\n if (\n !isObject(comment) ||\n typeof comment.blockId !== 'string' ||\n !isFiniteNumber(comment.x) ||\n !isFiniteNumber(comment.width)\n ) {\n continue;\n }\n const topBlockId = findTopBlockId(comment.blockId, blocks);\n if (!topBlockId) continue;\n const topBlock = blocks[topBlockId];\n if (!isObject(topBlock) || !isFiniteNumber(topBlock.x)) continue;\n const width = Math.max(comment.width, comment.x + comment.width - topBlock.x);\n widths.set(topBlockId, Math.max(widths.get(topBlockId) ?? 0, width));\n }\n return widths;\n}\n\nfunction isReporterPrimitive(value: unknown): value is unknown[] {\n return Array.isArray(value) && (value[0] === 12 || value[0] === 13) && value.length >= 5;\n}\n\nfunction commentBounds(comment: unknown): Bounds | undefined {\n if (\n !isObject(comment) ||\n !isFiniteNumber(comment.x) ||\n !isFiniteNumber(comment.y) ||\n !isFiniteNumber(comment.width) ||\n !isFiniteNumber(comment.height) ||\n comment.width < 0 ||\n comment.height < 0\n )\n return undefined;\n return {x: comment.x, y: comment.y, width: comment.width, height: comment.height};\n}\n\nfunction compactPlacements(\n scripts: Script[],\n target: UnknownRecord,\n blocks: UnknownRecord,\n): {script: Script; x: number; y: number}[] {\n const {columnGap, rowGap, startX, startY} = turboWarpCleanUpLayout;\n const items = scripts.map((script) => ({\n script,\n left: 0,\n right: script.size.width,\n top: 0,\n bottom: script.size.height,\n }));\n const byId = new Map(items.map((item) => [item.script.blockId, item]));\n const obstacles: Bounds[] = [];\n if (isObject(target.comments)) {\n for (const comment of Object.values(target.comments)) {\n const bounds = commentBounds(comment);\n if (!bounds || !isObject(comment)) continue;\n const topBlockId = findTopBlockId(comment.blockId, blocks);\n const item = topBlockId === null ? undefined : byId.get(topBlockId);\n if (!item) {\n obstacles.push(bounds);\n continue;\n }\n const x = bounds.x - item.script.originalX;\n const y = bounds.y - item.script.originalY;\n item.left = Math.min(item.left, x);\n item.right = Math.max(item.right, x + bounds.width);\n item.top = Math.min(item.top, y);\n item.bottom = Math.max(item.bottom, y + bounds.height);\n }\n }\n obstacles.sort((a, b) => compareNumbers(a.y, b.y));\n\n const placements: {script: Script; x: number; y: number}[] = [];\n let bestScore = Infinity;\n let bestRowCount = 1;\n\n // Try progressively larger column lengths while preserving the original reading order.\n for (let rows = 1; ; rows = Math.min(items.length, rows + Math.ceil(rows / 16))) {\n let width = 0;\n let height = 0;\n for (let first = 0; first < items.length; first += rows) {\n let left = 0;\n let right = 0;\n let columnHeight = 0;\n for (const item of items.slice(first, first + rows)) {\n left = Math.min(left, item.left);\n right = Math.max(right, item.right);\n columnHeight += item.bottom - item.top + rowGap;\n }\n width += right - left + columnGap;\n height = Math.max(height, columnHeight - rowGap);\n }\n // Score the size of the smallest 3:2 rectangle that could contain the layout.\n const score = Math.max((width - columnGap) / 1.5, height);\n if (score < bestScore) {\n bestScore = score;\n bestRowCount = rows;\n }\n if (rows >= items.length) break;\n }\n\n let cursorX: number = startX;\n for (let first = 0; first < items.length; first += bestRowCount) {\n const column = items.slice(first, first + bestRowCount);\n let left = 0;\n let right = 0;\n for (const item of column) {\n left = Math.min(left, item.left);\n right = Math.max(right, item.right);\n }\n const x = cursorX - Math.floor(left);\n let cursorY: number = startY;\n for (const item of column) {\n for (const obstacle of obstacles) {\n if (\n x + item.left < obstacle.x + obstacle.width + columnGap &&\n x + item.right + columnGap > obstacle.x &&\n cursorY < obstacle.y + obstacle.height + rowGap &&\n cursorY + item.bottom - item.top + rowGap > obstacle.y\n )\n cursorY = obstacle.y + obstacle.height + rowGap;\n }\n placements.push({script: item.script, x, y: cursorY - item.top});\n cursorY += item.bottom - item.top + rowGap;\n }\n cursorX = x + Math.ceil(right) + columnGap;\n }\n return placements;\n}\n\nfunction cleanUpTarget(\n target: UnknownRecord,\n targetIndex: number,\n compact: boolean,\n): TargetCleanUpResult {\n if (target.blocks === undefined) {\n return {movedCommentCount: 0, movedScriptCount: 0, scriptCount: 0};\n }\n assert(isObject(target.blocks), `Project target ${targetIndex} blocks must be an object.`);\n const blocks = target.blocks;\n const scripts: Script[] = [];\n for (const [blockId, block] of Object.entries(blocks)) {\n const primitive = compact && isReporterPrimitive(block);\n if (!primitive && (!isObject(block) || block.topLevel !== true)) continue;\n const x = Array.isArray(block) ? block[3] : block.x;\n const y = Array.isArray(block) ? block[4] : block.y;\n assert(\n isFiniteNumber(x) && isFiniteNumber(y),\n `Top-level block ${JSON.stringify(blockId)} in project target ${targetIndex} requires numeric x and y coordinates.`,\n );\n scripts.push({\n block,\n blockId,\n inputOrder: scripts.length,\n originalX: x,\n originalY: y,\n size: primitive\n ? {\n height: minimumBlockHeight,\n width: Math.max(minimumBlockWidth, 80 + String(block[1]).length * 8),\n }\n : measureStack(blockId, blocks, compact),\n });\n }\n\n const columns = groupIntoColumns(scripts);\n const movements = new Map<string, ScriptMovement>();\n const moveScript = (script: Script, x: number, y: number) => {\n assert(\n isFiniteNumber(x) && isFiniteNumber(y),\n 'Calculated SB3 layout coordinates must be finite.',\n );\n if (Array.isArray(script.block)) {\n script.block[3] = x;\n script.block[4] = y;\n } else {\n script.block.x = x;\n script.block.y = y;\n }\n const deltaX = x - script.originalX;\n const deltaY = y - script.originalY;\n if (deltaX || deltaY) movements.set(script.blockId, {deltaX, deltaY});\n };\n\n if (compact) {\n const ordered = columns.flatMap((column) => column.scripts);\n const placements = compactPlacements(ordered, target, blocks);\n for (const {script, x, y} of placements) moveScript(script, x, y);\n } else {\n const commentWidths = attachedCommentWidths(target, blocks);\n let cursorX: number = turboWarpCleanUpLayout.startX;\n for (const column of columns) {\n let cursorY: number = turboWarpCleanUpLayout.startY;\n let columnWidth = 0;\n for (const script of column.scripts) {\n moveScript(script, cursorX, cursorY);\n cursorY += script.size.height + turboWarpCleanUpLayout.rowGap;\n columnWidth = Math.max(\n columnWidth,\n script.size.width,\n commentWidths.get(script.blockId) ?? 0,\n );\n }\n cursorX += columnWidth + turboWarpCleanUpLayout.columnGap;\n }\n }\n\n return {\n movedCommentCount: moveAttachedComments(target, blocks, movements),\n movedScriptCount: movements.size,\n scriptCount: scripts.length,\n };\n}\n\nexport function cleanUpTurboWarpBlocks(\n project: ProjectJson,\n {compact = false}: {compact?: boolean} = {},\n): TurboWarpCleanUpResult {\n assert(isObject(project), 'TurboWarp project must be an object.');\n assert(Array.isArray(project.targets), 'TurboWarp project targets must be an array.');\n const cleanedProject = structuredClone(project);\n const targets = cleanedProject.targets as unknown[];\n let movedCommentCount = 0;\n let movedScriptCount = 0;\n let scriptCount = 0;\n let targetCount = 0;\n\n for (const [targetIndex, target] of targets.entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n const result = cleanUpTarget(target, targetIndex, compact);\n if (result.scriptCount > 0) targetCount += 1;\n movedCommentCount += result.movedCommentCount;\n movedScriptCount += result.movedScriptCount;\n scriptCount += result.scriptCount;\n }\n\n return {\n movedCommentCount,\n movedScriptCount,\n project: cleanedProject,\n scriptCount,\n targetCount,\n };\n}\n"],"mappings":";;AAKA,IAAa,yBAAyB,OAAO,OAAO;CAClD,WAAW;CACX,iBAAiB;CACjB,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV,CAAC;AAED,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAC1B,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AA2CzB,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,eAAe,OAAiC;CACvD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAC3D;AAEA,SAAS,eAAe,MAAc,OAAuB;CAC3D,O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,MAAM,SAAS,cAAc,QAAQ,aAAa,OAAO;EACzD,IAAI,OAAO,cAAc,GAAG,eAAe;EAC3C,qBAAqB,OAAO;EAC5B,oBAAoB,OAAO;EAC3B,eAAe,OAAO;CACxB;CAEA,OAAO;EACL;EACA;EACA,SAAS;EACT;EACA;CACF;AACF"}
@@ -0,0 +1,83 @@
1
+ # Extension digests and retention forms
2
+
3
+ ```bash
4
+ sb3-toolchain extensions digests project.sb3 [another.sb3 ...] [--json]
5
+ ```
6
+
7
+ Reads what each SB3 says about itself and reports, for every extension its manifest names:
8
+
9
+ - the extension ID,
10
+ - the pinned `sha256`,
11
+ - which of the four retention forms the author chose — `remote-non-cacheable`, `remote-cacheable`,
12
+ `embedded-file`, or `embedded-data`,
13
+ - the number of bytes the archive actually holds for it,
14
+ - the digest of those held bytes, when it differs from the pinned one,
15
+ - the recorded URL and, for `embedded-file`, the archive entry path,
16
+ - the requested execution mode.
17
+
18
+ It also reports the project's own `uri`, which is the name a browser's caches and the opener's
19
+ recorded decisions are filed under, and, given more than one SB3, which digests several of those
20
+ projects name and which belong to a single project.
21
+
22
+ ## What this command cannot do
23
+
24
+ **It does not read browser storage.** An extension cache lives in IndexedDB, which belongs to an
25
+ origin _and_ to a browser profile, so no command line can reach the cache the person running it
26
+ actually has — driving a fresh automated browser would only show a profile nobody uses. Only the
27
+ browser knows which projects it has cached, so listing and deleting belong to the screen in
28
+ [`kubohiroya/turbowarp-title-menu#23`](https://github.com/kubohiroya/turbowarp-title-menu/issues/23).
29
+ This command produces the list to compare that state against.
30
+
31
+ **It never decides anything by reachability.** A project URI returns nothing until its author
32
+ publishes there, so a work saved but never published and a published work whose address rotted look
33
+ exactly alike. No URL in an SB3 is contacted, and nothing is ever treated as absent because a
34
+ request failed. An input that was not given is unknown, not absent.
35
+
36
+ ## What the report is for
37
+
38
+ 1. Deciding what belongs in the shared bucket: a digest several projects name is a copy worth
39
+ keeping once rather than per project.
40
+ 2. Feeding the title-menu screen's "remove caches no project still names" mode with the set of
41
+ digests the projects on hand actually name.
42
+ 3. Finding entries left behind after a project was converted from `remote-cacheable` to
43
+ `remote-non-cacheable`. Only `remote-cacheable` can ever leave a copy in a browser, so a digest
44
+ whose `cacheable` is false across every input is one no project still asks to be retained. An
45
+ author who decided those bytes should not be kept has had that decision undone if a browser
46
+ keeps them anyway.
47
+
48
+ ## Reading the output
49
+
50
+ The text report prints one `key=value; ...` line per extension, then one line per distinct digest
51
+ labelled `Shared` (named by more than one input) or `Single`. `size=not-held` means the SB3 carries
52
+ only a reference, so the bytes are not there to measure — not that they are missing. `--json` emits
53
+ the same inventory as JSON, with `projects` in input order and `digests` sorted by digest.
54
+
55
+ ## JavaScript API
56
+
57
+ ```js
58
+ import {inventoryExtensionDigests} from '@kubohiroya/sb3-toolchain';
59
+
60
+ const inventory = await inventoryExtensionDigests(['one.sb3', 'two.sb3']);
61
+
62
+ for (const usage of inventory.digests) {
63
+ if (!usage.cacheable) {
64
+ // No input keeps these bytes in the one form a browser may retain.
65
+ console.log(
66
+ usage.sha256,
67
+ usage.ids,
68
+ usage.projects.map((project) => project.uri),
69
+ );
70
+ }
71
+ }
72
+ ```
73
+
74
+ `inspectSb3ExtensionDigests(inputPath, contents)` reports one already-read archive, and
75
+ `readProjectManifest(project)` validates just the `turboWarpPlus` member of a parsed `project.json`,
76
+ returning `null` when a project carries no manifest. A manifest written before the four names
77
+ existed is refused by naming what replaces each retired spelling, rather than translated into a
78
+ choice its author never made.
79
+
80
+ ## Limits
81
+
82
+ Inputs are accepted up to 64 MiB compressed, 256 MiB expanded, and 4096 ZIP entries, with at most
83
+ 64 extensions per manifest. Duplicate inputs, symbolic links, and non-`.sb3` paths are refused.
package/docs/index.html CHANGED
@@ -69,7 +69,7 @@
69
69
  <body>
70
70
  <header>
71
71
  <h1>SB3 Toolchain</h1>
72
- <p><code>@kubohiroya/sb3-toolchain@0.20.0</code></p>
72
+ <p><code>@kubohiroya/sb3-toolchain@0.22.0</code></p>
73
73
  <nav aria-label="Documentation">
74
74
  <a href="#scope">責務</a><a href="#usage">使い方</a><a href="#api">API</a
75
75
  ><a href="#schemas">Schema</a><a href="#guides">関連文書</a>
@@ -90,7 +90,7 @@
90
90
  <section id="usage">
91
91
  <h2>使い方</h2>
92
92
  <p>公開済みの完全固定versionを使います。</p>
93
- <pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.20.0</code></pre>
93
+ <pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.22.0</code></pre>
94
94
  <pre><code>sb3-toolchain import tmp/project.sb3 --output app
95
95
  sb3-toolchain check app
96
96
  sb3-toolchain build app --output dist/project.sb3</code></pre>
@@ -121,6 +121,12 @@ sb3-toolchain build app --output dist/project.sb3</code></pre>
121
121
  <th><code>bundleExtensions</code></th>
122
122
  <td>管理対象の埋込拡張を一つの権限単位へ静的bundleします。</td>
123
123
  </tr>
124
+ <tr>
125
+ <th><code>inventoryExtensionDigests</code></th>
126
+ <td>
127
+ SB3が述べる各拡張のdigest・保持形式・サイズと作品のURIを読み、複数の作品が共有するdigestを示します。取得もブラウザー保存状態の読み取りも行いません。
128
+ </td>
129
+ </tr>
124
130
  </tbody>
125
131
  </table>
126
132
  <p>
@@ -143,9 +149,11 @@ sb3-toolchain build app --output dist/project.sb3</code></pre>
143
149
  <ul>
144
150
  <li><a href="extension-api-compatibility.md">extension-api-compatibility.md</a></li>
145
151
  <li><a href="extension-bundles.md">extension-bundles.md</a></li>
152
+ <li><a href="extension-digests.md">extension-digests.md</a></li>
146
153
  <li><a href="extension-id-migration.md">extension-id-migration.md</a></li>
147
154
  <li><a href="ja/extension-api-compatibility.md">ja/extension-api-compatibility.md</a></li>
148
155
  <li><a href="ja/extension-bundles.md">ja/extension-bundles.md</a></li>
156
+ <li><a href="ja/extension-digests.md">ja/extension-digests.md</a></li>
149
157
  <li><a href="ja/extension-id-migration.md">ja/extension-id-migration.md</a></li>
150
158
  <li><a href="ja/project-asset-additions.md">ja/project-asset-additions.md</a></li>
151
159
  <li><a href="ja/source-format-v1.md">ja/source-format-v1.md</a></li>
@@ -0,0 +1,81 @@
1
+ # 機能拡張のdigestと保持形式を出す
2
+
3
+ ```bash
4
+ sb3-toolchain extensions digests project.sb3 [another.sb3 ...] [--json]
5
+ ```
6
+
7
+ SB3が自分自身について述べていることを読み、マニフェストが挙げる各機能拡張について次を出力します。
8
+
9
+ - 機能拡張のID
10
+ - 固定された`sha256`
11
+ - 作者が選んだ4つの保持形式のどれか(`remote-non-cacheable` / `remote-cacheable` /
12
+ `embedded-file` / `embedded-data`)
13
+ - そのSB3が実際に保持しているバイト数
14
+ - 保持しているバイト列のdigest(固定値と異なる場合のみ表示)
15
+ - 記録されたURL、`embedded-file`の場合はアーカイブ内のパス
16
+ - 要求された実行モード
17
+
18
+ あわせて作品自身の`uri`を出力します。これはブラウザーのキャッシュと、開いた人の記録済みの判断が
19
+ ひも付けられる名前です。SB3を複数与えた場合は、どのdigestが複数の作品から名指され、どれが1作品だけの
20
+ ものかも出力します。
21
+
22
+ ## このコマンドができないこと
23
+
24
+ **ブラウザーの保存状態は読みません。** 機能拡張のキャッシュはIndexedDBにあり、これはオリジンに属すると
25
+ 同時に**ブラウザーのプロファイル**にも属します。コマンドラインからは、実行する人が実際に持っている
26
+ キャッシュには原理的に届きません。自動化されたブラウザーを新たに起動しても、誰も使っていない
27
+ プロファイルが見えるだけです。どの作品がキャッシュされているかを知っているのはブラウザーだけなので、
28
+ 一覧と削除は[`kubohiroya/turbowarp-title-menu#23`](https://github.com/kubohiroya/turbowarp-title-menu/issues/23)
29
+ の画面が担います。このコマンドは、その状態と照合するための一覧を作る側です。
30
+
31
+ **到達性で何も判断しません。** 作品のURIは作者がそこに公開するまで何も返しません。保存したが未公開の
32
+ 作品と、公開済みだが住所が腐った作品は見分けがつきません。SB3の中のURLには一切アクセスせず、
33
+ リクエストが失敗したことを根拠に何かを「無い」と扱うことはありません。与えなかった入力は「不明」で
34
+ あって「無い」ではありません。
35
+
36
+ ## 何に使うか
37
+
38
+ 1. 共通バケットに何を置くべきかの判断材料。複数の作品が名指すdigestは、作品ごとに持つのではなく
39
+ 一度だけ持つ価値のあるバイト列です。
40
+ 2. title-menuの画面の「どの作品からも名指されなくなったキャッシュを消す」モードへの入力。手元の
41
+ 作品群が実際に名指すdigestの集合を渡します。
42
+ 3. 作品を`remote-cacheable`から`remote-non-cacheable`に変換したあと、取り残された古いエントリーを
43
+ 見つける材料。キャッシュを持ちうるのは`remote-cacheable`だけなので、すべての入力で`cacheable`が
44
+ falseのdigestは、もうどの作品も保持を求めていないバイト列です。作者が「残すな」と決めたのに
45
+ ブラウザーに残り続けるなら、その判断は反故になっています。
46
+
47
+ ## 出力の読み方
48
+
49
+ テキスト出力は機能拡張ごとに`key=value; ...`の1行を、続いてdistinctなdigestごとに1行を出します。
50
+ 後者は複数の入力から名指されていれば`Shared`、1つだけなら`Single`と表示します。`size=not-held`は
51
+ そのSB3が参照だけを持っていて、測るべきバイト列がそこに無いという意味で、失われているのではありません。
52
+ `--json`は同じ内容をJSONで出力します。`projects`は入力順、`digests`はdigest順です。
53
+
54
+ ## JavaScript API
55
+
56
+ ```js
57
+ import {inventoryExtensionDigests} from '@kubohiroya/sb3-toolchain';
58
+
59
+ const inventory = await inventoryExtensionDigests(['one.sb3', 'two.sb3']);
60
+
61
+ for (const usage of inventory.digests) {
62
+ if (!usage.cacheable) {
63
+ // どの入力も、ブラウザーが保持しうる唯一の形式では持っていないバイト列。
64
+ console.log(
65
+ usage.sha256,
66
+ usage.ids,
67
+ usage.projects.map((project) => project.uri),
68
+ );
69
+ }
70
+ }
71
+ ```
72
+
73
+ `inspectSb3ExtensionDigests(inputPath, contents)`は既に読み込んだアーカイブ1件を対象にします。
74
+ `readProjectManifest(project)`は、解析済み`project.json`の`turboWarpPlus`メンバーだけを検証し、
75
+ マニフェストを持たない作品では`null`を返します。4つの名前が存在する前に書かれたマニフェストは、
76
+ 作者がしていない選択を勝手に補う代わりに、廃止された綴りごとに何がそれを置き換えるかを示して拒否します。
77
+
78
+ ## 制限
79
+
80
+ 入力は圧縮サイズ64 MiB、展開サイズ256 MiB、ZIPエントリー数4096まで、マニフェスト1件あたりの機能拡張は
81
+ 64件までです。入力の重複、シンボリックリンク、`.sb3`以外のパスは拒否します。
@@ -2,6 +2,8 @@
2
2
 
3
3
  Kamishibai作品SB3に埋め込まれた実装を一括更新する場合は、[SB3の機能拡張更新](sb3-extension-replacement.md)を参照してください。
4
4
 
5
+ ブラウザーの機能拡張キャッシュと照合する一覧を作る場合は、[機能拡張のdigestと保持形式](extension-digests.md)を参照してください。
6
+
5
7
  [English](../workflows.md)
6
8
 
7
9
  この文書では、Scratch 3またはTurboWarpのSB3をGit内の展開ソースとして管理し、検証済みSB3を再ビルドする
@@ -100,6 +102,21 @@ sb3-toolchain build app --output dist/project.sb3 --clean-up-blocks
100
102
  プロジェクト固有のテストに加えて、生成SB3をTurboWarpで開き、起動、主要な操作、画像、音声、埋め込み
101
103
  機能拡張の動作を確認してください。
102
104
 
105
+ ## 既存の SB3 のブロック配置を整理する
106
+
107
+ ```bash
108
+ sb3-toolchain clean-up project.sb3 --output project-cleaned.sb3
109
+ ```
110
+
111
+ `clean-up` は SB3 を直接読み込み、整理したコピーを別ファイルへ保存します。スクリプトと添付コメントの寸法を
112
+ 推定し、配置全体が横 3: 縦 2 に近づくように列を組み直します。幅や高さが突出したスクリプトがあると、
113
+ その寸法が全体の縦横比を左右します。カスタムブロックを含む場合は、エディターで余白を確認してください。
114
+
115
+ スクリプトと添付コメントの座標を移動し、他のプロジェクトデータや ZIP 内のアセットを保持します。
116
+ 元の配置に戻すには入力ファイルを使います。異なる出力が既にある場合は置換確認または `--yes` が必要です。
117
+ Node API からは `cleanUpSb3({inputPath, outputPath})` を使用できます。生成処理で既に SB3 のバイト列がある場合は
118
+ `cleanUpSb3Archive(bytes).archive` で整理後のバイト列を取得できます。
119
+
103
120
  ## 管理対象の埋め込み機能拡張
104
121
 
105
122
  `embedded-extensions.json`の`source`オブジェクトには、GitHubコミットの来歴またはインストール済みnpm
package/docs/workflows.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # SB3 source-management workflows
2
2
 
3
+ To build the list to compare a browser's extension cache against, see
4
+ [extension digests and retention forms](extension-digests.md).
5
+
3
6
  [日本語版](ja/workflows.md)
4
7
 
5
8
  This document describes the common workflow for managing a Scratch 3 or TurboWarp SB3 as expanded
@@ -98,6 +101,23 @@ the option and rebuild to roll back to the source coordinates.
98
101
  In addition to project-specific tests, open the generated SB3 in TurboWarp and verify startup, primary
99
102
  operations, images, sounds, and embedded extension behavior.
100
103
 
104
+ ## Clean up an existing SB3
105
+
106
+ ```bash
107
+ sb3-toolchain clean-up project.sb3 --output project-cleaned.sb3
108
+ ```
109
+
110
+ `clean-up` reads an SB3 directly and writes a separate copy. It estimates the sizes of stacks
111
+ and attached comments and arranges them in columns, aiming for a 3:2 layout. A single unusually
112
+ wide or tall stack can determine the overall dimensions. Spacing is estimated from the SB3, so
113
+ check the result in the editor when a project uses custom blocks.
114
+
115
+ The command moves each stack with its attached comments, preserves the remaining project data and
116
+ ZIP entry contents, and leaves the input file available for rollback. If a different output already
117
+ exists, confirm replacement or specify `--yes`. The equivalent Node API is
118
+ `cleanUpSb3({inputPath, outputPath})`. For build pipelines that already have SB3 bytes,
119
+ `cleanUpSb3Archive(bytes).archive` returns the arranged archive in memory.
120
+
101
121
  ## Managed embedded extensions
102
122
 
103
123
  The `source` object in `embedded-extensions.json` can record either GitHub commit provenance or an