@kubohiroya/sb3-toolchain 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.20.0 - 2026-10-29
4
+
5
+ - Kamishibai作品SB3のRuntimeバンドルとBlock Scriptを一括更新する `extensions replace-sb3` とJavaScript APIを追加。
6
+ - `--from`省略時は公式サイトの公開済みブロック台本SB3を自動取得し、公開状態・バージョン・サイズ・SHA-256を検証。指定時はローカルSB3を使用。
7
+ - 作品の台本・素材・保存データ・無関係な機能拡張を保持し、入力や提供元の上書き、自動ダウングレード、検証失敗時の部分更新を防止。
8
+
9
+ Rollback: `@kubohiroya/sb3-toolchain@0.19.1`へ固定し、元の作品SB3を開く。
10
+
3
11
  ## 0.19.1 - 2026-10-29
4
12
 
5
13
  - Preserve explicitly configured bundle presentation metadata in classic and module headers, source configuration, and the CLI.
package/README.ja.md CHANGED
@@ -31,7 +31,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
31
31
  再現可能なインストールのため、検証済みのnpmバージョンを固定します。
32
32
 
33
33
  ```bash
34
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.19.1
34
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.20.0
35
35
  ```
36
36
 
37
37
  ## クイックスタート
@@ -44,6 +44,15 @@ sb3-toolchain check app
44
44
  sb3-toolchain build app --output dist/project.sb3
45
45
  ```
46
46
 
47
+ Kamishibai作品SB3のRuntimeバンドルとBlock Scriptは、一発コマンドで更新できます。
48
+ `--from`省略時は公式サイトの公開済みブロック台本を自動取得します。
49
+
50
+ ```bash
51
+ sb3-toolchain extensions replace-sb3 input.sb3 --output updated.sb3
52
+ ```
53
+
54
+ 提供元の指定方法、保持するデータ、検証と制限は[SB3の機能拡張更新](docs/ja/sb3-extension-replacement.md)を参照してください。
55
+
47
56
  プロジェクトリポジトリに推奨する信頼できる唯一の情報源、再import、置換保護、機能拡張更新、CIの
48
57
  ワークフローについては、[`docs/ja/workflows.md`](docs/ja/workflows.md)を参照してください。
49
58
 
package/README.md CHANGED
@@ -32,7 +32,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
32
32
  Pin the verified npm version for reproducible installation.
33
33
 
34
34
  ```bash
35
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.19.1
35
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.20.0
36
36
  ```
37
37
 
38
38
  ## Quick start
@@ -45,6 +45,16 @@ sb3-toolchain check app
45
45
  sb3-toolchain build app --output dist/project.sb3
46
46
  ```
47
47
 
48
+ Update a Kamishibai SB3's runtime bundle and Block Script together. Omitting `--from`
49
+ downloads and verifies the published block SB3 from the official samples site.
50
+
51
+ ```bash
52
+ sb3-toolchain extensions replace-sb3 input.sb3 --output updated.sb3
53
+ ```
54
+
55
+ See the [replacement guide (Japanese)](docs/ja/sb3-extension-replacement.md) for local donors,
56
+ preserved story data, validation, and limits.
57
+
48
58
  See [`docs/workflows.md`](docs/workflows.md) for the recommended source-of-truth, re-import,
49
59
  replacement protection, extension update, and CI workflows for a project repository.
50
60
 
package/dist/cli.d.ts CHANGED
@@ -80,7 +80,15 @@ export interface ExtensionsUnbundleArchiveCliOptions {
80
80
  outputPath: string;
81
81
  yes: boolean;
82
82
  }
83
- export type ExtensionsCliOptions = ExtensionsStatusCliOptions | ExtensionsMutationCliOptions | ExtensionsMigrateIdCliOptions | ExtensionsBundleCliOptions | ExtensionsUnbundleSourceCliOptions | ExtensionsUnbundleArchiveCliOptions;
83
+ export interface ExtensionsReplaceSb3CliOptions {
84
+ action: 'replace-sb3';
85
+ command: 'extensions';
86
+ fromPath?: string;
87
+ inputPath: string;
88
+ outputPath: string;
89
+ yes: boolean;
90
+ }
91
+ export type ExtensionsCliOptions = ExtensionsReplaceSb3CliOptions | ExtensionsStatusCliOptions | ExtensionsMutationCliOptions | ExtensionsMigrateIdCliOptions | ExtensionsBundleCliOptions | ExtensionsUnbundleSourceCliOptions | ExtensionsUnbundleArchiveCliOptions;
84
92
  export type CliOptions = HelpCliOptions | VersionCliOptions | ImportCliOptions | CheckCliOptions | BuildCliOptions | ExtensionsCliOptions;
85
93
  export interface RunCliOptions {
86
94
  fetch?: FetchImplementation;
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { importSb3 } from "./import.js";
7
7
  import { unbundleSb3 } from "./extension-bundle-archive.js";
8
8
  import { bundleExtensions, unbundleExtensions } from "./extension-bundle-configuration.js";
9
9
  import { migrateExtensionId } from "./extension-id-migration.js";
10
+ import { replaceSb3Extensions } from "./extension-sb3-replacement.js";
10
11
  import { extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
11
12
  import process from "node:process";
12
13
  import path from "node:path";
@@ -17,6 +18,7 @@ function usage() {
17
18
  sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]
18
19
  sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]
19
20
  sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]
21
+ sb3-toolchain extensions replace-sb3 INPUT.sb3 [--from DONOR.sb3] --output OUTPUT.sb3 [--yes]
20
22
  sb3-toolchain extensions status SOURCE_DIR
21
23
  sb3-toolchain extensions sync SOURCE_DIR [--yes]
22
24
  sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]
@@ -42,6 +44,12 @@ Project asset additions:
42
44
  backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the
43
45
  manifest directory unless --allow-asset-root explicitly permits another root.
44
46
 
47
+ Kamishibai SB3 replacement:
48
+ extensions replace-sb3 replaces the runtime bundle and Block Script in INPUT.sb3.
49
+ Omitting --from downloads the published block SB3 from the official samples site
50
+ and verifies its size and SHA-256. --from uses a local donor without network access.
51
+ The input is preserved; output must use a different path. Story data is not migrated.
52
+
45
53
  Replacement safety:
46
54
  Differing outputs require interactive confirmation or --yes.
47
55
  Import refuses to discard uncommitted Git changes unless
@@ -348,9 +356,43 @@ function parseExtensionUnbundleArguments(arguments_) {
348
356
  yes
349
357
  };
350
358
  }
