@kubohiroya/sb3-toolchain 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateExtensionBundleConfigurations} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\nexport const sourceFormatVersion = 1;\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n await assertDirectory(rootDirectory, description);\n const files: string[] = [];\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n manifest.formatVersion === sourceFormatVersion,\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nfunction validateExtensionManifest(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n): {extensionBundles: ExtensionBundleConfiguration[]; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === sourceFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n validateExtensionSourceMetadata(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(path.posix.relative('extensions', extension.source.apiManifest.path));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensions,\n ),\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n return references;\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json',\n );\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles, extensions} = validateExtensionManifest(\n extensionManifest,\n project,\n extensionFiles,\n );\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const referencedAssets = new Set<string>();\n const references = collectAssetReferences(project);\n for (const {asset, description} of references) {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n const contents = assetContents.get(expectedFilename);\n assert(contents, `Referenced asset is missing for ${description}: ${expectedFilename}`);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === asset.assetId,\n `Asset content hash mismatch for ${description}: expected ${asset.assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(expectedFilename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await inspectSb3Source(sourceDirectory, true);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n for (const entryName of projectAssets.archiveEntries) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.extensions.length,\n entryCount: projectAssets.archiveEntries.length,\n projectAssetAdditions: projectAssets.summary,\n source,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,IAAa,sBAAsB;AACnC,IAAa,oBAAoB,IAAI,KAAK,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAuChE,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,eAAe,SAAS,UAAkB,aAAuC;CAC/E,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,UAAU,MAAM,CAAC;CACpD,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,YAAY,sBAAsB,SAAS,IAAI,aAAa,KAAK,EAAE,IAAI,EACxF,OAAO,MACT,CAAC;CACH;AACF;AAEA,eAAe,gBAAgB,eAAuB,aAAoC;CACxF,MAAM,QAAQ,MAAM,MAAM,aAAa;CACvC,OACE,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAC7C,GAAG,YAAY,qDAAqD,eACtE;AACF;AAEA,eAAe,iBAAiB,eAAuB,aAAwC;CAC7F,MAAM,gBAAgB,eAAe,WAAW;CAChD,MAAM,QAAkB,CAAC;CAEzB,eAAe,MAAM,WAAmB,mBAA0C;EAChF,MAAM,UAAU,MAAM,QAAQ,WAAW,EAAC,eAAe,KAAI,CAAC;EAC9D,QAAQ,MAAM,MAAM,UAAW,KAAK,OAAO,MAAM,OAAO,KAAK,KAAK,OAAO,MAAM,OAAO,IAAI,CAAE;EAC5F,KAAK,MAAM,SAAS,SAAS;GAC3B,MAAM,eAAe,oBACjB,KAAK,MAAM,KA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Ac;EAChE;EACA,aAAa,QAAQ;EACrB,wBAAwB,QAAQ,WAAW;EAC3C,YAAY,cAAc,eAAe;EACzC,uBAAuB,cAAc;EACrC;CACF;AACF"}
1
+ {"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateExtensionBundleConfigurations} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\nexport const sourceFormatVersion = 1;\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n await assertDirectory(rootDirectory, description);\n const files: string[] = [];\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n manifest.formatVersion === sourceFormatVersion,\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nfunction validateExtensionManifest(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n): {extensionBundles: ExtensionBundleConfiguration[]; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === sourceFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n validateExtensionSourceMetadata(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(path.posix.relative('extensions', extension.source.apiManifest.path));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensions,\n ),\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n const fonts = project.customFonts ?? [];\n assert(Array.isArray(fonts), 'project.source.json customFonts must be an array.');\n for (const [index, font] of fonts.entries()) {\n if (!isObject(font) || font.system !== false || font.md5ext === undefined) continue;\n const md5ext = font.md5ext;\n const match = typeof md5ext === 'string' && /^([a-f0-9]{32})\\.(ttf|otf|woff2?)$/u.exec(md5ext);\n assert(match, `Invalid font asset reference for font ${index}: ${md5ext}`);\n const [, assetId, dataFormat] = match;\n references.push({asset: {assetId, dataFormat, md5ext}, description: `font ${index}`});\n }\n return references;\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json',\n );\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles, extensions} = validateExtensionManifest(\n extensionManifest,\n project,\n extensionFiles,\n );\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const referencedAssets = new Set<string>();\n const references = collectAssetReferences(project);\n for (const {asset, description} of references) {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n const contents = assetContents.get(expectedFilename);\n assert(contents, `Referenced asset is missing for ${description}: ${expectedFilename}`);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === asset.assetId,\n `Asset content hash mismatch for ${description}: expected ${asset.assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(expectedFilename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await inspectSb3Source(sourceDirectory, true);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n for (const entryName of projectAssets.archiveEntries) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.extensions.length,\n entryCount: projectAssets.archiveEntries.length,\n projectAssetAdditions: projectAssets.summary,\n source,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,IAAa,sBAAsB;AACnC,IAAa,oBAAoB,IAAI,KAAK,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAuChE,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,eAAe,SAAS,UAAkB,aAAuC;CAC/E,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,UAAU,MAAM,CAAC;CACpD,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,YAAY,sBAAsB,SAAS,IAAI,aAAa,KAAK,EAAE,IAAI,EACxF,OAAO,MACT,CAAC;CACH;AACF;AAEA,eAAe,gBAAgB,eAAuB,aAAoC;CACxF,MAAM,QAAQ,MAAM,MAAM,aAAa;CACvC,OACE,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAC7C,GAAG,YAAY,qDAAqD,eACtE;AACF;AAEA,eAAe,iBAAiB,eAAuB,aAAwC;CAC7F,MAAM,gBAA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U,uBAAuB,OAAO;EAC9C,UAAU,QAAQ;EAClB,eAAe;GACb,mBAAmB,QAAQ;GAC3B,kBAAkB,QAAQ;GAC1B,aAAa,QAAQ;GACrB,aAAa,QAAQ;EACvB;CACF;CACA,MAAM,gBAAyC,QAAQ,iBAAiB,CAAC;CACzE,KAAK,MAAM,aAAa,QAAQ,YAAY;EAC1C,MAAM,WAAW,QAAQ,kBAAkB,IAAI,UAAU,EAAE;EAC3D,OAAO,UAAU,uCAAuC,UAAU,IAAI;EACtE,cAAc,UAAU,MAAM,uBAAuB,WAAW,QAAQ;CAC1E;CACA,QAAQ,gBAAgB;CAExB,MAAM,iBAA6C,CAAC;CACpD,KAAK,MAAM,aAAa,cAAc,gBAAgB;EACpD,IAAI,cAAc,gBAAgB;GAChC,eAAe,aAAa,QAAQ,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG;GAClE;EACF;EACA,MAAM,WAAW,cAAc,cAAc,IAAI,SAAS;EAC1D,OAAO,UAAU,kCAAkC,WAAW;EAC9D,eAAe,aAAa;CAC9B;CAMA,OAAO;EACL,SANc,QAAQ,gBAAgB;GACtC,OAAO;GACP,OAAO;EACT,CAGE;EACA,YAAY,cAAc,cAAc;EACxC,qBAAqB,OAAO,sBAAsB,cAAc;EAChE;EACA,aAAa,QAAQ;EACrB,wBAAwB,QAAQ,WAAW;EAC3C,YAAY,cAAc,eAAe;EACzC,uBAAuB,cAAc;EACrC;CACF;AACF"}
@@ -15,4 +15,6 @@ export interface TurboWarpCleanUpResult extends TargetCleanUpResult {
15
15
  project: ProjectJson;
16
16
  targetCount: number;
17
17
  }
18
- export declare function cleanUpTurboWarpBlocks(project: ProjectJson): TurboWarpCleanUpResult;
18
+ export declare function cleanUpTurboWarpBlocks(project: ProjectJson, { compact }?: {
19
+ compact?: boolean;
20
+ }): TurboWarpCleanUpResult;
@@ -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,WAAW,MAAM,OAAO,SAAS;CACtE,IAAI,SAAS,MAAM,MAAM,GAClB;OAAA,MAAM,SAAS,OAAO,OAAO,MAAM,MAAM,GAC5C,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,KAAA,KAAa,MAAM,OAAO,MACjE,UAAU,OAAO,MAAM,EAAE,CAAC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AAQ,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,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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ED
@@ -69,7 +69,7 @@
69
69
  <body>
70
70
  <header>
71
71
  <h1>SB3 Toolchain</h1>
72
- <p><code>@kubohiroya/sb3-toolchain@0.21.0</code></p>
72
+ <p><code>@kubohiroya/sb3-toolchain@0.23.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.21.0</code></pre>
93
+ <pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.23.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>
@@ -188,9 +188,10 @@ APIマニフェストファイルは展開ソースの検証入力であり、SB
188
188
 
189
189
  ## アセット
190
190
 
191
- `assets/`には、`project.source.json`から参照されるコスチュームと音声が含まれます。各ファイル名は
192
- `<assetId>.<dataFormat>`であり、`assetId`は内容のMD5と一致しなければなりません。未参照、欠落、余分な
193
- ファイルはいずれも検証エラーです。
191
+ `assets/`には、`project.source.json`から参照されるコスチューム、音声、埋め込みフォントが含まれます。
192
+ 各ファイル名は `<assetId>.<dataFormat>` で、`assetId` は内容の MD5 と一致する必要があります。
193
+ `customFonts` の `system: false` の項目は、`md5ext` でフォントファイル(`ttf`、`otf`、`woff`、`woff2`)を参照します。
194
+ `system: true` の項目と Web フォントの参照は JSON に保持します。未参照、欠落、余分なファイルはいずれも検証エラーです。
194
195
 
195
196
  ## 決定的出力
196
197
 
@@ -102,6 +102,21 @@ sb3-toolchain build app --output dist/project.sb3 --clean-up-blocks
102
102
  プロジェクト固有のテストに加えて、生成SB3をTurboWarpで開き、起動、主要な操作、画像、音声、埋め込み
103
103
  機能拡張の動作を確認してください。
104
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
+
105
120
  ## 管理対象の埋め込み機能拡張
106
121
 
107
122
  `embedded-extensions.json`の`source`オブジェクトには、GitHubコミットの来歴またはインストール済みnpm
@@ -190,9 +190,11 @@ expanded source; direct `extensions unbundle` of the generated SB3 requires the
190
190
 
191
191
  ## Assets
192
192
 
193
- `assets/` contains costumes and sounds referenced by `project.source.json`. Each filename is
194
- `<assetId>.<dataFormat>`, and `assetId` must match the MD5 of its contents. An unreferenced, missing,
195
- or extra file is a validation error.
193
+ `assets/` contains costumes, sounds, and embedded fonts referenced by `project.source.json`.
194
+ Each filename is `<assetId>.<dataFormat>`, and `assetId` must match the MD5 of its contents.
195
+ A `customFonts` entry with `system: false` references a font file by `md5ext` (`ttf`, `otf`, `woff`, or `woff2`).
196
+ Entries with `system: true` are kept in the JSON, including any web font reference.
197
+ An unreferenced, missing, or extra file is a validation error.
196
198
 
197
199
  ## Deterministic output
198
200
 
package/docs/workflows.md CHANGED
@@ -101,6 +101,23 @@ the option and rebuild to roll back to the source coordinates.
101
101
  In addition to project-specific tests, open the generated SB3 in TurboWarp and verify startup, primary
102
102
  operations, images, sounds, and embedded extension behavior.
103
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
+
104
121
  ## Managed embedded extensions
105
122
 
106
123
  The `source` object in `embedded-extensions.json` can record either GitHub commit provenance or an