@kubohiroya/sb3-toolchain 0.24.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.ja.md +5 -2
- package/README.md +5 -2
- package/dist/block-palette.d.ts +60 -0
- package/dist/block-palette.js +295 -0
- package/dist/block-palette.js.map +1 -0
- package/dist/browser.d.ts +13 -4
- package/dist/browser.js +14 -3
- package/dist/browser.js.map +1 -1
- package/dist/build.d.ts +1 -1
- package/dist/clean-up-sb3.d.ts +2 -2
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/constants.js.map +1 -1
- package/dist/expand-archive.d.ts +6 -3
- package/dist/expand-archive.js +14 -3
- package/dist/expand-archive.js.map +1 -1
- package/dist/extension-api-manifest.d.ts +1 -1
- package/dist/extension-bundle-configuration.d.ts +4 -4
- package/dist/extension-bundle-metadata.d.ts +1 -1
- package/dist/extension-bundle.d.ts +3 -3
- package/dist/extension-dependencies.d.ts +1 -1
- package/dist/extension-id-migration.d.ts +2 -2
- package/dist/extension-module-bundle.d.ts +2 -2
- package/dist/extension-sb3-replacement.d.ts +2 -2
- package/dist/extension-sync.d.ts +6 -6
- package/dist/import.d.ts +6 -3
- package/dist/import.js +4 -3
- package/dist/import.js.map +1 -1
- package/dist/index.d.ts +42 -40
- package/dist/index.js +3 -2
- package/dist/npm-extension-source.d.ts +1 -1
- package/dist/output-safety.d.ts +1 -1
- package/dist/output-safety.js +2 -2
- package/dist/output-safety.js.map +1 -1
- package/dist/project-asset-additions.d.ts +1 -1
- package/dist/release-snapshot.d.ts +1 -1
- package/dist/source-format.d.ts +8 -1
- package/dist/source-format.js +10 -2
- package/dist/source-format.js.map +1 -1
- package/dist/source.d.ts +7 -4
- package/dist/source.js +7 -2
- package/dist/source.js.map +1 -1
- package/dist/turbowarp-clean-up.d.ts +1 -1
- package/dist/types.d.ts +2 -0
- package/docs/index.html +4 -2
- package/docs/ja/source-format-v1.md +2 -0
- package/docs/ja/source-format-v2.md +139 -0
- package/docs/source-format-v1.md +3 -0
- package/docs/source-format-v2.md +171 -0
- package/package.json +1 -1
package/dist/source.js.map
CHANGED
|
@@ -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 {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 {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n Sb3SourceManifest,\n} from './types';\n\nexport {sourceFormatVersion} from './source-format';\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\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 try {\n await assertDirectory(rootDirectory, description);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\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 md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\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: bundleConfiguration, extensions} = validateExtensionLayout(\n extensionManifest,\n project,\n extensionFiles,\n validateExtensionSourceMetadata,\n );\n const extensionBundles = validateExtensionBundleConfigurations(bundleConfiguration, extensions);\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 references = collectSourceAssetReferences(project);\n const referencedAssets = new Set<string>();\n for (const {filename, description} of references) {\n if (referencedAssets.has(filename)) continue;\n const contents = assetContents.get(filename);\n assert(contents, `Referenced asset is missing for ${description}: ${filename}`);\n const assetId = filename.slice(0, 32);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === assetId,\n `Asset content hash mismatch for ${description}: expected ${assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(filename);\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":";;;;;;;;;;;;;AAmCA,IAAa,oBAAoB,IAAI,KAAK,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAuChE,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,IAAI;EACF,MAAM,gBAAgB,eAAe,WAAW;CAClD,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO,CAAC;EAChE,MAAM;CACR;CACA,MAAM,QAAkB,CAAC;CAEzB,eAAe,MAAM,WAAmB,mBAA0C;EAChF,MAAM,UAAU,MAAM,QAAQ,WAAW,EAAC,eAAe,KAAI,CAAC;EAC9D,QAAQ,MAAM,MAAM,UAAW,KAAK,OA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AAsB,cAAc;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 {assert, errorMessage} from './assert';\nimport {\n applyBlockPaletteComments,\n resolveBlockPaletteReferences,\n validateBlockPaletteDocument,\n} from './block-palette';\nimport type {BlockPaletteDocument} from './block-palette';\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 {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n Sb3SourceManifest,\n} from './types';\n\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\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 /** `block-palette.json` in source format 2, otherwise null. */\n blockPalette: BlockPaletteDocument | null;\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\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 try {\n await assertDirectory(rootDirectory, description);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\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 md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\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 blockPalette =\n sourceManifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(\n await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.blockPalette),\n 'Block palette settings',\n ),\n );\n resolveBlockPaletteReferences(project, blockPalette);\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: bundleConfiguration, extensions} = validateExtensionLayout(\n extensionManifest,\n project,\n extensionFiles,\n validateExtensionSourceMetadata,\n );\n const extensionBundles = validateExtensionBundleConfigurations(bundleConfiguration, extensions);\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 references = collectSourceAssetReferences(project);\n const referencedAssets = new Set<string>();\n for (const {filename, description} of references) {\n if (referencedAssets.has(filename)) continue;\n const contents = assetContents.get(filename);\n assert(contents, `Referenced asset is missing for ${description}: ${filename}`);\n const assetId = filename.slice(0, 32);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === assetId,\n `Asset content hash mismatch for ${description}: expected ${assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(filename);\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 blockPalette,\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 applyBlockPaletteComments(project, source.blockPalette);\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":";;;;;;;;;;;;;;AA6CA,IAAa,oBAAoB,IAAI,KAAK,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAyChE,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,eA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3D,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"}
|
package/dist/types.d.ts
CHANGED
|
@@ -74,6 +74,8 @@ export interface Sb3SourceManifest {
|
|
|
74
74
|
embeddedExtensions: string;
|
|
75
75
|
assetsDirectory: string;
|
|
76
76
|
archiveEntries: string[];
|
|
77
|
+
/** Present only in source format 2. */
|
|
78
|
+
blockPalette?: string;
|
|
77
79
|
}
|
|
78
80
|
/**
|
|
79
81
|
* `project.json` is treated as an opaque record whose known members are narrowed on demand.
|
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.
|
|
72
|
+
<p><code>@kubohiroya/sb3-toolchain@0.25.1</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.
|
|
93
|
+
<pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.25.1</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>
|
|
@@ -157,9 +157,11 @@ sb3-toolchain build app --output dist/project.sb3</code></pre>
|
|
|
157
157
|
<li><a href="ja/extension-id-migration.md">ja/extension-id-migration.md</a></li>
|
|
158
158
|
<li><a href="ja/project-asset-additions.md">ja/project-asset-additions.md</a></li>
|
|
159
159
|
<li><a href="ja/source-format-v1.md">ja/source-format-v1.md</a></li>
|
|
160
|
+
<li><a href="ja/source-format-v2.md">ja/source-format-v2.md</a></li>
|
|
160
161
|
<li><a href="ja/workflows.md">ja/workflows.md</a></li>
|
|
161
162
|
<li><a href="project-asset-additions.md">project-asset-additions.md</a></li>
|
|
162
163
|
<li><a href="source-format-v1.md">source-format-v1.md</a></li>
|
|
164
|
+
<li><a href="source-format-v2.md">source-format-v2.md</a></li>
|
|
163
165
|
<li><a href="workflows.md">workflows.md</a></li>
|
|
164
166
|
<li>
|
|
165
167
|
<a href="https://github.com/kubohiroya/sb3-toolchain/blob/main/README.md"
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# SB3展開ソース形式v2
|
|
2
|
+
|
|
3
|
+
[English](../source-format-v2.md)
|
|
4
|
+
|
|
5
|
+
形式 v2 は、[形式 v1](source-format-v1.md) にブロックパレットの設定を足したものである。設定とは、スプライト・背景ごとに、ブロックパレットにどのブロックグループを表示するかである。ここに書いていないことは v1 と同じ。
|
|
6
|
+
|
|
7
|
+
## どちらの版で書くか
|
|
8
|
+
|
|
9
|
+
版は作品の中身で決まり、利用者は選ばない。
|
|
10
|
+
|
|
11
|
+
- パレット設定のある作品は、`block-palette.json` を付けて v2 で書く。
|
|
12
|
+
- 設定のない作品は、今までと1バイトも変わらない v1 で書く。設定をすべて消したときは v1 に戻し、`block-palette.json` と `blockPalette` のキーを消す。
|
|
13
|
+
|
|
14
|
+
読み手(`check`・`build`・`import`、ブラウザー版の `validateSourceFiles`・`unpackSb3`)は v1 と v2 を受け付ける。それ以外の版は、出力を変えずに拒否する。v1 しか知らない版のツールは、v2 の作品フォルダの設定を黙って捨てずに、対応していない版として断る。
|
|
15
|
+
|
|
16
|
+
## 構成
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
SOURCE_DIR/
|
|
20
|
+
├── sb3-source.json
|
|
21
|
+
├── project.source.json
|
|
22
|
+
├── embedded-extensions.json
|
|
23
|
+
├── block-palette.json
|
|
24
|
+
├── assets/
|
|
25
|
+
└── extensions/
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`sb3-source.json` は `"formatVersion": 2` で、パレット設定のパスを記録する。
|
|
29
|
+
|
|
30
|
+
```json
|
|
31
|
+
{
|
|
32
|
+
"formatVersion": 2,
|
|
33
|
+
"project": "project.source.json",
|
|
34
|
+
"embeddedExtensions": "embedded-extensions.json",
|
|
35
|
+
"assetsDirectory": "assets",
|
|
36
|
+
"archiveEntries": ["project.json", "<assetId>.svg"],
|
|
37
|
+
"blockPalette": "block-palette.json"
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`blockPalette` は v2 では必須で、v1 では書けない。`embedded-extensions.json` は、独自の `"formatVersion": 1` のままである。
|
|
42
|
+
|
|
43
|
+
## ブロックグループの ID
|
|
44
|
+
|
|
45
|
+
| 種類 | ID |
|
|
46
|
+
| -------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
47
|
+
| 標準 | `motion`・`looks`・`sound`・`events`・`control`・`sensing`・`operators`・`variables`・`lists`・`myBlocks` |
|
|
48
|
+
| 機能拡張(1つのグループ) | `<extensionId>`(例:`pen`) |
|
|
49
|
+
| 機能拡張(複数のグループ) | `<extensionId>/<groupId>`(例:`myExt/geometry`)。`groupId` は英数字・`_`・`-` だけで書く |
|
|
50
|
+
|
|
51
|
+
グループ ID は `^[A-Za-z0-9._-]+(/[A-Za-z0-9_-]+)?$` に合う文字列とする。作品に読み込まれていない機能拡張のグループ ID はエラーにしない。あとで機能拡張を読み込めば表示されるようにするためである。
|
|
52
|
+
|
|
53
|
+
## `block-palette.json`
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"formatVersion": 1,
|
|
58
|
+
"order": [
|
|
59
|
+
"motion",
|
|
60
|
+
"looks",
|
|
61
|
+
"sound",
|
|
62
|
+
"events",
|
|
63
|
+
"control",
|
|
64
|
+
"sensing",
|
|
65
|
+
"operators",
|
|
66
|
+
"variables",
|
|
67
|
+
"lists",
|
|
68
|
+
"myBlocks",
|
|
69
|
+
"pen"
|
|
70
|
+
],
|
|
71
|
+
"sets": {
|
|
72
|
+
"logic": {"name": "ロジック専用", "groups": ["events", "control", "operators", "myExt"]}
|
|
73
|
+
},
|
|
74
|
+
"stage": {
|
|
75
|
+
"groups": [
|
|
76
|
+
"looks",
|
|
77
|
+
"sound",
|
|
78
|
+
"events",
|
|
79
|
+
"control",
|
|
80
|
+
"sensing",
|
|
81
|
+
"operators",
|
|
82
|
+
"variables",
|
|
83
|
+
"lists",
|
|
84
|
+
"myBlocks"
|
|
85
|
+
]
|
|
86
|
+
},
|
|
87
|
+
"sprites": {
|
|
88
|
+
"Sprite1": {"groups": ["events", "control", "operators", "myExt/geometry"]}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- `formatVersion`:パレット設定の形式の版で、`1`。展開ソース形式の版とは別に数える。
|
|
94
|
+
- `order`(省略可):作品全体でのグループの並び。載っていないグループは後ろに並べる。
|
|
95
|
+
- `sets`(省略可):作品全体で使う、名前付きのグループの組。組の ID は `^[A-Za-z_][A-Za-z0-9_-]*$` に合う文字列とし、組ごとに空でない `name` と `groups` を書く。
|
|
96
|
+
- `stage`(省略可):背景に表示するグループ。
|
|
97
|
+
- `sprites`(省略可):スプライトごとに表示するグループ。キーはスプライト名で、作品にあるスプライトを指す。空のオブジェクトは書かず、キーごと省く。
|
|
98
|
+
- `groups` は、既定からの差分ではなく、表示するものをすべて書く。既定が将来変わっても、作品の見え方が変わらないようにするためである。重複はエラーにする。
|
|
99
|
+
- 記録のないスプライト・背景は、エディターの既定のグループで表示する。
|
|
100
|
+
- 知らないキーはエラーにする。`order`・`sets`・`stage`・`sprites` のどれか1つは必要である。
|
|
101
|
+
|
|
102
|
+
ツールは、2 スペースで字下げし、キーを上の例の順に並べ、末尾に改行を付けて書く。
|
|
103
|
+
|
|
104
|
+
## `project.source.json` のコメント参照
|
|
105
|
+
|
|
106
|
+
設定のあるスプライト・背景には、本文が次のとおりのコメントがちょうど1つある。
|
|
107
|
+
|
|
108
|
+
```text
|
|
109
|
+
block-palette:block-palette.json
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
このコメントは、sb3 での ID・位置・大きさ・最小化の状態・並び順を保つ。背景では、`stage`・`order`・`sets` のどれかがあるときにこのコメントを置く。設定のないスプライト・背景にはこのコメントを置かない。参照のあるスプライト・背景に、パレット設定のコメントの本文をそのまま置くこともできない。
|
|
113
|
+
|
|
114
|
+
## sb3 のパレット設定のコメント
|
|
115
|
+
|
|
116
|
+
sb3 では、設定を普通のコメントとして、スプライト・背景ごとに1つずつ入れる。標準の TurboWarp や Scratch 3 で開いて保存し直しても、設定が失われないようにするためである。本文は2行である。
|
|
117
|
+
|
|
118
|
+
```text
|
|
119
|
+
TurboWarp Plus Editor block palette for this sprite. You can delete this comment to reset the palette.
|
|
120
|
+
{"formatVersion":1,"groups":["events","control","operators","myExt/geometry"]} // _twplus_palette_
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- 1行目は英語で固定する。背景では `TurboWarp Plus Editor block palette for the stage. You can delete this comment to reset the palette.` とする。
|
|
124
|
+
- 2行目は1行の JSON で、末尾に印 ` // _twplus_palette_` を付ける。パレット設定のコメントは、コメントの ID ではなくこの印で見分ける。TurboWarp は保存のたびにコメントの ID を付け直すためである。
|
|
125
|
+
- スプライトの JSON のキーは、`formatVersion`・`groups` の順とする。
|
|
126
|
+
- 背景の JSON のキーは、`formatVersion` のあとに、あるものだけ `groups`・`order`・`sets` の順に並べる。
|
|
127
|
+
- 本文全体を 8000 文字(Unicode のコードポイント数)以内にする。Scratch 3 はこれより長いコメントを含む作品を開かないため、`check` と `build` を失敗させる。
|
|
128
|
+
- 新しく置くコメントは、`blockId: null`、`x: 0`、`y: 0`、`width: 200`、`height: 200`、`minimized: true` で作る。
|
|
129
|
+
|
|
130
|
+
## 展開と `build`
|
|
131
|
+
|
|
132
|
+
- **展開(sb3 → 作品フォルダ)**:各スプライト・背景から印の付いたコメントを探し、その JSON を `block-palette.json` の `stage` か `sprites.<名前>` に移す。背景のコメントからは `order` と `sets` も移す。コメントの本文は参照に置き換える。
|
|
133
|
+
- **`build`(作品フォルダ → sb3)**:参照を、上の決まった書式の本文に戻す。パレット設定のコメントが決まった書式どおりの sb3 は、展開して `build` すると同じバイト列に戻る。
|
|
134
|
+
- **本文が決まった書式と違うとき**(手で書き換えた場合など):JSON として読めて検査に通れば取り込み、`build` で決まった書式に書き直すことを展開時に警告する。この場合、元の sb3 と同じバイト列には戻らない。
|
|
135
|
+
- **本文が読めないとき**:普通のコメントとしてそのまま残し、設定はないものとして扱い、展開時に警告する。
|
|
136
|
+
- **1つのスプライト・背景に印の付いたコメントが2つ以上あるとき**:展開を失敗させる。
|
|
137
|
+
- **本文がちょうど `block-palette:block-palette.json` の普通のコメントがあるとき**:参照のために取ってある本文なので、展開を失敗させる。
|
|
138
|
+
|
|
139
|
+
ブラウザー版の `unpackSb3` は、警告を `block-palette-normalized` か `block-palette-invalid` として、`target`・`commentId`・`message` を付けて返す。`importSb3` は結果の `warnings` で返し、CLI はそれを表示する。`validateSourceFiles` は、パレット設定の誤りを `invalid-block-palette` のコードで報告する。
|
package/docs/source-format-v1.md
CHANGED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# SB3 expanded source format v2
|
|
2
|
+
|
|
3
|
+
[日本語版](ja/source-format-v2.md)
|
|
4
|
+
|
|
5
|
+
Format v2 is [format v1](source-format-v1.md) plus block palette settings: which block groups the
|
|
6
|
+
block palette shows for each sprite and for the stage. Everything not described here is the same as
|
|
7
|
+
in v1.
|
|
8
|
+
|
|
9
|
+
## Which version is written
|
|
10
|
+
|
|
11
|
+
The version follows the contents of the project, not a user choice:
|
|
12
|
+
|
|
13
|
+
- A project with block palette settings is written as v2 with `block-palette.json`.
|
|
14
|
+
- A project without them is written as v1, byte for byte as before. When the last setting is
|
|
15
|
+
removed, the folder goes back to v1: `block-palette.json` and the `blockPalette` key are removed.
|
|
16
|
+
|
|
17
|
+
Readers (`check`, `build`, `import`, and the browser `validateSourceFiles` and `unpackSb3`) accept
|
|
18
|
+
v1 and v2. Any other version is rejected without changing the output. Tools that only know v1 reject
|
|
19
|
+
a v2 folder instead of silently dropping its settings.
|
|
20
|
+
|
|
21
|
+
## Layout
|
|
22
|
+
|
|
23
|
+
```text
|
|
24
|
+
SOURCE_DIR/
|
|
25
|
+
├── sb3-source.json
|
|
26
|
+
├── project.source.json
|
|
27
|
+
├── embedded-extensions.json
|
|
28
|
+
├── block-palette.json
|
|
29
|
+
├── assets/
|
|
30
|
+
└── extensions/
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`sb3-source.json` has `"formatVersion": 2` and records the path of the palette settings:
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
{
|
|
37
|
+
"formatVersion": 2,
|
|
38
|
+
"project": "project.source.json",
|
|
39
|
+
"embeddedExtensions": "embedded-extensions.json",
|
|
40
|
+
"assetsDirectory": "assets",
|
|
41
|
+
"archiveEntries": ["project.json", "<assetId>.svg"],
|
|
42
|
+
"blockPalette": "block-palette.json"
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`blockPalette` is required in v2 and not allowed in v1. `embedded-extensions.json` keeps its own
|
|
47
|
+
`"formatVersion": 1`.
|
|
48
|
+
|
|
49
|
+
## Block group IDs
|
|
50
|
+
|
|
51
|
+
| Kind | ID |
|
|
52
|
+
| ----------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
53
|
+
| Standard | `motion`, `looks`, `sound`, `events`, `control`, `sensing`, `operators`, `variables`, `lists`, `myBlocks` |
|
|
54
|
+
| Extension with one group | `<extensionId>`, for example `pen` |
|
|
55
|
+
| Extension with several groups | `<extensionId>/<groupId>`, for example `myExt/geometry`; `groupId` uses letters, digits, `_` and `-` |
|
|
56
|
+
|
|
57
|
+
A group ID matches `^[A-Za-z0-9._-]+(/[A-Za-z0-9_-]+)?$`. Group IDs of extensions that the project
|
|
58
|
+
does not load are not an error, so the groups appear once the extension is added.
|
|
59
|
+
|
|
60
|
+
## `block-palette.json`
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"formatVersion": 1,
|
|
65
|
+
"order": [
|
|
66
|
+
"motion",
|
|
67
|
+
"looks",
|
|
68
|
+
"sound",
|
|
69
|
+
"events",
|
|
70
|
+
"control",
|
|
71
|
+
"sensing",
|
|
72
|
+
"operators",
|
|
73
|
+
"variables",
|
|
74
|
+
"lists",
|
|
75
|
+
"myBlocks",
|
|
76
|
+
"pen"
|
|
77
|
+
],
|
|
78
|
+
"sets": {
|
|
79
|
+
"logic": {"name": "Logic only", "groups": ["events", "control", "operators", "myExt"]}
|
|
80
|
+
},
|
|
81
|
+
"stage": {
|
|
82
|
+
"groups": [
|
|
83
|
+
"looks",
|
|
84
|
+
"sound",
|
|
85
|
+
"events",
|
|
86
|
+
"control",
|
|
87
|
+
"sensing",
|
|
88
|
+
"operators",
|
|
89
|
+
"variables",
|
|
90
|
+
"lists",
|
|
91
|
+
"myBlocks"
|
|
92
|
+
]
|
|
93
|
+
},
|
|
94
|
+
"sprites": {
|
|
95
|
+
"Sprite1": {"groups": ["events", "control", "operators", "myExt/geometry"]}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
- `formatVersion`: the version of the palette settings, `1`. It is counted separately from the
|
|
101
|
+
source format version.
|
|
102
|
+
- `order` (optional): the order of groups in the palette for the whole project. Groups not listed
|
|
103
|
+
come after the listed ones.
|
|
104
|
+
- `sets` (optional): named group sets for the whole project. A set ID matches
|
|
105
|
+
`^[A-Za-z_][A-Za-z0-9_-]*$`; each set has a non-empty `name` and `groups`.
|
|
106
|
+
- `stage` (optional): the groups shown for the stage.
|
|
107
|
+
- `sprites` (optional): the groups shown for each sprite, keyed by sprite name. Every key must be
|
|
108
|
+
an existing sprite. Omit the key rather than writing an empty object.
|
|
109
|
+
- `groups` lists every group to show, not a difference from the default, so a future default does
|
|
110
|
+
not change the project. Duplicates are an error.
|
|
111
|
+
- A sprite or the stage without an entry is shown with the editor's default groups.
|
|
112
|
+
- Unknown keys are an error, and at least one of `order`, `sets`, `stage` and `sprites` must be
|
|
113
|
+
present.
|
|
114
|
+
|
|
115
|
+
Tools write the file as two-space-indented JSON with a trailing newline, with keys in the order
|
|
116
|
+
shown above.
|
|
117
|
+
|
|
118
|
+
## Comment references in `project.source.json`
|
|
119
|
+
|
|
120
|
+
Each sprite or stage that has settings has exactly one comment whose text is:
|
|
121
|
+
|
|
122
|
+
```text
|
|
123
|
+
block-palette:block-palette.json
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The comment keeps the ID, position, size, minimized state and order it had in the SB3. For the
|
|
127
|
+
stage, the comment exists when `stage`, `order` or `sets` is present. A target without settings must
|
|
128
|
+
not have such a comment, and a target with a reference must not also have a raw palette comment.
|
|
129
|
+
|
|
130
|
+
## Palette comments in the SB3
|
|
131
|
+
|
|
132
|
+
In an SB3, the settings are stored as ordinary comments, one per sprite or stage, so that standard
|
|
133
|
+
TurboWarp and Scratch 3 open and save the project without losing them. The text has two lines:
|
|
134
|
+
|
|
135
|
+
```text
|
|
136
|
+
TurboWarp Plus Editor block palette for this sprite. You can delete this comment to reset the palette.
|
|
137
|
+
{"formatVersion":1,"groups":["events","control","operators","myExt/geometry"]} // _twplus_palette_
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
- The first line is fixed English text. The stage uses
|
|
141
|
+
`TurboWarp Plus Editor block palette for the stage. You can delete this comment to reset the palette.`
|
|
142
|
+
- The second line is one-line JSON followed by the marker ` // _twplus_palette_`. A palette comment
|
|
143
|
+
is identified by this marker, not by its comment ID, because TurboWarp renumbers comment IDs on
|
|
144
|
+
every save.
|
|
145
|
+
- Sprite JSON has the keys `formatVersion` and `groups`, in this order.
|
|
146
|
+
- Stage JSON has `formatVersion`, then `groups`, `order` and `sets` when present, in this order.
|
|
147
|
+
- The whole text must be at most 8000 characters (Unicode code points). Scratch 3 refuses to open a
|
|
148
|
+
project with a longer comment, so `check` and `build` fail instead.
|
|
149
|
+
- A new comment is created with `blockId: null`, `x: 0`, `y: 0`, `width: 200`, `height: 200` and
|
|
150
|
+
`minimized: true`.
|
|
151
|
+
|
|
152
|
+
## Unpack and build
|
|
153
|
+
|
|
154
|
+
- **Unpack (SB3 → folder)**: for each sprite and the stage, find the comment with the marker, move
|
|
155
|
+
its JSON into `block-palette.json` (`stage` or `sprites.<name>`; `order` and `sets` from the stage),
|
|
156
|
+
and replace the comment text with the reference.
|
|
157
|
+
- **Build (folder → SB3)**: replace each reference with the canonical text above. Unpacking an SB3
|
|
158
|
+
whose palette comments are canonical and building the result gives back the same bytes.
|
|
159
|
+
- **Non-canonical text** (edited by hand, for example): if the JSON parses and validates, it is
|
|
160
|
+
imported, and unpacking warns that build will rewrite it in the canonical form. The rebuilt SB3 is
|
|
161
|
+
then not byte-identical to the input.
|
|
162
|
+
- **Unreadable text**: the comment is kept as a plain comment, the target has no settings, and
|
|
163
|
+
unpacking warns about it.
|
|
164
|
+
- **Two or more marked comments on one target**: unpacking fails.
|
|
165
|
+
- **A plain comment whose text is exactly `block-palette:block-palette.json`**: unpacking fails,
|
|
166
|
+
because that text is reserved for references.
|
|
167
|
+
|
|
168
|
+
The browser `unpackSb3` returns the warnings as `block-palette-normalized` or
|
|
169
|
+
`block-palette-invalid` with `target`, `commentId` and `message`. `importSb3` returns them in
|
|
170
|
+
`warnings`, and the CLI prints them. `validateSourceFiles` reports palette errors with the code
|
|
171
|
+
`invalid-block-palette`.
|
package/package.json
CHANGED