359
+ function parseExtensionReplaceSb3Arguments(arguments_) {
360
+ let fromPath;
361
+ let inputPath;
362
+ let outputPath;
363
+ let yes = false;
364
+ for (let index = 0; index < arguments_.length; index += 1) {
365
+ const argument = arguments_[index];
366
+ if (argument === "--from") {
367
+ assert(!fromPath, "--from may only be specified once.");
368
+ fromPath = path.resolve(takeValue(arguments_, index, "--from"));
369
+ index += 1;
370
+ } else if (argument === "--output") {
371
+ assert(!outputPath, "--output may only be specified once.");
372
+ outputPath = path.resolve(takeValue(arguments_, index, "--output"));
373
+ index += 1;
374
+ } else if (argument === "--yes") yes = true;
375
+ else {
376
+ assert(!argument.startsWith("-"), `Unknown option: ${argument}`);
377
+ assert(!inputPath, "Only one input SB3 may be specified.");
378
+ inputPath = path.resolve(argument);
379
+ }
380
+ }
381
+ assert(inputPath, "The extensions replace-sb3 command requires INPUT.sb3.");
382
+ assert(outputPath, "The extensions replace-sb3 command requires --output OUTPUT.sb3.");
383
+ return {
384
+ action: "replace-sb3",
385
+ command: "extensions",
386
+ fromPath,
387
+ inputPath,
388
+ outputPath,
389
+ yes
390
+ };
391
+ }
351
392
  function parseExtensionsArguments(arguments_) {
352
393
  const [action, ...actionArguments] = arguments_;
353
- assert(action === "bundle" || action === "migrate-id" || action === "status" || action === "sync" || action === "unbundle" || action === "update", "The extensions command requires status, sync, update, migrate-id, bundle, or unbundle.");
394
+ assert(action === "replace-sb3" || action === "bundle" || action === "migrate-id" || action === "status" || action === "sync" || action === "unbundle" || action === "update", "The extensions command requires status, sync, update, migrate-id, bundle, unbundle, or replace-sb3.");
395
+ if (action === "replace-sb3") return parseExtensionReplaceSb3Arguments(actionArguments);
354
396
  if (action === "status") {
355
397
  assert(actionArguments.length === 1 && !actionArguments[0].startsWith("-"), "The extensions status command requires exactly one SOURCE_DIR.");
356
398
  return {
@@ -474,6 +516,20 @@ async function runCli(arguments_, { fetch: fetchImplementation = globalThis.fetc
474
516
  return;
475
517
  }
476
518
  if (options.command === "extensions") {
519
+ if (options.action === "replace-sb3") {
520
+ const result = await replaceSb3Extensions({
521
+ confirmReplace: confirmBuildReplacement,
522
+ fetch: fetchImplementation,
523
+ fromPath: options.fromPath,
524
+ inputPath: options.inputPath,
525
+ outputPath: options.outputPath,
526
+ yes: options.yes
527
+ });
528
+ log(`${result.changed ? "Wrote" : "Already up to date"}: ${result.outputPath} (${result.extensionIds.join(", ")}).`);
529
+ log(`Donor: ${result.donor.source}; version=${result.donor.version ?? "unknown"}; sha256=${result.donor.sha256}`);
530
+ if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
531
+ return;
532
+ }
477
533
  if (options.action === "bundle") {
478
534
  const result = await bundleExtensions({
479
535
  bundleId: options.bundleId,
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport path from 'node:path';\nimport process from 'node:process';\nimport {createInterface} from 'node:readline/promises';\n\nimport {assert} from './assert';\nimport {buildSb3} from './build';\nimport {packageVersion} from './constants';\nimport {unbundleSb3} from './extension-bundle-archive';\nimport {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport type {ExtensionBundleMetadata} from './types';\nimport {migrateExtensionId} from './extension-id-migration';\nimport type {ExtensionIdMigrationCounts, ExtensionIdReference} from './extension-id-migration';\nimport {extensionStatus, syncExtensions, updateExtensions} from './extension-sync';\nimport type {ExtensionSyncConfirmContext, FetchImplementation} from './extension-sync';\nimport {importSb3} from './import';\nimport type {OutputReplacementContext} from './import';\nimport type {DirectoryDifferences} from './output-safety';\nimport {createDeterministicSb3, validateSb3Source} from './source';\n\nexport interface HelpCliOptions {\n command: 'help';\n}\n\nexport interface VersionCliOptions {\n command: 'version';\n}\n\nexport interface ImportCliOptions {\n command: 'import';\n discardLocalChanges: boolean;\n inputPath: string;\n outputDirectory: string;\n yes: boolean;\n}\n\nexport interface CheckCliOptions {\n allowedAssetRoots?: string[];\n command: 'check';\n projectAssetsPath?: string;\n sourceDirectory: string;\n}\n\nexport interface BuildCliOptions {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n command: 'build';\n outputPath: string;\n projectAssetsPath?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsStatusCliOptions {\n action: 'status';\n command: 'extensions';\n sourceDirectory: string;\n}\n\nexport interface ExtensionsMutationCliOptions {\n action: 'sync' | 'update';\n allowBreakingApi?: boolean;\n apiManifestArtifact?: string;\n command: 'extensions';\n extensionId?: string;\n migrateToId?: string;\n sourceArtifact?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsMigrateIdCliOptions {\n action: 'migrate-id';\n command: 'extensions';\n fromId: string;\n sourceDirectory: string;\n toId: string;\n yes: boolean;\n}\n\nexport interface ExtensionsBundleCliOptions {\n action: 'bundle';\n bundleId: string;\n bundleName: string;\n metadata?: ExtensionBundleMetadata;\n command: 'extensions';\n extensionIds: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n yes: boolean;\n buildMode?: 'classic' | 'module';\n sharedDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionsUnbundleSourceCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsUnbundleArchiveCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport type ExtensionsCliOptions =\n | ExtensionsStatusCliOptions\n | ExtensionsMutationCliOptions\n | ExtensionsMigrateIdCliOptions\n | ExtensionsBundleCliOptions\n | ExtensionsUnbundleSourceCliOptions\n | ExtensionsUnbundleArchiveCliOptions;\n\nexport type CliOptions =\n | HelpCliOptions\n | VersionCliOptions\n | ImportCliOptions\n | CheckCliOptions\n | BuildCliOptions\n | ExtensionsCliOptions;\n\nexport interface RunCliOptions {\n fetch?: FetchImplementation;\n log?: (message: string) => void;\n}\n\ninterface MigrationLogResult {\n applied: boolean;\n artifactReady: boolean;\n counts: ExtensionIdMigrationCounts;\n fromId: string | undefined;\n toId: string | undefined;\n totalChanges: number;\n unclassifiedReferences: ExtensionIdReference[];\n}\n\nexport function usage() {\n return `Usage:\n sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]\n sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]\n sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]\n sb3-toolchain extensions status SOURCE_DIR\n sb3-toolchain extensions sync SOURCE_DIR [--yes]\n sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]\n sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]\n sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--metadata-json JSON] [--build-mode classic|module] [--share PACKAGE@EXACT_VERSION] [--include-recovery-capsule] [--yes]\n sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]\n sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]\n\nCommands:\n import Expand an SB3 into Git-friendly source files.\n check Validate an expanded SB3 source directory.\n build Build a deterministic SB3 from expanded sources.\n extensions Inspect, restore, or update managed embedded extensions.\n\nBuild layout cleanup:\n --clean-up-blocks applies a deterministic TurboWarp-style \"Clean up Blocks\"\n layout to every target in the generated SB3. It never deletes blocks,\n variables, lists, or comments. The expanded source is unchanged, but the\n generated SB3 might not be able to undo the coordinate changes.\n\nProject asset additions:\n --project-assets validates a JSON or YAML manifest and adds its sprites,\n backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the\n manifest directory unless --allow-asset-root explicitly permits another root.\n\nReplacement safety:\n Differing outputs require interactive confirmation or --yes.\n Import refuses to discard uncommitted Git changes unless\n --discard-local-changes is also specified. --force is not supported.`;\n}\n\nfunction takeValue(arguments_: string[], index: number, option: string): string {\n const value = arguments_[index + 1];\n assert(value && !value.startsWith('-'), `${option} requires a value.`);\n return value;\n}\n\nfunction parseImportArguments(arguments_: string[]): ImportCliOptions {\n let inputPath: string | undefined;\n let outputDirectory: string | undefined;\n let discardLocalChanges = false;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--output') {\n outputDirectory = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--discard-local-changes') {\n discardLocalChanges = true;\n } else {\n assert(\n argument !== '--force',\n '--force is intentionally unsupported. Use --yes and, only when necessary, ' +\n '--discard-local-changes.',\n );\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n\n assert(inputPath, 'The import command requires INPUT.sb3.');\n assert(outputDirectory, 'The import command requires --output SOURCE_DIR.');\n return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};\n}\n\nfunction parseCheckArguments(arguments_: string[]): CheckCliOptions {\n const allowedAssetRoots: string[] = [];\n let projectAssetsPath: string | undefined;\n let sourceDirectory: string | undefined;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The check command requires SOURCE_DIR.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n command: 'check',\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n };\n}\n\nfunction parseBuildArguments(arguments_: string[]): BuildCliOptions {\n const allowedAssetRoots: string[] = [];\n let cleanUpBlocks = false;\n let sourceDirectory: string | undefined;\n let outputPath: string | undefined;\n let projectAssetsPath: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--clean-up-blocks') {\n cleanUpBlocks = true;\n } else if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n\n assert(sourceDirectory, 'The build command requires SOURCE_DIR.');\n assert(outputPath, 'The build command requires --output OUTPUT.sb3.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n ...(cleanUpBlocks ? {cleanUpBlocks} : {}),\n command: 'build',\n outputPath,\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionMutationArguments(\n action: 'sync' | 'update',\n arguments_: string[],\n): ExtensionsMutationCliOptions {\n let allowBreakingApi = false;\n let apiManifestArtifact: string | undefined;\n let sourceDirectory: string | undefined;\n let extensionId: string | undefined;\n let migrateToId: string | undefined;\n let sourceArtifact: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--allow-breaking-api') {\n assert(action === 'update', '--allow-breaking-api is only valid for extensions update.');\n allowBreakingApi = true;\n } else if (argument === '--migrate-id') {\n assert(action === 'update', '--migrate-id is only valid for extensions update.');\n migrateToId = takeValue(arguments_, index, '--migrate-id');\n index += 1;\n } else if (argument === '--artifact') {\n assert(action === 'update', '--artifact is only valid for extensions update.');\n sourceArtifact = takeValue(arguments_, index, '--artifact');\n index += 1;\n } else if (argument === '--api-manifest-artifact') {\n assert(action === 'update', '--api-manifest-artifact is only valid for extensions update.');\n apiManifestArtifact = takeValue(arguments_, index, '--api-manifest-artifact');\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(action === 'update', `The extensions ${action} command accepts only SOURCE_DIR.`);\n assert(!extensionId, 'Only one EXTENSION_ID may be specified.');\n assert(\n /^[A-Za-z0-9._-]+$/u.test(argument),\n `Invalid embedded extension ID: ${JSON.stringify(argument)}`,\n );\n extensionId = argument;\n }\n }\n }\n\n assert(sourceDirectory, `The extensions ${action} command requires SOURCE_DIR.`);\n assert(\n migrateToId === undefined || extensionId !== undefined,\n '--migrate-id requires an explicit existing EXTENSION_ID.',\n );\n assert(\n sourceArtifact === undefined || migrateToId !== undefined,\n '--artifact requires --migrate-id.',\n );\n assert(\n apiManifestArtifact === undefined || migrateToId !== undefined,\n '--api-manifest-artifact requires --migrate-id.',\n );\n assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');\n return {\n action,\n ...(allowBreakingApi ? {allowBreakingApi} : {}),\n ...(apiManifestArtifact ? {apiManifestArtifact} : {}),\n command: 'extensions',\n extensionId,\n migrateToId,\n sourceArtifact,\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionIdMigrationArguments(arguments_: string[]): ExtensionsMigrateIdCliOptions {\n let fromId: string | undefined;\n let sourceDirectory: string | undefined;\n let toId: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n fromId = takeValue(arguments_, index, '--from');\n index += 1;\n } else if (argument === '--to') {\n toId = takeValue(arguments_, index, '--to');\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The extensions migrate-id command requires SOURCE_DIR.');\n assert(fromId, 'The extensions migrate-id command requires --from OLD_ID.');\n assert(toId, 'The extensions migrate-id command requires --to NEW_ID.');\n return {\n action: 'migrate-id',\n command: 'extensions',\n fromId,\n sourceDirectory,\n toId,\n yes,\n };\n}\n\nfunction parseExtensionBundleArguments(arguments_: string[]): ExtensionsBundleCliOptions {\n let bundleId: string | undefined;\n let bundleName: string | undefined;\n let metadata: ExtensionBundleMetadata | undefined;\n let recoveryCapsule = false;\n let sourceDirectory: string | undefined;\n const extensionIds: string[] = [];\n let yes = false;\n let buildMode: 'classic' | 'module' | undefined;\n const sharedDependencies: Record<string, string> = {};\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--id') {\n bundleId = takeValue(arguments_, index, '--id');\n index += 1;\n } else if (argument === '--name') {\n bundleName = takeValue(arguments_, index, '--name');\n index += 1;\n } else if (argument === '--metadata-json') {\n assert(metadata === undefined, '--metadata-json may only be specified once.');\n const value = takeValue(arguments_, index, '--metadata-json');\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new Error('--metadata-json must contain a JSON object.');\n }\n metadata = validateExtensionBundleMetadata(parsed);\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--include-recovery-capsule') {\n recoveryCapsule = true;\n } else if (argument === '--build-mode') {\n const value = takeValue(arguments_, index, '--build-mode');\n assert(value === 'classic' || value === 'module', '--build-mode must be classic or module.');\n buildMode = value;\n index += 1;\n } else if (argument === '--share') {\n const value = takeValue(arguments_, index, '--share');\n const separator = value.lastIndexOf('@');\n assert(separator > 0, '--share requires PACKAGE@EXACT_VERSION.');\n const name = value.slice(0, separator);\n assert(\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(name),\n `Invalid shared dependency name: ${name}`,\n );\n assert(\n /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u.test(value.slice(separator + 1)),\n '--share requires an exact semantic version.',\n );\n assert(!Object.hasOwn(sharedDependencies, name), `Duplicate shared dependency: ${name}`);\n sharedDependencies[name] = value.slice(separator + 1);\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(\n /^[a-z0-9]+$/u.test(argument),\n `Bundle member ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(argument)}`,\n );\n extensionIds.push(argument);\n }\n }\n }\n assert(sourceDirectory, 'The extensions bundle command requires SOURCE_DIR.');\n assert(bundleId, 'The extensions bundle command requires --id BUNDLE_ID.');\n assert(bundleName, 'The extensions bundle command requires --name NAME.');\n assert(\n !Object.keys(sharedDependencies).length || buildMode === 'module',\n '--share requires --build-mode module.',\n );\n return {\n action: 'bundle',\n bundleId,\n bundleName,\n ...(metadata === undefined ? {} : {metadata}),\n command: 'extensions',\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n yes,\n ...(buildMode === undefined ? {} : {buildMode}),\n ...(Object.keys(sharedDependencies).length ? {sharedDependencies} : {}),\n };\n}\n\nfunction parseExtensionUnbundleArguments(\n arguments_: string[],\n): ExtensionsUnbundleSourceCliOptions | ExtensionsUnbundleArchiveCliOptions {\n let bundleId: string | undefined;\n let input: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!input) {\n input = path.resolve(argument);\n } else {\n assert(!bundleId, 'Only one BUNDLE_ID may be specified.');\n bundleId = argument;\n }\n }\n }\n assert(input, 'The extensions unbundle command requires SOURCE_DIR or INPUT.sb3.');\n assert(bundleId, 'The extensions unbundle command requires BUNDLE_ID.');\n if (path.extname(input).toLowerCase() === '.sb3') {\n assert(outputPath, 'SB3 unbundle requires --output OUTPUT.sb3.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n inputPath: input,\n outputPath,\n yes,\n };\n }\n assert(!outputPath, '--output is only valid when unbundling an SB3 file.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n sourceDirectory: input,\n yes,\n };\n}\n\nfunction parseExtensionsArguments(arguments_: string[]): ExtensionsCliOptions {\n const [action, ...actionArguments] = arguments_;\n assert(\n action === 'bundle' ||\n action === 'migrate-id' ||\n action === 'status' ||\n action === 'sync' ||\n action === 'unbundle' ||\n action === 'update',\n 'The extensions command requires status, sync, update, migrate-id, bundle, or unbundle.',\n );\n if (action === 'status') {\n assert(\n actionArguments.length === 1 && !actionArguments[0].startsWith('-'),\n 'The extensions status command requires exactly one SOURCE_DIR.',\n );\n return {\n action,\n command: 'extensions',\n sourceDirectory: path.resolve(actionArguments[0]),\n };\n }\n if (action === 'migrate-id') {\n return parseExtensionIdMigrationArguments(actionArguments);\n }\n if (action === 'bundle') {\n return parseExtensionBundleArguments(actionArguments);\n }\n if (action === 'unbundle') {\n return parseExtensionUnbundleArguments(actionArguments);\n }\n return parseExtensionMutationArguments(action, actionArguments);\n}\n\nexport function parseCliArguments(arguments_: string[]): CliOptions {\n const normalized = arguments_.filter((argument) => argument !== '--');\n if (normalized.length === 0 || normalized[0] === '--help' || normalized[0] === '-h') {\n return {command: 'help'};\n }\n if (normalized[0] === '--version' || normalized[0] === '-v') {\n return {command: 'version'};\n }\n\n const [command, ...commandArguments] = normalized;\n if (commandArguments.includes('--help') || commandArguments.includes('-h')) {\n return {command: 'help'};\n }\n if (command === 'import') return parseImportArguments(commandArguments);\n if (command === 'check') return parseCheckArguments(commandArguments);\n if (command === 'build') return parseBuildArguments(commandArguments);\n if (command === 'extensions') return parseExtensionsArguments(commandArguments);\n throw new Error(`Unknown command: ${command}`);\n}\n\nfunction formatDifferenceLines(differences: DirectoryDifferences): string {\n const labels: Record<string, string> = {added: '+', modified: '~', removed: '-'};\n const lines = Object.entries(differences).flatMap(([kind, paths]) =>\n paths.map((relativePath: string) => `${labels[kind]} ${relativePath}`),\n );\n const visibleLines = lines.slice(0, 12);\n if (lines.length > visibleLines.length) {\n visibleLines.push(`... and ${lines.length - visibleLines.length} more`);\n }\n return visibleLines.join('\\n');\n}\n\nasync function confirmImportReplacement(context: OutputReplacementContext): Promise<boolean> {\n const {comparison, discardLocalChanges, gitState, outputDirectory} = context;\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Output directory already exists: ${outputDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const gitMessage = gitState.clean\n ? 'Git state: clean'\n : 'Git state: uncommitted changes will be discarded';\n const answer = await readline.question(\n `Existing SB3 source differs from the import candidate:\\n` +\n ` ${outputDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n `${gitMessage}\\n` +\n `${discardLocalChanges ? 'WARNING: --discard-local-changes is active.\\n' : ''}` +\n 'Replace the existing source directory? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmBuildReplacement(outputPath: string): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Existing SB3 output differs: ${outputPath}. Non-interactive replacement requires --yes.`,\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Existing generated SB3 will be replaced:\\n ${outputPath}\\nContinue? [y/N] `,\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmExtensionReplacement({\n comparison,\n sourceDirectory,\n}: ExtensionSyncConfirmContext): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Managed extension files differ in ${sourceDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Managed extension changes will be installed:\\n` +\n ` ${sourceDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n 'Replace these files? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nfunction logMigrationResult(result: MigrationLogResult, log: (message: string) => void): void {\n const counts = Object.entries(result.counts)\n .filter(([, count]) => count > 0)\n .map(([kind, count]) => `${kind}=${count}`)\n .join(', ');\n const action = result.applied ? 'Migrated' : 'Dry run';\n log(\n `${action}: ${result.fromId} -> ${result.toId}; ` +\n `${result.totalChanges} classified changes (${counts || 'none'}); ` +\n `artifact=${result.artifactReady ? 'ready' : 'requires-new-ID'}.`,\n );\n for (const reference of result.unclassifiedReferences) {\n log(\n `Unclassified ${reference.kind}: ${reference.file}${reference.path} = ` +\n JSON.stringify(reference.value),\n );\n }\n}\n\nexport async function runCli(\n arguments_: string[],\n {fetch: fetchImplementation = globalThis.fetch, log = console.log}: RunCliOptions = {},\n): Promise<void> {\n const options = parseCliArguments(arguments_);\n if (options.command === 'help') {\n log(usage());\n return;\n }\n if (options.command === 'version') {\n log(packageVersion);\n return;\n }\n if (options.command === 'check') {\n assert(\n 'sourceDirectory' in options && !('action' in options),\n 'Internal CLI check command routing error.',\n );\n if (options.projectAssetsPath) {\n const result = await createDeterministicSb3(options.sourceDirectory, {\n allowedAssetRoots: options.allowedAssetRoots,\n projectAssetsPath: options.projectAssetsPath,\n });\n log(\n `Valid SB3 source with project assets: ${result.source.resolvedSourceDirectory} ` +\n `(${result.entryCount} entries, ${result.assetCount} assets, ` +\n `${result.assetReferenceCount} references, ${result.embeddedExtensionCount} embedded extensions).`,\n );\n return;\n }\n const result = await validateSb3Source(options.sourceDirectory);\n log(\n `Valid SB3 source: ${result.resolvedSourceDirectory} ` +\n `(${result.sourceManifest.archiveEntries.length} entries, ` +\n `${result.assetContents.size} assets, ${result.assetReferenceCount} references, ` +\n `${result.extensions.length} embedded extensions).`,\n );\n return;\n }\n if (\n options.command === 'build' &&\n 'outputPath' in options &&\n 'sourceDirectory' in options &&\n !('action' in options)\n ) {\n const result = await buildSb3({\n allowedAssetRoots: options.allowedAssetRoots,\n cleanUpBlocks: options.cleanUpBlocks,\n confirmReplace: confirmBuildReplacement,\n outputPath: options.outputPath,\n projectAssetsPath: options.projectAssetsPath,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n const action = result.changed ? 'Built' : 'Already up to date';\n const cleanUpMessage = result.blockCleanUp\n ? `, ${result.blockCleanUp.movedScriptCount}/${result.blockCleanUp.scriptCount} scripts laid out`\n : '';\n log(\n `${action}: ${result.outputPath} (${result.entryCount} entries, ` +\n `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions` +\n `${cleanUpMessage}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.command === 'extensions') {\n if (options.action === 'bundle') {\n const result = await bundleExtensions({\n bundleId: options.bundleId,\n bundleName: options.bundleName,\n metadata: options.metadata,\n extensionIds: options.extensionIds,\n recoveryCapsule: options.recoveryCapsule,\n buildMode: options.buildMode,\n sharedDependencies: options.sharedDependencies,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Configured' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'unbundle') {\n if ('inputPath' in options) {\n const result = await unbundleSb3({\n bundleId: options.bundleId,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Wrote' : 'Dry run'} unbundled SB3: ${result.bundleId} ` +\n `(${result.members.join(', ')}) -> ${result.outputPath}.`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n const result = await unbundleExtensions({\n bundleId: options.bundleId,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Removed' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'migrate-id') {\n const result = await migrateExtensionId({\n fromId: options.fromId,\n sourceDirectory: options.sourceDirectory,\n toId: options.toId,\n yes: options.yes,\n });\n logMigrationResult(result, log);\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'status') {\n const statuses = await extensionStatus(options.sourceDirectory, {\n fetch: fetchImplementation,\n });\n if (statuses.length === 0) {\n log(`No managed embedded extensions: ${options.sourceDirectory}`);\n return;\n }\n for (const status of statuses) {\n if ('package' in status) {\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.package}@${status.version} (installed ${status.installedVersion})`,\n );\n continue;\n }\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.ref} -> ${status.remoteCommit} ` +\n `(installed ${status.resolvedCommit})`,\n );\n }\n return;\n }\n\n const operationOptions = {\n confirmReplace: confirmExtensionReplacement,\n fetch: fetchImplementation,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n };\n const result =\n options.action === 'sync'\n ? await syncExtensions(operationOptions)\n : await updateExtensions({\n ...operationOptions,\n allowBreakingApi: options.allowBreakingApi,\n apiManifestArtifact: options.apiManifestArtifact,\n extensionId: options.extensionId,\n migrateToId: options.migrateToId,\n sourceArtifact: options.sourceArtifact,\n });\n const action = result.changed ? 'Updated' : 'Already up to date';\n log(\n `${action}: ${result.sourceDirectory} ` +\n `(${result.extensions.map((extension) => extension.id).join(', ')}).`,\n );\n if (result.migration) {\n logMigrationResult(\n {\n applied: result.changed,\n artifactReady: true,\n ...result.migration,\n },\n log,\n );\n }\n for (const compatibility of result.apiCompatibility) {\n for (const change of compatibility.changes) {\n log(\n `API ${compatibility.id}: ${change.breaking ? 'breaking' : 'compatible'} ` +\n `${change.kind} ${change.path}`,\n );\n }\n }\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n\n assert(\n options.command === 'import' && 'inputPath' in options,\n 'Internal CLI command routing error.',\n );\n const result = await importSb3({\n confirmReplace: confirmImportReplacement,\n discardLocalChanges: options.discardLocalChanges,\n inputPath: options.inputPath,\n outputDirectory: options.outputDirectory,\n yes: options.yes,\n });\n if (result.changed) {\n const differenceMessage = result.differenceCounts\n ? ` Changes: +${result.differenceCounts.added} ` +\n `~${result.differenceCounts.modified} -${result.differenceCounts.removed}.`\n : '';\n log(\n `Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} ` +\n `(${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` +\n differenceMessage,\n );\n } else {\n log(`Already up to date; no files changed: ${result.outputDirectory}`);\n }\n if (result.rollbackCleanupWarning) log(result.rollbackClean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,CAAC;CACD,IAAI,OAAO,SAAS;EAClB,MAAM,oBAAoB,OAAO,mBAC7B,cAAc,OAAO,iBAAiB,MAAM,IACxC,OAAO,iBAAiB,SAAS,IAAI,OAAO,iBAAiB,QAAQ,KACzE;EACJ,IACE,YAAY,OAAO,kBAAkB,oBAAoB,OAAO,gBAAgB,IAC1E,OAAO,WAAW,WAAW,OAAO,uBAAuB,0BAC/D,iBACJ;CACF,OACE,IAAI,yCAAyC,OAAO,iBAAiB;CAEvE,IAAI,OAAO,wBAAwB,IAAI,OAAO,sBAAsB;AACtE"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport path from 'node:path';\nimport process from 'node:process';\nimport {createInterface} from 'node:readline/promises';\n\nimport {assert} from './assert';\nimport {buildSb3} from './build';\nimport {packageVersion} from './constants';\nimport {unbundleSb3} from './extension-bundle-archive';\nimport {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport type {ExtensionBundleMetadata} from './types';\nimport {migrateExtensionId} from './extension-id-migration';\nimport {replaceSb3Extensions} from './extension-sb3-replacement';\nimport type {ExtensionIdMigrationCounts, ExtensionIdReference} from './extension-id-migration';\nimport {extensionStatus, syncExtensions, updateExtensions} from './extension-sync';\nimport type {ExtensionSyncConfirmContext, FetchImplementation} from './extension-sync';\nimport {importSb3} from './import';\nimport type {OutputReplacementContext} from './import';\nimport type {DirectoryDifferences} from './output-safety';\nimport {createDeterministicSb3, validateSb3Source} from './source';\n\nexport interface HelpCliOptions {\n command: 'help';\n}\n\nexport interface VersionCliOptions {\n command: 'version';\n}\n\nexport interface ImportCliOptions {\n command: 'import';\n discardLocalChanges: boolean;\n inputPath: string;\n outputDirectory: string;\n yes: boolean;\n}\n\nexport interface CheckCliOptions {\n allowedAssetRoots?: string[];\n command: 'check';\n projectAssetsPath?: string;\n sourceDirectory: string;\n}\n\nexport interface BuildCliOptions {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n command: 'build';\n outputPath: string;\n projectAssetsPath?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsStatusCliOptions {\n action: 'status';\n command: 'extensions';\n sourceDirectory: string;\n}\n\nexport interface ExtensionsMutationCliOptions {\n action: 'sync' | 'update';\n allowBreakingApi?: boolean;\n apiManifestArtifact?: string;\n command: 'extensions';\n extensionId?: string;\n migrateToId?: string;\n sourceArtifact?: string;\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsMigrateIdCliOptions {\n action: 'migrate-id';\n command: 'extensions';\n fromId: string;\n sourceDirectory: string;\n toId: string;\n yes: boolean;\n}\n\nexport interface ExtensionsBundleCliOptions {\n action: 'bundle';\n bundleId: string;\n bundleName: string;\n metadata?: ExtensionBundleMetadata;\n command: 'extensions';\n extensionIds: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n yes: boolean;\n buildMode?: 'classic' | 'module';\n sharedDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionsUnbundleSourceCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n sourceDirectory: string;\n yes: boolean;\n}\n\nexport interface ExtensionsUnbundleArchiveCliOptions {\n action: 'unbundle';\n bundleId: string;\n command: 'extensions';\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport interface ExtensionsReplaceSb3CliOptions {\n action: 'replace-sb3';\n command: 'extensions';\n fromPath?: string;\n inputPath: string;\n outputPath: string;\n yes: boolean;\n}\n\nexport type ExtensionsCliOptions =\n | ExtensionsReplaceSb3CliOptions\n | ExtensionsStatusCliOptions\n | ExtensionsMutationCliOptions\n | ExtensionsMigrateIdCliOptions\n | ExtensionsBundleCliOptions\n | ExtensionsUnbundleSourceCliOptions\n | ExtensionsUnbundleArchiveCliOptions;\n\nexport type CliOptions =\n | HelpCliOptions\n | VersionCliOptions\n | ImportCliOptions\n | CheckCliOptions\n | BuildCliOptions\n | ExtensionsCliOptions;\n\nexport interface RunCliOptions {\n fetch?: FetchImplementation;\n log?: (message: string) => void;\n}\n\ninterface MigrationLogResult {\n applied: boolean;\n artifactReady: boolean;\n counts: ExtensionIdMigrationCounts;\n fromId: string | undefined;\n toId: string | undefined;\n totalChanges: number;\n unclassifiedReferences: ExtensionIdReference[];\n}\n\nexport function usage() {\n return `Usage:\n sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]\n sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]\n sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]\n sb3-toolchain extensions replace-sb3 INPUT.sb3 [--from DONOR.sb3] --output OUTPUT.sb3 [--yes]\n sb3-toolchain extensions status SOURCE_DIR\n sb3-toolchain extensions sync SOURCE_DIR [--yes]\n sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]\n sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]\n sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--metadata-json JSON] [--build-mode classic|module] [--share PACKAGE@EXACT_VERSION] [--include-recovery-capsule] [--yes]\n sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]\n sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]\n\nCommands:\n import Expand an SB3 into Git-friendly source files.\n check Validate an expanded SB3 source directory.\n build Build a deterministic SB3 from expanded sources.\n extensions Inspect, restore, or update managed embedded extensions.\n\nBuild layout cleanup:\n --clean-up-blocks applies a deterministic TurboWarp-style \"Clean up Blocks\"\n layout to every target in the generated SB3. It never deletes blocks,\n variables, lists, or comments. The expanded source is unchanged, but the\n generated SB3 might not be able to undo the coordinate changes.\n\nProject asset additions:\n --project-assets validates a JSON or YAML manifest and adds its sprites,\n backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the\n manifest directory unless --allow-asset-root explicitly permits another root.\n\nKamishibai SB3 replacement:\n extensions replace-sb3 replaces the runtime bundle and Block Script in INPUT.sb3.\n Omitting --from downloads the published block SB3 from the official samples site\n and verifies its size and SHA-256. --from uses a local donor without network access.\n The input is preserved; output must use a different path. Story data is not migrated.\n\nReplacement safety:\n Differing outputs require interactive confirmation or --yes.\n Import refuses to discard uncommitted Git changes unless\n --discard-local-changes is also specified. --force is not supported.`;\n}\n\nfunction takeValue(arguments_: string[], index: number, option: string): string {\n const value = arguments_[index + 1];\n assert(value && !value.startsWith('-'), `${option} requires a value.`);\n return value;\n}\n\nfunction parseImportArguments(arguments_: string[]): ImportCliOptions {\n let inputPath: string | undefined;\n let outputDirectory: string | undefined;\n let discardLocalChanges = false;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--output') {\n outputDirectory = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--discard-local-changes') {\n discardLocalChanges = true;\n } else {\n assert(\n argument !== '--force',\n '--force is intentionally unsupported. Use --yes and, only when necessary, ' +\n '--discard-local-changes.',\n );\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n\n assert(inputPath, 'The import command requires INPUT.sb3.');\n assert(outputDirectory, 'The import command requires --output SOURCE_DIR.');\n return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};\n}\n\nfunction parseCheckArguments(arguments_: string[]): CheckCliOptions {\n const allowedAssetRoots: string[] = [];\n let projectAssetsPath: string | undefined;\n let sourceDirectory: string | undefined;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The check command requires SOURCE_DIR.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n command: 'check',\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n };\n}\n\nfunction parseBuildArguments(arguments_: string[]): BuildCliOptions {\n const allowedAssetRoots: string[] = [];\n let cleanUpBlocks = false;\n let sourceDirectory: string | undefined;\n let outputPath: string | undefined;\n let projectAssetsPath: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--clean-up-blocks') {\n cleanUpBlocks = true;\n } else if (argument === '--project-assets') {\n projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));\n index += 1;\n } else if (argument === '--allow-asset-root') {\n allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));\n index += 1;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n\n assert(sourceDirectory, 'The build command requires SOURCE_DIR.');\n assert(outputPath, 'The build command requires --output OUTPUT.sb3.');\n assert(\n allowedAssetRoots.length === 0 || projectAssetsPath,\n '--allow-asset-root requires --project-assets.',\n );\n return {\n ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),\n ...(cleanUpBlocks ? {cleanUpBlocks} : {}),\n command: 'build',\n outputPath,\n ...(projectAssetsPath ? {projectAssetsPath} : {}),\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionMutationArguments(\n action: 'sync' | 'update',\n arguments_: string[],\n): ExtensionsMutationCliOptions {\n let allowBreakingApi = false;\n let apiManifestArtifact: string | undefined;\n let sourceDirectory: string | undefined;\n let extensionId: string | undefined;\n let migrateToId: string | undefined;\n let sourceArtifact: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--allow-breaking-api') {\n assert(action === 'update', '--allow-breaking-api is only valid for extensions update.');\n allowBreakingApi = true;\n } else if (argument === '--migrate-id') {\n assert(action === 'update', '--migrate-id is only valid for extensions update.');\n migrateToId = takeValue(arguments_, index, '--migrate-id');\n index += 1;\n } else if (argument === '--artifact') {\n assert(action === 'update', '--artifact is only valid for extensions update.');\n sourceArtifact = takeValue(arguments_, index, '--artifact');\n index += 1;\n } else if (argument === '--api-manifest-artifact') {\n assert(action === 'update', '--api-manifest-artifact is only valid for extensions update.');\n apiManifestArtifact = takeValue(arguments_, index, '--api-manifest-artifact');\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(action === 'update', `The extensions ${action} command accepts only SOURCE_DIR.`);\n assert(!extensionId, 'Only one EXTENSION_ID may be specified.');\n assert(\n /^[A-Za-z0-9._-]+$/u.test(argument),\n `Invalid embedded extension ID: ${JSON.stringify(argument)}`,\n );\n extensionId = argument;\n }\n }\n }\n\n assert(sourceDirectory, `The extensions ${action} command requires SOURCE_DIR.`);\n assert(\n migrateToId === undefined || extensionId !== undefined,\n '--migrate-id requires an explicit existing EXTENSION_ID.',\n );\n assert(\n sourceArtifact === undefined || migrateToId !== undefined,\n '--artifact requires --migrate-id.',\n );\n assert(\n apiManifestArtifact === undefined || migrateToId !== undefined,\n '--api-manifest-artifact requires --migrate-id.',\n );\n assert(!allowBreakingApi || yes, '--allow-breaking-api requires --yes.');\n return {\n action,\n ...(allowBreakingApi ? {allowBreakingApi} : {}),\n ...(apiManifestArtifact ? {apiManifestArtifact} : {}),\n command: 'extensions',\n extensionId,\n migrateToId,\n sourceArtifact,\n sourceDirectory,\n yes,\n };\n}\n\nfunction parseExtensionIdMigrationArguments(arguments_: string[]): ExtensionsMigrateIdCliOptions {\n let fromId: string | undefined;\n let sourceDirectory: string | undefined;\n let toId: string | undefined;\n let yes = false;\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n fromId = takeValue(arguments_, index, '--from');\n index += 1;\n } else if (argument === '--to') {\n toId = takeValue(arguments_, index, '--to');\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');\n sourceDirectory = path.resolve(argument);\n }\n }\n assert(sourceDirectory, 'The extensions migrate-id command requires SOURCE_DIR.');\n assert(fromId, 'The extensions migrate-id command requires --from OLD_ID.');\n assert(toId, 'The extensions migrate-id command requires --to NEW_ID.');\n return {\n action: 'migrate-id',\n command: 'extensions',\n fromId,\n sourceDirectory,\n toId,\n yes,\n };\n}\n\nfunction parseExtensionBundleArguments(arguments_: string[]): ExtensionsBundleCliOptions {\n let bundleId: string | undefined;\n let bundleName: string | undefined;\n let metadata: ExtensionBundleMetadata | undefined;\n let recoveryCapsule = false;\n let sourceDirectory: string | undefined;\n const extensionIds: string[] = [];\n let yes = false;\n let buildMode: 'classic' | 'module' | undefined;\n const sharedDependencies: Record<string, string> = {};\n\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--id') {\n bundleId = takeValue(arguments_, index, '--id');\n index += 1;\n } else if (argument === '--name') {\n bundleName = takeValue(arguments_, index, '--name');\n index += 1;\n } else if (argument === '--metadata-json') {\n assert(metadata === undefined, '--metadata-json may only be specified once.');\n const value = takeValue(arguments_, index, '--metadata-json');\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n throw new Error('--metadata-json must contain a JSON object.');\n }\n metadata = validateExtensionBundleMetadata(parsed);\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else if (argument === '--include-recovery-capsule') {\n recoveryCapsule = true;\n } else if (argument === '--build-mode') {\n const value = takeValue(arguments_, index, '--build-mode');\n assert(value === 'classic' || value === 'module', '--build-mode must be classic or module.');\n buildMode = value;\n index += 1;\n } else if (argument === '--share') {\n const value = takeValue(arguments_, index, '--share');\n const separator = value.lastIndexOf('@');\n assert(separator > 0, '--share requires PACKAGE@EXACT_VERSION.');\n const name = value.slice(0, separator);\n assert(\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(name),\n `Invalid shared dependency name: ${name}`,\n );\n assert(\n /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u.test(value.slice(separator + 1)),\n '--share requires an exact semantic version.',\n );\n assert(!Object.hasOwn(sharedDependencies, name), `Duplicate shared dependency: ${name}`);\n sharedDependencies[name] = value.slice(separator + 1);\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!sourceDirectory) {\n sourceDirectory = path.resolve(argument);\n } else {\n assert(\n /^[a-z0-9]+$/u.test(argument),\n `Bundle member ID must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(argument)}`,\n );\n extensionIds.push(argument);\n }\n }\n }\n assert(sourceDirectory, 'The extensions bundle command requires SOURCE_DIR.');\n assert(bundleId, 'The extensions bundle command requires --id BUNDLE_ID.');\n assert(bundleName, 'The extensions bundle command requires --name NAME.');\n assert(\n !Object.keys(sharedDependencies).length || buildMode === 'module',\n '--share requires --build-mode module.',\n );\n return {\n action: 'bundle',\n bundleId,\n bundleName,\n ...(metadata === undefined ? {} : {metadata}),\n command: 'extensions',\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n yes,\n ...(buildMode === undefined ? {} : {buildMode}),\n ...(Object.keys(sharedDependencies).length ? {sharedDependencies} : {}),\n };\n}\n\nfunction parseExtensionUnbundleArguments(\n arguments_: string[],\n): ExtensionsUnbundleSourceCliOptions | ExtensionsUnbundleArchiveCliOptions {\n let bundleId: string | undefined;\n let input: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--yes') {\n yes = true;\n } else if (argument === '--output') {\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n if (!input) {\n input = path.resolve(argument);\n } else {\n assert(!bundleId, 'Only one BUNDLE_ID may be specified.');\n bundleId = argument;\n }\n }\n }\n assert(input, 'The extensions unbundle command requires SOURCE_DIR or INPUT.sb3.');\n assert(bundleId, 'The extensions unbundle command requires BUNDLE_ID.');\n if (path.extname(input).toLowerCase() === '.sb3') {\n assert(outputPath, 'SB3 unbundle requires --output OUTPUT.sb3.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n inputPath: input,\n outputPath,\n yes,\n };\n }\n assert(!outputPath, '--output is only valid when unbundling an SB3 file.');\n return {\n action: 'unbundle',\n bundleId,\n command: 'extensions',\n sourceDirectory: input,\n yes,\n };\n}\n\nfunction parseExtensionReplaceSb3Arguments(arguments_: string[]): ExtensionsReplaceSb3CliOptions {\n let fromPath: string | undefined;\n let inputPath: string | undefined;\n let outputPath: string | undefined;\n let yes = false;\n for (let index = 0; index < arguments_.length; index += 1) {\n const argument = arguments_[index];\n if (argument === '--from') {\n assert(!fromPath, '--from may only be specified once.');\n fromPath = path.resolve(takeValue(arguments_, index, '--from'));\n index += 1;\n } else if (argument === '--output') {\n assert(!outputPath, '--output may only be specified once.');\n outputPath = path.resolve(takeValue(arguments_, index, '--output'));\n index += 1;\n } else if (argument === '--yes') {\n yes = true;\n } else {\n assert(!argument.startsWith('-'), `Unknown option: ${argument}`);\n assert(!inputPath, 'Only one input SB3 may be specified.');\n inputPath = path.resolve(argument);\n }\n }\n assert(inputPath, 'The extensions replace-sb3 command requires INPUT.sb3.');\n assert(outputPath, 'The extensions replace-sb3 command requires --output OUTPUT.sb3.');\n return {action: 'replace-sb3', command: 'extensions', fromPath, inputPath, outputPath, yes};\n}\n\nfunction parseExtensionsArguments(arguments_: string[]): ExtensionsCliOptions {\n const [action, ...actionArguments] = arguments_;\n assert(\n action === 'replace-sb3' ||\n action === 'bundle' ||\n action === 'migrate-id' ||\n action === 'status' ||\n action === 'sync' ||\n action === 'unbundle' ||\n action === 'update',\n 'The extensions command requires status, sync, update, migrate-id, bundle, unbundle, or replace-sb3.',\n );\n if (action === 'replace-sb3') return parseExtensionReplaceSb3Arguments(actionArguments);\n if (action === 'status') {\n assert(\n actionArguments.length === 1 && !actionArguments[0].startsWith('-'),\n 'The extensions status command requires exactly one SOURCE_DIR.',\n );\n return {\n action,\n command: 'extensions',\n sourceDirectory: path.resolve(actionArguments[0]),\n };\n }\n if (action === 'migrate-id') {\n return parseExtensionIdMigrationArguments(actionArguments);\n }\n if (action === 'bundle') {\n return parseExtensionBundleArguments(actionArguments);\n }\n if (action === 'unbundle') {\n return parseExtensionUnbundleArguments(actionArguments);\n }\n return parseExtensionMutationArguments(action, actionArguments);\n}\n\nexport function parseCliArguments(arguments_: string[]): CliOptions {\n const normalized = arguments_.filter((argument) => argument !== '--');\n if (normalized.length === 0 || normalized[0] === '--help' || normalized[0] === '-h') {\n return {command: 'help'};\n }\n if (normalized[0] === '--version' || normalized[0] === '-v') {\n return {command: 'version'};\n }\n\n const [command, ...commandArguments] = normalized;\n if (commandArguments.includes('--help') || commandArguments.includes('-h')) {\n return {command: 'help'};\n }\n if (command === 'import') return parseImportArguments(commandArguments);\n if (command === 'check') return parseCheckArguments(commandArguments);\n if (command === 'build') return parseBuildArguments(commandArguments);\n if (command === 'extensions') return parseExtensionsArguments(commandArguments);\n throw new Error(`Unknown command: ${command}`);\n}\n\nfunction formatDifferenceLines(differences: DirectoryDifferences): string {\n const labels: Record<string, string> = {added: '+', modified: '~', removed: '-'};\n const lines = Object.entries(differences).flatMap(([kind, paths]) =>\n paths.map((relativePath: string) => `${labels[kind]} ${relativePath}`),\n );\n const visibleLines = lines.slice(0, 12);\n if (lines.length > visibleLines.length) {\n visibleLines.push(`... and ${lines.length - visibleLines.length} more`);\n }\n return visibleLines.join('\\n');\n}\n\nasync function confirmImportReplacement(context: OutputReplacementContext): Promise<boolean> {\n const {comparison, discardLocalChanges, gitState, outputDirectory} = context;\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Output directory already exists: ${outputDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const gitMessage = gitState.clean\n ? 'Git state: clean'\n : 'Git state: uncommitted changes will be discarded';\n const answer = await readline.question(\n `Existing SB3 source differs from the import candidate:\\n` +\n ` ${outputDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n `${gitMessage}\\n` +\n `${discardLocalChanges ? 'WARNING: --discard-local-changes is active.\\n' : ''}` +\n 'Replace the existing source directory? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmBuildReplacement(outputPath: string): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Existing SB3 output differs: ${outputPath}. Non-interactive replacement requires --yes.`,\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Existing generated SB3 will be replaced:\\n ${outputPath}\\nContinue? [y/N] `,\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nasync function confirmExtensionReplacement({\n comparison,\n sourceDirectory,\n}: ExtensionSyncConfirmContext): Promise<boolean> {\n assert(\n process.stdin.isTTY && process.stdout.isTTY,\n `Managed extension files differ in ${sourceDirectory}. ` +\n 'Non-interactive replacement requires --yes.',\n );\n const readline = createInterface({input: process.stdin, output: process.stdout});\n try {\n const answer = await readline.question(\n `Managed extension changes will be installed:\\n` +\n ` ${sourceDirectory}\\n` +\n `${formatDifferenceLines(comparison.differences)}\\n` +\n 'Replace these files? [y/N] ',\n );\n return /^(?:y|yes)$/iu.test(answer.trim());\n } finally {\n readline.close();\n }\n}\n\nfunction logMigrationResult(result: MigrationLogResult, log: (message: string) => void): void {\n const counts = Object.entries(result.counts)\n .filter(([, count]) => count > 0)\n .map(([kind, count]) => `${kind}=${count}`)\n .join(', ');\n const action = result.applied ? 'Migrated' : 'Dry run';\n log(\n `${action}: ${result.fromId} -> ${result.toId}; ` +\n `${result.totalChanges} classified changes (${counts || 'none'}); ` +\n `artifact=${result.artifactReady ? 'ready' : 'requires-new-ID'}.`,\n );\n for (const reference of result.unclassifiedReferences) {\n log(\n `Unclassified ${reference.kind}: ${reference.file}${reference.path} = ` +\n JSON.stringify(reference.value),\n );\n }\n}\n\nexport async function runCli(\n arguments_: string[],\n {fetch: fetchImplementation = globalThis.fetch, log = console.log}: RunCliOptions = {},\n): Promise<void> {\n const options = parseCliArguments(arguments_);\n if (options.command === 'help') {\n log(usage());\n return;\n }\n if (options.command === 'version') {\n log(packageVersion);\n return;\n }\n if (options.command === 'check') {\n assert(\n 'sourceDirectory' in options && !('action' in options),\n 'Internal CLI check command routing error.',\n );\n if (options.projectAssetsPath) {\n const result = await createDeterministicSb3(options.sourceDirectory, {\n allowedAssetRoots: options.allowedAssetRoots,\n projectAssetsPath: options.projectAssetsPath,\n });\n log(\n `Valid SB3 source with project assets: ${result.source.resolvedSourceDirectory} ` +\n `(${result.entryCount} entries, ${result.assetCount} assets, ` +\n `${result.assetReferenceCount} references, ${result.embeddedExtensionCount} embedded extensions).`,\n );\n return;\n }\n const result = await validateSb3Source(options.sourceDirectory);\n log(\n `Valid SB3 source: ${result.resolvedSourceDirectory} ` +\n `(${result.sourceManifest.archiveEntries.length} entries, ` +\n `${result.assetContents.size} assets, ${result.assetReferenceCount} references, ` +\n `${result.extensions.length} embedded extensions).`,\n );\n return;\n }\n if (\n options.command === 'build' &&\n 'outputPath' in options &&\n 'sourceDirectory' in options &&\n !('action' in options)\n ) {\n const result = await buildSb3({\n allowedAssetRoots: options.allowedAssetRoots,\n cleanUpBlocks: options.cleanUpBlocks,\n confirmReplace: confirmBuildReplacement,\n outputPath: options.outputPath,\n projectAssetsPath: options.projectAssetsPath,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n const action = result.changed ? 'Built' : 'Already up to date';\n const cleanUpMessage = result.blockCleanUp\n ? `, ${result.blockCleanUp.movedScriptCount}/${result.blockCleanUp.scriptCount} scripts laid out`\n : '';\n log(\n `${action}: ${result.outputPath} (${result.entryCount} entries, ` +\n `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions` +\n `${cleanUpMessage}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.command === 'extensions') {\n if (options.action === 'replace-sb3') {\n const result = await replaceSb3Extensions({\n confirmReplace: confirmBuildReplacement,\n fetch: fetchImplementation,\n fromPath: options.fromPath,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.changed ? 'Wrote' : 'Already up to date'}: ${result.outputPath} (${result.extensionIds.join(', ')}).`,\n );\n log(\n `Donor: ${result.donor.source}; version=${result.donor.version ?? 'unknown'}; sha256=${result.donor.sha256}`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'bundle') {\n const result = await bundleExtensions({\n bundleId: options.bundleId,\n bundleName: options.bundleName,\n metadata: options.metadata,\n extensionIds: options.extensionIds,\n recoveryCapsule: options.recoveryCapsule,\n buildMode: options.buildMode,\n sharedDependencies: options.sharedDependencies,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Configured' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'unbundle') {\n if ('inputPath' in options) {\n const result = await unbundleSb3({\n bundleId: options.bundleId,\n inputPath: options.inputPath,\n outputPath: options.outputPath,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Wrote' : 'Dry run'} unbundled SB3: ${result.bundleId} ` +\n `(${result.members.join(', ')}) -> ${result.outputPath}.`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n const result = await unbundleExtensions({\n bundleId: options.bundleId,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n });\n log(\n `${result.applied ? 'Removed' : 'Dry run'} extension bundle: ${result.bundleId} ` +\n `(${result.members.join(', ')}).`,\n );\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'migrate-id') {\n const result = await migrateExtensionId({\n fromId: options.fromId,\n sourceDirectory: options.sourceDirectory,\n toId: options.toId,\n yes: options.yes,\n });\n logMigrationResult(result, log);\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n if (options.action === 'status') {\n const statuses = await extensionStatus(options.sourceDirectory, {\n fetch: fetchImplementation,\n });\n if (statuses.length === 0) {\n log(`No managed embedded extensions: ${options.sourceDirectory}`);\n return;\n }\n for (const status of statuses) {\n if ('package' in status) {\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.package}@${status.version} (installed ${status.installedVersion})`,\n );\n continue;\n }\n log(\n `${status.id}: ${status.state}; local=${status.local}; ` +\n `${status.ref} -> ${status.remoteCommit} ` +\n `(installed ${status.resolvedCommit})`,\n );\n }\n return;\n }\n\n const operationOptions = {\n confirmReplace: confirmExtensionReplacement,\n fetch: fetchImplementation,\n sourceDirectory: options.sourceDirectory,\n yes: options.yes,\n };\n const result =\n options.action === 'sync'\n ? await syncExtensions(operationOptions)\n : await updateExtensions({\n ...operationOptions,\n allowBreakingApi: options.allowBreakingApi,\n apiManifestArtifact: options.apiManifestArtifact,\n extensionId: options.extensionId,\n migrateToId: options.migrateToId,\n sourceArtifact: options.sourceArtifact,\n });\n const action = result.changed ? 'Updated' : 'Already up to date';\n log(\n `${action}: ${result.sourceDirectory} ` +\n `(${result.extensions.map((extension) => extension.id).join(', ')}).`,\n );\n if (result.migration) {\n logMigrationResult(\n {\n applied: result.changed,\n artifactReady: true,\n ...result.migration,\n },\n log,\n );\n }\n for (const compatibility of result.apiCompatibility) {\n for (const change of compatibility.changes) {\n log(\n `API ${compatibility.id}: ${change.breaking ? 'breaking' : 'compatible'} ` +\n `${change.kind} ${change.path}`,\n );\n }\n }\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n return;\n }\n\n assert(\n options.command === 'import' && 'inputPath' in options,\n 'Internal CLI command routing error.',\n );\n const result = await importSb3({\n confirmReplace: confirmImportReplacement,\n discardLocalChanges: options.discardLocalChanges,\n inputPath: options.inputPath,\n outputDirectory: options.outputDirectory,\n yes: options.yes,\n });\n if (result.changed) {\n const differenceMessage = result.differenceCounts\n ? ` Changes: +${result.differenceCounts.added} ` +\n `~${result.differenceCounts.modified} -${result.differenceCounts.removed}.`\n : '';\n log(\n `Imported ${result.archiveEntryCount} SB3 entries into ${result.outputDirectory} ` +\n `(${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).` +\n differenceMessage,\n );\n } else {\n log(`Already up to date; no files changed: ${result.outputDirectory}`);\n }\n if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2JA,SAAgB,QAAQ;CACtB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCT;AAEA,SAAS,UAAU,YAAsB,OAAe,QAAwB;CAC9E,MAAM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AAO,gBAAgB,IAC1E,OAAO,WAAW,WAAW,OAAO,uBAAuB,0BAC/D,iBACJ;CACF,OACE,IAAI,yCAAyC,OAAO,iBAAiB;CAEvE,IAAI,OAAO,wBAAwB,IAAI,OAAO,sBAAsB;AACtE"}
@@ -1,2 +1,2 @@
1
1
  export declare const packageName = "@kubohiroya/sb3-toolchain";
2
- export declare const packageVersion = "0.19.1";
2
+ export declare const packageVersion = "0.20.0";
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  //#region src/constants.ts
2
2
  var packageName = "@kubohiroya/sb3-toolchain";
3
- var packageVersion = "0.19.1";
3
+ var packageVersion = "0.20.0";
4
4
  //#endregion
5
5
  export { packageName, packageVersion };
6
6
 
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.19.1';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.20.0';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
@@ -0,0 +1,22 @@
1
+ import { WriteSb3ArchiveOptions, WriteSb3ArchiveResult } from './build';
2
+ import { FetchImplementation } from './extension-sync';
3
+ export declare const defaultKamishibaiManifestUrl = "https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json";
4
+ export declare const kamishibaiReplacementIds: readonly string[];
5
+ export interface ReplaceSb3ExtensionsOptions {
6
+ confirmReplace?: WriteSb3ArchiveOptions['confirmReplace'];
7
+ fetch?: FetchImplementation;
8
+ fromPath?: string;
9
+ inputPath: string;
10
+ outputPath: string;
11
+ yes?: boolean;
12
+ }
13
+ export interface ReplaceSb3ExtensionsResult extends WriteSb3ArchiveResult {
14
+ extensionIds: string[];
15
+ donor: {
16
+ source: string;
17
+ sha256: string;
18
+ version: string | null;
19
+ };
20
+ }
21
+ /** Replaces the Kamishibai runtime bundle and Block Script without executing donor code. */
22
+ export declare function replaceSb3Extensions({ confirmReplace, fetch: fetchImplementation, fromPath, inputPath, outputPath, yes, }: ReplaceSb3ExtensionsOptions): Promise<ReplaceSb3ExtensionsResult>;
@@ -0,0 +1,176 @@
1
+ import { assert } from "./assert.js";
2
+ import { validateArchiveEntryName } from "./archive.js";
3
+ import { extensionHeaderId } from "./extension-dependencies.js";
4
+ import { fixedZipTimestamp } from "./source.js";
5
+ import { writeSb3Archive } from "./build.js";
6
+ import { decodeExtensionDataUrl } from "./import.js";
7
+ import path from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { lstat, readFile, realpath } from "node:fs/promises";
10
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
11
+ import { lt, valid } from "semver";
12
+ //#region src/extension-sb3-replacement.ts
13
+ var defaultKamishibaiManifestUrl = "https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json";
14
+ var kamishibaiReplacementIds = Object.freeze(["kubohiroyakamishibai4", "kubohiroyakamishibaiauthoring4"]);
15
+ var archiveSizeLimit = 67108864;
16
+ var expandedSizeLimit = 268435456;
17
+ function isObject(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+ function sha256(contents) {
21
+ return createHash("sha256").update(contents).digest("hex");
22
+ }
23
+ async function readArchive(filePath) {
24
+ assert(path.extname(filePath).toLowerCase() === ".sb3", `Expected an .sb3 file: ${filePath}`);
25
+ const stats = await lstat(filePath);
26
+ assert(stats.isFile() && !stats.isSymbolicLink(), `Expected a regular SB3 file: ${filePath}`);
27
+ assert(stats.size <= archiveSizeLimit, `SB3 exceeds the 64 MiB limit: ${filePath}`);
28
+ return readFile(filePath);
29
+ }
30
+ function parseArchive(contents) {
31
+ const names = /* @__PURE__ */ new Set();
32
+ let expandedSize = 0;
33
+ const entries = unzipSync(contents, { filter: (entry) => {
34
+ validateArchiveEntryName(entry.name);
35
+ assert(!names.has(entry.name), `Duplicate SB3 archive entry: ${entry.name}`);
36
+ assert(!/^(?:0|[1-9][0-9]*)$/u.test(entry.name), "Integer ZIP entry names are unsupported.");
37
+ names.add(entry.name);
38
+ expandedSize += entry.originalSize;
39
+ assert(names.size <= 4096 && expandedSize <= expandedSizeLimit, "SB3 expansion limit exceeded.");
40
+ return true;
41
+ } });
42
+ assert(Object.hasOwn(entries, "project.json"), "SB3 archive does not contain project.json.");
43
+ const project = JSON.parse(strFromU8(entries["project.json"]));
44
+ assert(isObject(project) && isObject(project.extensionURLs), "SB3 requires an extensionURLs object.");
45
+ return {
46
+ entries,
47
+ project,
48
+ urls: project.extensionURLs
49
+ };
50
+ }
51
+ function embeddedSource(urls, id) {
52
+ const dataUrl = urls[id];
53
+ assert(typeof dataUrl === "string" && dataUrl.startsWith("data:"), `Missing embedded extension: ${id}`);
54
+ const decoded = decodeExtensionDataUrl(dataUrl);
55
+ assert(decoded.mediaType === "text/javascript" || decoded.mediaType === "application/javascript", `Embedded extension must contain JavaScript: ${id}`);
56
+ const source = Buffer.from(decoded.source);
57
+ const literalId = source.toString("utf8").match(/getInfo\s*\(\)\s*\{\s*return\s*\{\s*"id"\s*:\s*"([a-z0-9]+)"/u)?.[1];
58
+ const actualId = extensionHeaderId(source) ?? literalId;
59
+ assert(actualId === id, `Embedded extension ID mismatch: expected ${id}, got ${actualId ?? "(missing)"}.`);
60
+ return source;
61
+ }
62
+ function runtimeVersion(source) {
63
+ const value = source.toString("utf8").match(/^\/\/ Version: (.+)\r?$/mu)?.[1]?.trim();
64
+ return value && valid(value) ? value : null;
65
+ }
66
+ async function download(url, limit, fetchImplementation) {
67
+ const response = await fetchImplementation(url, {
68
+ redirect: "error",
69
+ signal: AbortSignal.timeout(3e4),
70
+ cache: "no-store"
71
+ });
72
+ assert(response.ok, `Download failed (${response.status}): ${url}`);
73
+ assert(response.body, `Empty download: ${url}`);
74
+ const reader = response.body.getReader();
75
+ const chunks = [];
76
+ let size = 0;
77
+ try {
78
+ for (;;) {
79
+ const { done, value } = await reader.read();
80
+ if (done) break;
81
+ size += value.byteLength;
82
+ assert(size <= limit, `Download exceeds the size limit: ${url}`);
83
+ chunks.push(value);
84
+ }
85
+ } catch (error) {
86
+ await reader.cancel().catch(() => void 0);
87
+ throw error;
88
+ } finally {
89
+ reader.releaseLock();
90
+ }
91
+ return Buffer.concat(chunks, size);
92
+ }
93
+ async function publishedDonor(fetchImplementation) {
94
+ const manifest = JSON.parse((await download(defaultKamishibaiManifestUrl, 1048576, fetchImplementation)).toString("utf8"));
95
+ assert(isObject(manifest), "Invalid Kamishibai public surfaces manifest.");
96
+ assert(manifest.formatVersion === 1 && manifest.status === "published" && manifest.published === true, "Kamishibai donor must be a published format 1 release.");
97
+ assert(typeof manifest.version === "string" && valid(manifest.version), "Invalid published version.");
98
+ assert(isObject(manifest.runtime) && manifest.runtime.version === manifest.version, "Published runtime version mismatch.");
99
+ assert(isObject(manifest.surfaces) && typeof manifest.surfaces.sb3BlocksUrl === "string", "Missing published block SB3 URL.");
100
+ assert(isObject(manifest.artifacts) && isObject(manifest.artifacts.sb3Blocks), "Missing block SB3 artifact.");
101
+ const artifact = manifest.artifacts.sb3Blocks;
102
+ assert(typeof artifact.size === "number" && Number.isSafeInteger(artifact.size) && artifact.size > 0 && artifact.size <= archiveSizeLimit, "Invalid block SB3 size.");
103
+ assert(typeof artifact.sha256 === "string" && /^[a-f0-9]{64}$/u.test(artifact.sha256), "Invalid block SB3 SHA-256.");
104
+ const url = new URL(manifest.surfaces.sb3BlocksUrl);
105
+ const manifestUrl = new URL(defaultKamishibaiManifestUrl);
106
+ assert(url.origin === manifestUrl.origin && !url.username && !url.password && url.pathname.startsWith("/turbowarp-kamishibai-samples/"), "Block SB3 URL must remain on the official samples site.");
107
+ const archive = await download(url.href, archiveSizeLimit, fetchImplementation);
108
+ assert(archive.byteLength === artifact.size, "Downloaded block SB3 size mismatch.");
109
+ assert(sha256(archive) === artifact.sha256, "Downloaded block SB3 SHA-256 mismatch.");
110
+ return {
111
+ archive,
112
+ source: url.href,
113
+ version: manifest.version
114
+ };
115
+ }
116
+ async function assertDistinctOutput(outputPath, protectedPaths) {
117
+ for (const protectedPath of protectedPaths) {
118
+ assert(path.resolve(outputPath) !== path.resolve(protectedPath), "Output must differ from input and donor SB3 paths.");
119
+ try {
120
+ assert(await realpath(outputPath) !== await realpath(protectedPath), "Output must differ from input and donor SB3 paths.");
121
+ } catch (error) {
122
+ if (!isObject(error) || error.code !== "ENOENT") throw error;
123
+ }
124
+ }
125
+ }
126
+ /** Replaces the Kamishibai runtime bundle and Block Script without executing donor code. */
127
+ async function replaceSb3Extensions({ confirmReplace, fetch: fetchImplementation = globalThis.fetch, fromPath, inputPath, outputPath, yes = false }) {
128
+ const protectedPaths = fromPath ? [inputPath, fromPath] : [inputPath];
129
+ await assertDistinctOutput(outputPath, protectedPaths);
130
+ const input = parseArchive(await readArchive(inputPath));
131
+ const extensionIds = kamishibaiReplacementIds.filter((id) => Object.hasOwn(input.urls, id));
132
+ assert(extensionIds.length > 0, "Input contains no supported Kamishibai embedded extensions.");
133
+ const inputSources = new Map(extensionIds.map((id) => [id, embeddedSource(input.urls, id)]));
134
+ const donor = fromPath ? {
135
+ archive: await readArchive(fromPath),
136
+ source: path.resolve(fromPath),
137
+ version: null
138
+ } : await publishedDonor(fetchImplementation);
139
+ const replacement = parseArchive(donor.archive);
140
+ for (const id of extensionIds) embeddedSource(replacement.urls, id);
141
+ const runtimeId = kamishibaiReplacementIds[0];
142
+ const donorRuntime = Object.hasOwn(replacement.urls, runtimeId) ? embeddedSource(replacement.urls, runtimeId) : null;
143
+ const donorVersion = donor.version ?? (donorRuntime ? runtimeVersion(donorRuntime) : null);
144
+ if (!fromPath && donorVersion) {
145
+ const inputRuntime = inputSources.get(runtimeId);
146
+ const inputVersion = inputRuntime ? runtimeVersion(inputRuntime) : null;
147
+ assert(!inputVersion || !lt(donorVersion, inputVersion), `Published donor ${donorVersion} is older than input ${inputVersion}. Wait for publication or select an intentional donor with --from.`);
148
+ const declaredVersion = donorRuntime ? runtimeVersion(donorRuntime) : null;
149
+ assert(!declaredVersion || declaredVersion === donorVersion, "Donor runtime header does not match the published version.");
150
+ }
151
+ for (const id of extensionIds) input.urls[id] = replacement.urls[id];
152
+ input.entries["project.json"] = strToU8(`${JSON.stringify(input.project)}\n`);
153
+ const archive = zipSync(input.entries, {
154
+ level: 6,
155
+ mtime: fixedZipTimestamp
156
+ });
157
+ await assertDistinctOutput(outputPath, protectedPaths);
158
+ return {
159
+ ...await writeSb3Archive({
160
+ archive,
161
+ confirmReplace,
162
+ outputPath,
163
+ yes
164
+ }),
165
+ extensionIds,
166
+ donor: {
167
+ source: donor.source,
168
+ sha256: sha256(donor.archive),
169
+ version: donorVersion
170
+ }
171
+ };
172
+ }
173
+ //#endregion
174
+ export { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions };
175
+
176
+ //# sourceMappingURL=extension-sb3-replacement.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension-sb3-replacement.js","names":[],"sources":["../src/extension-sb3-replacement.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readFile, realpath} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strFromU8, strToU8, unzipSync, zipSync} from 'fflate';\nimport {lt, valid} from 'semver';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert} from './assert';\nimport {writeSb3Archive} from './build';\nimport type {WriteSb3ArchiveOptions, WriteSb3ArchiveResult} from './build';\nimport {extensionHeaderId} from './extension-dependencies';\nimport type {FetchImplementation} from './extension-sync';\nimport {decodeExtensionDataUrl} from './import';\nimport {fixedZipTimestamp} from './source';\nimport type {UnknownRecord} from './types';\n\nexport const defaultKamishibaiManifestUrl =\n 'https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json';\n\nexport const kamishibaiReplacementIds: readonly string[] = Object.freeze([\n 'kubohiroyakamishibai4',\n 'kubohiroyakamishibaiauthoring4',\n]);\n\nconst archiveSizeLimit = 64 * 1024 * 1024;\nconst expandedSizeLimit = 256 * 1024 * 1024;\n\nexport interface ReplaceSb3ExtensionsOptions {\n confirmReplace?: WriteSb3ArchiveOptions['confirmReplace'];\n fetch?: FetchImplementation;\n fromPath?: string;\n inputPath: string;\n outputPath: string;\n yes?: boolean;\n}\n\nexport interface ReplaceSb3ExtensionsResult extends WriteSb3ArchiveResult {\n extensionIds: string[];\n donor: {source: string; sha256: string; version: string | null};\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction sha256(contents: Uint8Array): string {\n return createHash('sha256').update(contents).digest('hex');\n}\n\nasync function readArchive(filePath: string): Promise<Buffer> {\n assert(path.extname(filePath).toLowerCase() === '.sb3', `Expected an .sb3 file: ${filePath}`);\n const stats = await lstat(filePath);\n assert(stats.isFile() && !stats.isSymbolicLink(), `Expected a regular SB3 file: ${filePath}`);\n assert(stats.size <= archiveSizeLimit, `SB3 exceeds the 64 MiB limit: ${filePath}`);\n return readFile(filePath);\n}\n\nfunction parseArchive(contents: Uint8Array) {\n const names = new Set<string>();\n let expandedSize = 0;\n const entries = unzipSync(contents, {\n filter: (entry) => {\n validateArchiveEntryName(entry.name);\n assert(!names.has(entry.name), `Duplicate SB3 archive entry: ${entry.name}`);\n assert(!/^(?:0|[1-9][0-9]*)$/u.test(entry.name), 'Integer ZIP entry names are unsupported.');\n names.add(entry.name);\n expandedSize += entry.originalSize;\n assert(\n names.size <= 4096 && expandedSize <= expandedSizeLimit,\n 'SB3 expansion limit exceeded.',\n );\n return true;\n },\n });\n assert(Object.hasOwn(entries, 'project.json'), 'SB3 archive does not contain project.json.');\n const project: unknown = JSON.parse(strFromU8(entries['project.json']));\n assert(\n isObject(project) && isObject(project.extensionURLs),\n 'SB3 requires an extensionURLs object.',\n );\n return {entries, project, urls: project.extensionURLs};\n}\n\nfunction embeddedSource(urls: UnknownRecord, id: string): Buffer {\n const dataUrl = urls[id];\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n `Missing embedded extension: ${id}`,\n );\n const decoded = decodeExtensionDataUrl(dataUrl);\n assert(\n decoded.mediaType === 'text/javascript' || decoded.mediaType === 'application/javascript',\n `Embedded extension must contain JavaScript: ${id}`,\n );\n const source = Buffer.from(decoded.source);\n // Generated Block Script declares its ID in a literal getInfo() result, without a header.\n const literalId = source\n .toString('utf8')\n .match(/getInfo\\s*\\(\\)\\s*\\{\\s*return\\s*\\{\\s*\"id\"\\s*:\\s*\"([a-z0-9]+)\"/u)?.[1];\n const actualId = extensionHeaderId(source) ?? literalId;\n assert(\n actualId === id,\n `Embedded extension ID mismatch: expected ${id}, got ${actualId ?? '(missing)'}.`,\n );\n return source;\n}\n\nfunction runtimeVersion(source: Buffer): string | null {\n const value = source\n .toString('utf8')\n .match(/^\\/\\/ Version: (.+)\\r?$/mu)?.[1]\n ?.trim();\n return value && valid(value) ? value : null;\n}\n\nasync function download(\n url: string,\n limit: number,\n fetchImplementation: FetchImplementation,\n): Promise<Buffer> {\n const response = await fetchImplementation(url, {\n redirect: 'error',\n signal: AbortSignal.timeout(30_000),\n cache: 'no-store',\n });\n assert(response.ok, `Download failed (${response.status}): ${url}`);\n assert(response.body, `Empty download: ${url}`);\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for (;;) {\n const {done, value} = await reader.read();\n if (done) break;\n size += value.byteLength;\n assert(size <= limit, `Download exceeds the size limit: ${url}`);\n chunks.push(value);\n }\n } catch (error) {\n await reader.cancel().catch(() => undefined);\n throw error;\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks, size);\n}\n\nasync function publishedDonor(fetchImplementation: FetchImplementation) {\n const manifest: unknown = JSON.parse(\n (await download(defaultKamishibaiManifestUrl, 1024 * 1024, fetchImplementation)).toString(\n 'utf8',\n ),\n );\n assert(isObject(manifest), 'Invalid Kamishibai public surfaces manifest.');\n assert(\n manifest.formatVersion === 1 && manifest.status === 'published' && manifest.published === true,\n 'Kamishibai donor must be a published format 1 release.',\n );\n assert(\n typeof manifest.version === 'string' && valid(manifest.version),\n 'Invalid published version.',\n );\n assert(\n isObject(manifest.runtime) && manifest.runtime.version === manifest.version,\n 'Published runtime version mismatch.',\n );\n assert(\n isObject(manifest.surfaces) && typeof manifest.surfaces.sb3BlocksUrl === 'string',\n 'Missing published block SB3 URL.',\n );\n assert(\n isObject(manifest.artifacts) && isObject(manifest.artifacts.sb3Blocks),\n 'Missing block SB3 artifact.',\n );\n const artifact = manifest.artifacts.sb3Blocks;\n assert(\n typeof artifact.size === 'number' &&\n Number.isSafeInteger(artifact.size) &&\n artifact.size > 0 &&\n artifact.size <= archiveSizeLimit,\n 'Invalid block SB3 size.',\n );\n assert(\n typeof artifact.sha256 === 'string' && /^[a-f0-9]{64}$/u.test(artifact.sha256),\n 'Invalid block SB3 SHA-256.',\n );\n const url = new URL(manifest.surfaces.sb3BlocksUrl);\n const manifestUrl = new URL(defaultKamishibaiManifestUrl);\n assert(\n url.origin === manifestUrl.origin &&\n !url.username &&\n !url.password &&\n url.pathname.startsWith('/turbowarp-kamishibai-samples/'),\n 'Block SB3 URL must remain on the official samples site.',\n );\n const archive = await download(url.href, archiveSizeLimit, fetchImplementation);\n assert(archive.byteLength === artifact.size, 'Downloaded block SB3 size mismatch.');\n assert(sha256(archive) === artifact.sha256, 'Downloaded block SB3 SHA-256 mismatch.');\n return {archive, source: url.href, version: manifest.version};\n}\n\nasync function assertDistinctOutput(outputPath: string, protectedPaths: string[]): Promise<void> {\n for (const protectedPath of protectedPaths) {\n assert(\n path.resolve(outputPath) !== path.resolve(protectedPath),\n 'Output must differ from input and donor SB3 paths.',\n );\n try {\n assert(\n (await realpath(outputPath)) !== (await realpath(protectedPath)),\n 'Output must differ from input and donor SB3 paths.',\n );\n } catch (error) {\n if (!isObject(error) || error.code !== 'ENOENT') throw error;\n }\n }\n}\n\n/** Replaces the Kamishibai runtime bundle and Block Script without executing donor code. */\nexport async function replaceSb3Extensions({\n confirmReplace,\n fetch: fetchImplementation = globalThis.fetch,\n fromPath,\n inputPath,\n outputPath,\n yes = false,\n}: ReplaceSb3ExtensionsOptions): Promise<ReplaceSb3ExtensionsResult> {\n const protectedPaths = fromPath ? [inputPath, fromPath] : [inputPath];\n await assertDistinctOutput(outputPath, protectedPaths);\n const input = parseArchive(await readArchive(inputPath));\n const extensionIds = kamishibaiReplacementIds.filter((id) => Object.hasOwn(input.urls, id));\n assert(extensionIds.length > 0, 'Input contains no supported Kamishibai embedded extensions.');\n const inputSources = new Map(extensionIds.map((id) => [id, embeddedSource(input.urls, id)]));\n const donor = fromPath\n ? {archive: await readArchive(fromPath), source: path.resolve(fromPath), version: null}\n : await publishedDonor(fetchImplementation);\n const replacement = parseArchive(donor.archive);\n for (const id of extensionIds) embeddedSource(replacement.urls, id);\n const runtimeId = kamishibaiReplacementIds[0];\n const donorRuntime = Object.hasOwn(replacement.urls, runtimeId)\n ? embeddedSource(replacement.urls, runtimeId)\n : null;\n const donorVersion = donor.version ?? (donorRuntime ? runtimeVersion(donorRuntime) : null);\n if (!fromPath && donorVersion) {\n const inputRuntime = inputSources.get(runtimeId);\n const inputVersion = inputRuntime ? runtimeVersion(inputRuntime) : null;\n assert(\n !inputVersion || !lt(donorVersion, inputVersion),\n `Published donor ${donorVersion} is older than input ${inputVersion}. Wait for publication or select an intentional donor with --from.`,\n );\n const declaredVersion = donorRuntime ? runtimeVersion(donorRuntime) : null;\n assert(\n !declaredVersion || declaredVersion === donorVersion,\n 'Donor runtime header does not match the published version.',\n );\n }\n for (const id of extensionIds) input.urls[id] = replacement.urls[id];\n input.entries['project.json'] = strToU8(`${JSON.stringify(input.project)}\\n`);\n const archive = zipSync(input.entries, {level: 6, mtime: fixedZipTimestamp});\n await assertDistinctOutput(outputPath, protectedPaths);\n const written = await writeSb3Archive({archive, confirmReplace, outputPath, yes});\n return {\n ...written,\n extensionIds,\n donor: {source: donor.source, sha256: sha256(donor.archive), version: donorVersion},\n };\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,IAAa,+BACX;AAEF,IAAa,2BAA8C,OAAO,OAAO,CACvE,yBACA,gCACF,CAAC;AAED,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAgB1B,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,OAAO,UAA8B;CAC5C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,OAAO,KAAK;AAC3D;AAEA,eAAe,YAAY,UAAmC;CAC5D,OAAO,KAAK,QAAQ,QAAQ,CAAC,CAAC,YAAY,MAAM,QAAQ,0BAA0B,UAAU;CAC5F,MAAM,QAAQ,MAAM,MAAM,QAAQ;CAClC,OAAO,MAAM,OAAO,KAAK,CAAC,MAAM,eAAe,GAAG,gCAAgC,UAAU;CAC5F,OAAO,MAAM,QAAQ,kBAAkB,iCAAiC,UAAU;CAClF,OAAO,SAAS,QAAQ;AAC1B;AAEA,SAAS,aAAa,UAAsB;CAC1C,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI,eAAe;CACnB,MAAM,UAAU,UAAU,UAAU,EAClC,SAAS,UAAU;EACjB,yBAAyB,MAAM,IAAI;EACnC,OAAO,CAAC,MAAM,IAAI,MAAM,IAAI,GAAG,gCAAgC,MAAM,MAAM;EAC3E,OAAO,CAAC,uBAAuB,KAAK,MAAM,IAAI,GAAG,0CAA0C;EAC3F,MAAM,IAAI,MAAM,IAAI;EACpB,gBAAgB,MAAM;EACtB,OACE,MAAM,QAAQ,QAAQ,gBAAgB,mBACtC,+BACF;EACA,OAAO;CACT,EACF,CAA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Y,MAAM,SAAS,IAC1D,eAAe,YAAY,MAAM,SAAS,IAC1C;CACJ,MAAM,eAAe,MAAM,YAAY,eAAe,eAAe,YAAY,IAAI;CACrF,IAAI,CAAC,YAAY,cAAc;EAC7B,MAAM,eAAe,aAAa,IAAI,SAAS;EAC/C,MAAM,eAAe,eAAe,eAAe,YAAY,IAAI;EACnE,OACE,CAAC,gBAAgB,CAAC,GAAG,cAAc,YAAY,GAC/C,mBAAmB,aAAa,uBAAuB,aAAa,mEACtE;EACA,MAAM,kBAAkB,eAAe,eAAe,YAAY,IAAI;EACtE,OACE,CAAC,mBAAmB,oBAAoB,cACxC,4DACF;CACF;CACA,KAAK,MAAM,MAAM,cAAc,MAAM,KAAK,MAAM,YAAY,KAAK;CACjE,MAAM,QAAQ,kBAAkB,QAAQ,GAAG,KAAK,UAAU,MAAM,OAAO,EAAE,GAAG;CAC5E,MAAM,UAAU,QAAQ,MAAM,SAAS;EAAC,OAAO;EAAG,OAAO;CAAiB,CAAC;CAC3E,MAAM,qBAAqB,YAAY,cAAc;CAErD,OAAO;EACL,GAAG,MAFiB,gBAAgB;GAAC;GAAS;GAAgB;GAAY;EAAG,CAAC;EAG9E;EACA,OAAO;GAAC,QAAQ,MAAM;GAAQ,QAAQ,OAAO,MAAM,OAAO;GAAG,SAAS;EAAY;CACpF;AACF"}
package/dist/index.d.ts CHANGED
@@ -32,3 +32,5 @@ export type { ProjectAssetAdditionsSummary } from './project-asset-additions';
32
32
  export type { Sb3ReleaseSnapshotMetadata } from './release-snapshot';
33
33
  export type { DeterministicSb3, InspectedSb3Source } from './source';
34
34
  export type { TurboWarpCleanUpResult } from './turbowarp-clean-up';
35
+ export { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions, } from './extension-sb3-replacement';
36
+ export type { ReplaceSb3ExtensionsOptions, ReplaceSb3ExtensionsResult, } from './extension-sb3-replacement';
package/dist/index.js CHANGED
@@ -14,6 +14,7 @@ import { decodeExtensionDataUrl, importSb3 } from "./import.js";
14
14
  import { planBundledSb3Unbundle, unbundleSb3 } from "./extension-bundle-archive.js";
15
15
  import { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions } from "./extension-bundle-configuration.js";
16
16
  import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId } from "./extension-id-migration.js";
17
+ import { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions } from "./extension-sb3-replacement.js";
17
18
  import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
18
19
  import { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate } from "./release-snapshot.js";
19
- export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
20
+ export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultKamishibaiManifestUrl, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, kamishibaiReplacementIds, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, replaceSb3Extensions, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
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.19.1</code></p>
72
+ <p><code>@kubohiroya/sb3-toolchain@0.20.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.19.1</code></pre>
93
+ <pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.20.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>
@@ -0,0 +1,41 @@
1
+ # Kamishibai作品SB3の埋め込み機能拡張を一括更新する
2
+
3
+ ```sh
4
+ sb3-toolchain extensions replace-sb3 ari-kirigirisu-20161029.sb3 --output ari-kirigirisu-updated.sb3
5
+ ```
6
+
7
+ `--from`を省略すると、[公式サンプルサイトの公開マニフェスト](https://kubohiroya.github.io/turbowarp-kamishibai-samples/stories/tutorial/public-surfaces.json)から
8
+ ブロック台本SB3のURLを解決し、自動取得します。公開済み状態・バージョンの整合性・ダウンロードしたSB3のサイズとSHA-256を検証してから、入力作品にある次の実装を差し替えます。
9
+
10
+ - `kubohiroyakamishibai4`: Kamishibai DSL 4.0 Runtimeを含むバンドル全体
11
+ - `kubohiroyakamishibaiauthoring4`: Kamishibai Block Script
12
+
13
+ 入力に両方あれば、同じ提供元SB3から両方を更新します。片方だけなら、その機能拡張だけを更新します。提供元に必要なIDがない場合は停止します。取得したコードは実行しません。
14
+
15
+ 取得するのはサンプルサイトで現在公開されているブロック台本です。開発中の候補版は使いません。アプリ本体だけが先に公開され、サンプルサイトの更新がまだの場合は、その本体版を取得できません。公開版が入力のRuntimeヘッダーに記載された版より古い場合は、自動ダウングレードを防ぐため停止します。入力にバージョンヘッダーがない場合は、新旧の比較を省略します。
16
+
17
+ 提供元を手元のファイルに固定する場合は、`--from`を指定します。この場合、ネットワーク通信は不要です。明示的に古い提供元を選ぶこともできます。
18
+
19
+ ```sh
20
+ sb3-toolchain extensions replace-sb3 input.sb3 --from 新版のブロック台本.sb3 --output updated.sb3
21
+ ```
22
+
23
+ 元ファイルを保護するため、入力と提供元は出力先に指定できません。既存の出力内容が異なる場合は、対話確認または`--yes`が必要です。検証失敗時には出力を変更しません。元の作品を開けば更新前の状態に戻れます。
24
+
25
+ 変更するのは`project.json`内の対象IDの`extensionURLs`の値です。その他の機能拡張、ブロック、座標、変数、リスト、`extensionStorage`、素材、および追加のZIPエントリーは保持します。ZIPの圧縮とタイムスタンプ、`project.json`の文字列表現は再生成します。出力には提供元・公開版・SHA-256・更新対象IDを表示します。ローカル提供元にバージョンヘッダーがない場合は`unknown`と表示します。
26
+
27
+ このコマンドはDSLや保存データの移行を行いません。例えば`/assets/SafetyPose`の参照が作品の保存データに残っている場合、そのデータは保持されます。コードの置換だけでは、旧版とのDSL互換性や再生の成功を保証できません。更新後の作品をエディターで再生して確認してください。
28
+
29
+ 入力・提供元の圧縮サイズは64 MiB、展開サイズは256 MiB、ZIPエントリー数は4096までです。ネットワーク取得には各30秒のタイムアウトを設け、マニフェストは1 MiBまで受け付けます。
30
+
31
+ JavaScript APIでも同じ処理を利用できます。
32
+
33
+ ```js
34
+ import {replaceSb3Extensions} from '@kubohiroya/sb3-toolchain';
35
+
36
+ const result = await replaceSb3Extensions({
37
+ inputPath: 'input.sb3',
38
+ outputPath: 'updated.sb3',
39
+ });
40
+ console.log(result.donor, result.extensionIds);
41
+ ```
@@ -1,5 +1,7 @@
1
1
  # SB3ソース管理ワークフロー
2
2
 
3
+ Kamishibai作品SB3に埋め込まれた実装を一括更新する場合は、[SB3の機能拡張更新](sb3-extension-replacement.md)を参照してください。
4
+
3
5
  [English](../workflows.md)
4
6
 
5
7
  この文書では、Scratch 3またはTurboWarpのSB3をGit内の展開ソースとして管理し、検証済みSB3を再ビルドする
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/sb3-toolchain",
3
- "version": "0.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Git-friendly source management and deterministic builds for Scratch 3 and TurboWarp SB3 projects",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -85,9 +85,9 @@
85
85
  "source-control",
86
86
  "reproducible-builds"
87
87
  ],
88
- "gitHead": "642f5c81d99c1892fdfc90b5a9bd52fe90e65184",
88
+ "gitHead": "80bdc3d0bf282234223257aca23c6a79fe31e9c6",
89
89
  "x-turbowarp-source": {
90
- "revision": "642f5c81d99c1892fdfc90b5a9bd52fe90e65184",
90
+ "revision": "80bdc3d0bf282234223257aca23c6a79fe31e9c6",
91
91
  "revisionRole": "base-commit",
92
92
  "sourceState": "local-release-overlay"
93
93
  }