@kubohiroya/sb3-toolchain 0.4.0 → 0.5.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/README.ja.md CHANGED
@@ -9,11 +9,13 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
9
9
 
10
10
  - SB3を、整形済みの`project.source.json`、アセット、埋め込み機能拡張へ安全に展開
11
11
  - アセット参照、MD5ハッシュ、ZIPエントリ、埋め込み機能拡張の対応関係を検証
12
- - GitHubでホストされる埋め込み機能拡張のコミットとSHA-256ハッシュを記録し、オフラインで検証
12
+ - GitHubの固定コミットまたはインストール済みnpmパッケージの完全固定バージョンから埋め込み機能拡張を管理し、
13
+ SHA-256ハッシュをオフラインで検証
13
14
  - 埋め込みJavaScriptを置き換える前に、バージョン付き機能拡張APIマニフェストを任意で比較
14
15
  - 元のJavaScriptを削除せず、複数の機能拡張を1つの権限単位へ静的にbundleし、展開ソースまたは
15
16
  bundle済みSB3から復元
16
17
  - ZIPエントリ順、タイムスタンプ、圧縮設定を固定した決定的ビルド
18
+ - 全ターゲットのスクリプトをTurboWarp風の決定的な「きれいにする」配置へ任意で整理
17
19
  - import時に未コミットのGit変更を保護
18
20
  - トランザクションによる置換とロールバックで既存出力を保護
19
21
  - CLIとJavaScript APIの両方を提供
@@ -28,7 +30,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
28
30
  再現可能なインストールのため、検証済みのnpmバージョンを固定します。
29
31
 
30
32
  ```bash
31
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.4.0
33
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.5.0
32
34
  ```
33
35
 
34
36
  ## クイックスタート
@@ -75,9 +77,11 @@ await validateSb3Source('app');
75
77
  await buildSb3({
76
78
  sourceDirectory: 'app',
77
79
  outputPath: 'dist/project.sb3',
80
+ // 生成SB3だけを整理済みブロック座標にする場合に明示的に有効化します。
81
+ cleanUpBlocks: true,
78
82
  });
79
83
 
80
- const {archive} = await createDeterministicSb3('app');
84
+ const {archive} = await createDeterministicSb3('app', {cleanUpBlocks: true});
81
85
 
82
86
  const integrity = extensionIntegrity(await readFile('app/extensions/example.js'));
83
87
 
package/README.md CHANGED
@@ -9,11 +9,13 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
9
9
 
10
10
  - Safely expand an SB3 into formatted `project.source.json`, assets, and embedded extensions
11
11
  - Validate asset references, MD5 hashes, ZIP entries, and embedded extension mappings
12
- - Record commits and SHA-256 hashes for GitHub-hosted embedded extensions and verify them offline
12
+ - Manage embedded extensions from pinned GitHub commits or exact installed npm package versions and
13
+ verify their SHA-256 hashes offline
13
14
  - Optionally compare versioned extension API manifests before replacing embedded JavaScript
14
15
  - Statically bundle multiple extensions into one permission unit without deleting their original
15
16
  JavaScript, then restore them from either the expanded source or the bundled SB3
16
17
  - Produce deterministic builds with fixed ZIP entry order, timestamps, and compression settings
18
+ - Optionally lay out every target's scripts in a deterministic TurboWarp-style cleaned arrangement
17
19
  - Protect uncommitted Git changes when importing
18
20
  - Protect existing output through transactional replacement and rollback
19
21
  - Provide both a CLI and a JavaScript API
@@ -28,7 +30,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
28
30
  Pin the verified npm version for reproducible installation.
29
31
 
30
32
  ```bash
31
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.4.0
33
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.5.0
32
34
  ```
33
35
 
34
36
  ## Quick start
@@ -75,9 +77,11 @@ await validateSb3Source('app');
75
77
  await buildSb3({
76
78
  sourceDirectory: 'app',
77
79
  outputPath: 'dist/project.sb3',
80
+ // Opt in to cleaned block coordinates in the generated SB3 only:
81
+ cleanUpBlocks: true,
78
82
  });
79
83
 
80
- const {archive} = await createDeterministicSb3('app');
84
+ const {archive} = await createDeterministicSb3('app', {cleanUpBlocks: true});
81
85
 
82
86
  const integrity = extensionIntegrity(await readFile('app/extensions/example.js'));
83
87
 
@@ -180,6 +180,13 @@ sequenceDiagram
180
180
 
181
181
  A->>W: startHats("alpha_whenReady")
182
182
  W->>VM: startHats("projectbundle_alpha__whenReady")
183
+
184
+ A->>W: getOpcodeFunction("beta_echo")
185
+ W->>VM: getOpcodeFunction("projectbundle_beta__echo")
186
+ VM-->>A: Bundled opcode handler
187
+ A->>C: Call handler(args, util)
188
+ C->>B: Call original echo(args, util)
189
+ B-->>A: Result or Promise
183
190
  ```
184
191
 
185
192
  ### Data transformations
@@ -192,6 +199,7 @@ sequenceDiagram
192
199
  | Stored project opcode | `alpha_doSomething` | `projectbundle_alpha__doSomething` |
193
200
  | Menu and custom-field names | Member-local names | `memberId__` namespace |
194
201
  | `startHats()` opcode | `alpha_whenReady` | `projectbundle_alpha__whenReady` |
202
+ | `getOpcodeFunction()` | `beta_echo` | `projectbundle_beta__echo` |
195
203
  | Extension storage | `storage.alpha`, `storage.beta` | `storage.projectbundle.components.alpha/beta` |
196
204
  | Block IDs and graph links | Original IDs and `next`/`parent`/`inputs` | Unchanged |
197
205
 
@@ -222,7 +230,16 @@ behavior. The current static-bundle contract requires all of the following:
222
230
 
223
231
  The bundle namespaces ordinary commands, reporters, booleans, events, buttons, labels, static and
224
232
  dynamic menus, custom fields, and global and target extension storage. Calls from child extensions
225
- to `runtime.startHats` are also translated to bundled opcodes.
233
+ to `runtime.startHats` are also translated to bundled opcodes. When a member calls
234
+ `runtime.getOpcodeFunction()`, an opcode beginning with any member ID in the same bundle is
235
+ translated at runtime. This supports both self references and calls to another member, such as an
236
+ Asset Manager member resolving an Animated Text member's handler.
237
+
238
+ Only the opcode passed to `getOpcodeFunction()` is adapted. The function returned by the VM is
239
+ passed through unchanged, so its binding, handler arguments, synchronous result, or Promise result
240
+ are preserved. Core, external-extension, and unknown opcodes whose prefix is not a bundle member ID
241
+ are passed to the VM unchanged. Other APIs that carry opcode strings are outside this compatibility
242
+ contract unless documented separately.
226
243
 
227
244
  The bundle preserves the `members` order from the manifest and the block-definition order within
228
245
  each member's `getInfo().blocks`. In the TurboWarp Editor palette, each group begins with a decorated
@@ -176,6 +176,13 @@ sequenceDiagram
176
176
 
177
177
  A->>W: startHats("alpha_whenReady")
178
178
  W->>VM: startHats("projectbundle_alpha__whenReady")
179
+
180
+ A->>W: getOpcodeFunction("beta_echo")
181
+ W->>VM: getOpcodeFunction("projectbundle_beta__echo")
182
+ VM-->>A: bundle済みopcodeのhandler
183
+ A->>C: handler(args, util)を呼び出す
184
+ C->>B: 元のecho(args, util)を呼び出す
185
+ B-->>A: 結果またはPromise
179
186
  ```
180
187
 
181
188
  ### データ変換
@@ -188,6 +195,7 @@ sequenceDiagram
188
195
  | 保存されるプロジェクトopcode | `alpha_doSomething` | `projectbundle_alpha__doSomething` |
189
196
  | メニューとカスタムフィールド名 | メンバー内の名前 | `memberId__`名前空間 |
190
197
  | `startHats()`のopcode | `alpha_whenReady` | `projectbundle_alpha__whenReady` |
198
+ | `getOpcodeFunction()` | `beta_echo` | `projectbundle_beta__echo` |
191
199
  | 機能拡張ストレージ | `storage.alpha`、`storage.beta` | `storage.projectbundle.components.alpha/beta` |
192
200
  | ブロックIDとグラフリンク | 元のIDと`next`/`parent`/`inputs` | 変更なし |
193
201
 
@@ -217,7 +225,15 @@ bundle設定は`embedded-extensions.json`だけに追加されます。信頼で
217
225
 
218
226
  bundleは、通常のcommand、reporter、boolean、event、button、label、静的および動的メニュー、
219
227
  カスタムフィールド、グローバルおよびターゲット機能拡張ストレージを名前空間化します。子機能拡張からの
220
- `runtime.startHats`呼び出しもbundle済みopcodeへ変換します。
228
+ `runtime.startHats`呼び出しもbundle済みopcodeへ変換します。メンバーが`runtime.getOpcodeFunction()`を
229
+ 呼び出した場合は、同じbundleに含まれるいずれかのメンバーIDで始まるopcodeをランタイムで変換します。
230
+ これにより、自身のopcode参照だけでなく、Asset ManagerメンバーがAnimated Textメンバーのhandlerを
231
+ 解決するようなmember間呼び出しにも対応します。
232
+
233
+ 変換するのは`getOpcodeFunction()`へ渡すopcodeだけです。VMが返す関数は変更せずそのまま返すため、関数の
234
+ 束縛、handlerの引数、同期的な戻り値、Promiseの戻り値は保持されます。先頭部分がbundle member IDではない
235
+ core、外部機能拡張、未知のopcodeは変更せずVMへ渡します。opcode文字列を受け取るほかのAPIは、個別に明記
236
+ されていない限り、この互換性契約の対象外です。
221
237
 
222
238
  bundleは、マニフェストの`members`順と、各メンバーの`getInfo().blocks`内のブロック定義順を保持します。
223
239
  TurboWarp Editorのパレットでは、各グループが次の形式の装飾済みLABEL見出しから始まります。
@@ -42,8 +42,8 @@ embedded-extension:extensions/<extensionId>.js
42
42
 
43
43
  ## `embedded-extensions.json`
44
44
 
45
- このファイルは、埋め込み機能拡張のdata URL情報と展開先パスを記録します。GitHubから管理する機能拡張には、
46
- 任意の`source`メタデータを追加できます。
45
+ このファイルは、埋め込み機能拡張のdata URL情報と展開先パスを記録します。GitHubまたはインストール済み
46
+ npmパッケージから管理する機能拡張には、任意の`source`メタデータを追加できます。
47
47
 
48
48
  ```json
49
49
  {
@@ -74,10 +74,25 @@ embedded-extension:extensions/<extensionId>.js
74
74
  }
75
75
  ```
76
76
 
77
+ 完全固定したnpm依存では、GitHub固有のフィールドをパッケージ情報へ置き換えます。
78
+
79
+ ```json
80
+ {
81
+ "provider": "npm",
82
+ "package": "@owner/example-extension",
83
+ "version": "1.2.3",
84
+ "artifact": "dist/example.js",
85
+ "integrity": "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
86
+ }
87
+ ```
88
+
89
+ - `provider`: `github`または`npm`
77
90
  - `repository`: `<owner>/<repository>`形式のGitHubリポジトリ
78
91
  - `ref`: 更新候補として追跡するブランチ、タグ、またはコミット
79
92
  - `resolvedCommit`: 現在のファイルの取得に使用した、小文字40文字のコミットSHA
80
- - `artifact`: リポジトリルートを基準にしたJavaScript成果物のパス
93
+ - `package`: スコープを含む完全なnpmパッケージ名
94
+ - `version`: インストール済み`package.json`に記録された完全固定のsemantic version。範囲指定は不可
95
+ - `artifact`: リポジトリまたはnpmパッケージのルートを基準にしたJavaScript成果物のパス
81
96
  - `integrity`: 現在のファイルのSRI形式SHA-256
82
97
  - `apiManifest`: 任意で使用するAPI互換性メタデータ
83
98
  - `artifact`: 同じGitHubリポジトリを基準にしたAPIマニフェストのパス
@@ -89,19 +104,19 @@ embedded-extension:extensions/<extensionId>.js
89
104
 
90
105
  - 実ファイルのSHA-256が`integrity`と一致する
91
106
  - ファイルの`// ID: <extensionId>`ヘッダーが`id`と一致する
92
- - リポジトリ、ref、コミット、成果物パスが安全な形式である
107
+ - GitHubリポジトリ、ref、コミット、npmパッケージ、完全固定バージョン、成果物パスが安全な形式である
93
108
  - `apiManifest`が存在する場合、そのJSONスキーマ、ID、形式バージョン、パス、SHA-256が有効である
94
109
 
95
110
  既存の展開ソースディレクトリへSB3を再importすると、同じIDとパスの`source`メタデータが保持されます。
96
111
  importしたファイルが記録済みのハッシュまたはIDと一致しない場合、既存の出力を変更せずにimportを拒否します。
97
112
  新規importでは来歴を推測できないため、`source`は自動作成されません。
98
113
 
99
- `extensions sync`は、変更不能な`resolvedCommit`を使用してJavaScriptと任意のAPIマニフェストを
100
- ダウンロードし、そのIDとハッシュが既存メタデータに一致する場合に限りローカルファイルを復元します。
101
- `extensions update`はGitHub APIを通じて`ref`を解決し、同じコミットから両方の成果物をダウンロードして、
102
- 候補APIマニフェストをインストール済み契約と比較します。互換性検査と内容検証が成功した後に限り、
103
- `resolvedCommit`と両方のintegrity値を更新します。選択したすべてのエントリのダウンロードと検証が完了するまで、
104
- 展開ソースは変更されません。
114
+ GitHub sourceの`extensions sync`は変更不能な`resolvedCommit`からJavaScriptと任意のAPIマニフェストを
115
+ ダウンロードします。npm sourceでは、最寄りの親`node_modules`にインストールされた完全固定パッケージから、
116
+ ネットワークを使わずに読み込みます。どちらもIDとハッシュが既存メタデータに一致する場合だけ復元します。
117
+ パッケージマネージャーで新しい完全固定npmバージョンを導入した後に`extensions update`を実行すると、成果物を
118
+ コピーして`version`とintegrityを更新します。GitHub更新では`ref`を解決して`resolvedCommit`を更新します。
119
+ どちらも候補APIマニフェストを事前に比較し、選択した全項目の検証が終わるまで展開ソースを変更しません。
105
120
 
106
121
  機能拡張IDの移行では、マニフェストの`id`と`path`、`project.source.json`内の既知の参照、
107
122
  `extensions/<id>.js`を1回のトランザクションで変更します。`extensions update`の一部として管理対象機能拡張を
@@ -84,25 +84,37 @@ sb3-toolchain build app --output dist/project.sb3
84
84
  バイト単位で同一のSB3が生成されます。既存出力が同一なら変更しません。異なる場合は、置換の確認または
85
85
  `--yes`が必要です。
86
86
 
87
+ 生成SB3へ書き込む前に、全ターゲットのトップレベルスクリプトを整理するには、明示的にオプションを指定します。
88
+
89
+ ```bash
90
+ sb3-toolchain build app --output dist/project.sb3 --clean-up-blocks
91
+ ```
92
+
93
+ `--clean-up-blocks`は、TurboWarpの「きれいにする」配置と同じ開始座標、列の判定範囲、余白を使用します。
94
+ ブロック、変数、リスト、コメントは削除せず、ブロックに付いたコメントはスクリプトと一緒に移動します。変換する
95
+ のは生成物内の`project.json`だけであり、展開ソースは変更しません。生成SB3をTurboWarpで開いた後は座標変更を
96
+ 元に戻せない場合があります。ソース座標へ戻すにはこのオプションを外して再ビルドしてください。
97
+
87
98
  プロジェクト固有のテストに加えて、生成SB3をTurboWarpで開き、起動、主要な操作、画像、音声、埋め込み
88
99
  機能拡張の動作を確認してください。
89
100
 
90
101
  ## 管理対象の埋め込み機能拡張
91
102
 
92
- `embedded-extensions.json`の`source`オブジェクトには、GitHubリポジトリ、追跡対象ref、解決済みコミット、
93
- 成果物パス、SHA-256を記録できます。更新時の静的互換性検査に使用するバージョン付きAPIマニフェストも任意で
94
- 設定できます。完全なスキーマは[`source-format-v1.md`](source-format-v1.md)を参照してください。
103
+ `embedded-extensions.json`の`source`オブジェクトには、GitHubコミットの来歴またはインストール済みnpm
104
+ パッケージの完全固定バージョンと、成果物パス、SHA-256を記録できます。更新時の静的互換性検査に使用する
105
+ バージョン付きAPIマニフェストも任意で設定できます。完全なスキーマは
106
+ [`source-format-v1.md`](source-format-v1.md)を参照してください。
95
107
 
96
108
  機能拡張コマンドの役割は次のとおりです。
97
109
 
98
- | コマンド | ネットワーク | refの解決 | メタデータ更新 | 目的 |
99
- | ----------------------- | ------------ | --------- | -------------- | -------------------------------------- |
100
- | `extensions status` | あり | あり | なし | 追跡対象refに更新があるか確認 |
101
- | `extensions sync` | あり | なし | なし | 固定したコミットからファイルを復元 |
102
- | `extensions update` | あり | あり | あり | 最新のrefコミットへ明示的に更新 |
103
- | `extensions migrate-id` | なし | なし | ID/参照 | プロジェクトで使用中の機能拡張IDを移行 |
104
- | `extensions bundle` | なし | なし | bundle設定 | 機能拡張を1つの権限単位へ統合 |
105
- | `extensions unbundle` | なし | なし | 設定またはSB3 | 個別機能拡張を使用する出力へ復元 |
110
+ | コマンド | ネットワーク | refの解決 | メタデータ更新 | 目的 |
111
+ | ----------------------- | ------------ | ---------- | -------------- | -------------------------------------- |
112
+ | `extensions status` | GitHubのみ | GitHubのみ | なし | 上流または導入済みパッケージを確認 |
113
+ | `extensions sync` | GitHubのみ | なし | なし | 宣言したsourceからファイルを復元 |
114
+ | `extensions update` | GitHubのみ | GitHubのみ | あり | 上流または導入済みパッケージを採用 |
115
+ | `extensions migrate-id` | なし | なし | ID/参照 | プロジェクトで使用中の機能拡張IDを移行 |
116
+ | `extensions bundle` | なし | なし | bundle設定 | 機能拡張を1つの権限単位へ統合 |
117
+ | `extensions unbundle` | なし | なし | 設定またはSB3 | 個別機能拡張を使用する出力へ復元 |
106
118
 
107
119
  ### 更新の確認
108
120
 
@@ -110,8 +122,8 @@ sb3-toolchain build app --output dist/project.sb3
110
122
  sb3-toolchain extensions status app
111
123
  ```
112
124
 
113
- `status`はローカルファイルを変更しません。追跡対象refが`resolvedCommit`と異なる機能拡張について上流の
114
- 変更を確認し、更新するかどうかを判断します。
125
+ `status`はローカルファイルを変更しません。GitHub sourceでは追跡対象refと`resolvedCommit`を比較します。
126
+ npm sourceでは、宣言した完全固定バージョンとインストール済みパッケージをネットワークなしで比較します。
115
127
 
116
128
  ### 固定したコミットからの復元
117
129
 
@@ -120,9 +132,9 @@ sb3-toolchain extensions sync app
120
132
  sb3-toolchain check app
121
133
  ```
122
134
 
123
- `sync`は変更可能なブランチやタグを解決しません。記録済みの`resolvedCommit`からダウンロードし、
124
- JavaScriptと任意のAPIマニフェストが記録済みIDおよびSHA-256値に一致する場合に限り、ローカルファイルを
125
- 置き換えます。
135
+ `sync`は変更可能なブランチやタグを解決しません。GitHub sourceは`resolvedCommit`からダウンロードし、
136
+ npm sourceは最寄りの親`node_modules`へ導入済みの完全固定パッケージから読み込みます。JavaScriptと任意の
137
+ APIマニフェストが記録済みIDおよびSHA-256値に一致する場合に限り、ローカルファイルを置き換えます。
126
138
 
127
139
  ### 追跡対象refの更新
128
140
 
@@ -136,6 +148,10 @@ git diff -- app
136
148
  IDを省略すると、管理対象の全機能拡張を1回のトランザクションで更新します。ダウンロードまたは検証が1つでも
137
149
  失敗した場合、ファイルもメタデータも変更しません。
138
150
 
151
+ npm sourceでは、最初にプロジェクトのパッケージマネージャーで新しい完全固定バージョンを導入し、続けて
152
+ `extensions status`と`extensions update`を実行します。updateは導入済み成果物をコピーし、パッケージの
153
+ `version`とintegrityを記録します。sb3-toolchain自身はnpm registryへ問い合わせません。
154
+
139
155
  `source.apiManifest`が存在する場合、同じ解決済みコミットからJavaScriptとAPIマニフェストをダウンロードします。
140
156
  互換性のある追加は報告されます。ブロックの削除、ブロック種別の変更、引数契約の変更、参照中メニューの削除、
141
157
  `acceptReporters`の変更は、インストール前に拒否されます。未参照メニューの削除には互換性があります。
@@ -148,8 +164,8 @@ sb3-toolchain extensions update app EXTENSION_ID --allow-breaking-api --yes
148
164
  バージョン付きマニフェスト契約、分類表、既定OFFの動作、ロールバックについては、
149
165
  [`extension-api-compatibility.md`](extension-api-compatibility.md)を参照してください。
150
166
 
151
- 更新PRでは、`resolvedCommit`、JavaScriptとマニフェストのintegrity、互換性パス、両成果物をまとめて確認し、
152
- 生成SB3で機能拡張の主要機能をテストします。
167
+ 更新PRでは、`resolvedCommit`またはnpmの`version`、JavaScriptとマニフェストのintegrity、互換性パス、
168
+ 両成果物をまとめて確認し、生成SB3で機能拡張の主要機能をテストします。
153
169
 
154
170
  ## 機能拡張IDの移行
155
171
 
@@ -44,7 +44,7 @@ reconstruct the data URL.
44
44
  ## `embedded-extensions.json`
45
45
 
46
46
  This file records embedded extension data URL information and extraction paths. Optional `source`
47
- metadata can be added for an extension managed from GitHub.
47
+ metadata can be added for an extension managed from GitHub or an installed npm package.
48
48
 
49
49
  ```json
50
50
  {
@@ -75,10 +75,25 @@ metadata can be added for an extension managed from GitHub.
75
75
  }
76
76
  ```
77
77
 
78
+ For an exact npm dependency, replace the GitHub-specific fields with the package identity:
79
+
80
+ ```json
81
+ {
82
+ "provider": "npm",
83
+ "package": "@owner/example-extension",
84
+ "version": "1.2.3",
85
+ "artifact": "dist/example.js",
86
+ "integrity": "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
87
+ }
88
+ ```
89
+
90
+ - `provider`: `github` or `npm`
78
91
  - `repository`: GitHub repository in `<owner>/<repository>` form
79
92
  - `ref`: branch, tag, or commit to track for update candidates
80
93
  - `resolvedCommit`: lowercase 40-character commit SHA used to obtain the current file
81
- - `artifact`: JavaScript artifact path relative to the repository root
94
+ - `package`: exact npm package name, including its scope when applicable
95
+ - `version`: exact semantic version recorded in the installed package's `package.json`; ranges are not accepted
96
+ - `artifact`: JavaScript artifact path relative to the repository or npm package root
82
97
  - `integrity`: SRI-form SHA-256 of the current file
83
98
  - `apiManifest`: optional, opt-in API compatibility metadata
84
99
  - `artifact`: API manifest path relative to the same GitHub repository
@@ -90,7 +105,7 @@ Validation and builds verify managed extensions without accessing the network:
90
105
 
91
106
  - The actual file SHA-256 matches `integrity`
92
107
  - The file's `// ID: <extensionId>` header matches `id`
93
- - The repository, ref, commit, and artifact path use safe forms
108
+ - The GitHub repository, ref, commit, npm package, exact version, and artifact path use safe forms
94
109
  - When `apiManifest` exists, its JSON schema, ID, format version, path, and SHA-256 are valid
95
110
 
96
111
  Re-importing an SB3 into an existing expanded source directory preserves `source` metadata for the
@@ -98,12 +113,14 @@ same ID and path. If the imported file does not match the recorded hash or ID, t
98
113
  without changing the existing output. A new import cannot infer provenance, so it does not create
99
114
  `source` automatically.
100
115
 
101
- `extensions sync` downloads the JavaScript and optional API manifest using the immutable
102
- `resolvedCommit` and restores local files only when their IDs and hashes match the existing metadata.
103
- `extensions update` resolves `ref` through the GitHub API, downloads both artifacts from that same
104
- commit, and compares a candidate API manifest with the installed contract. It updates
105
- `resolvedCommit` and both integrity values only after compatibility and content validation succeed.
106
- The expanded source is not changed until every selected entry has been downloaded and validated.
116
+ For GitHub sources, `extensions sync` downloads the JavaScript and optional API manifest using the
117
+ immutable `resolvedCommit`. For npm sources, it reads them from the exact package installed in the
118
+ nearest ancestor `node_modules` directory without network access. Both paths restore local files only
119
+ when IDs and hashes match existing metadata. After the package manager installs a newer exact npm
120
+ version, `extensions update` copies its artifacts and updates `version` and integrity metadata.
121
+ GitHub updates instead resolve `ref` and update `resolvedCommit`. Candidate API manifests are compared
122
+ before either type is installed. The expanded source remains unchanged until every selected entry has
123
+ been validated.
107
124
 
108
125
  An extension ID migration changes the manifest `id` and `path`, known references in
109
126
  `project.source.json`, and `extensions/<id>.js` in one transaction. When a managed extension is
package/docs/workflows.md CHANGED
@@ -83,22 +83,35 @@ expanded format, embedded extension IDs, and SHA-256 hashes using only local inp
83
83
  and expanded source produce a bit-for-bit identical SB3. An identical existing output is left
84
84
  untouched. A differing output requires replacement confirmation or `--yes`.
85
85
 
86
+ To arrange the top-level scripts in every target before writing the generated SB3, opt in explicitly:
87
+
88
+ ```bash
89
+ sb3-toolchain build app --output dist/project.sb3 --clean-up-blocks
90
+ ```
91
+
92
+ `--clean-up-blocks` uses TurboWarp's cleaned-layout starting coordinates, column grouping tolerance,
93
+ and spacing. It preserves blocks, variables, lists, and comments; attached comments move with their
94
+ scripts. Only the generated `project.json` is transformed, so the expanded source remains unchanged.
95
+ TurboWarp might not be able to undo these coordinate changes after opening the generated SB3. Omit
96
+ the option and rebuild to roll back to the source coordinates.
97
+
86
98
  In addition to project-specific tests, open the generated SB3 in TurboWarp and verify startup, primary
87
99
  operations, images, sounds, and embedded extension behavior.
88
100
 
89
101
  ## Managed embedded extensions
90
102
 
91
- The `source` object in `embedded-extensions.json` can record the GitHub repository, tracked ref,
92
- resolved commit, artifact path, and SHA-256. It can also opt in to a versioned API manifest for static
93
- update compatibility checks. See [`source-format-v1.md`](source-format-v1.md) for the complete schema.
103
+ The `source` object in `embedded-extensions.json` can record either GitHub commit provenance or an
104
+ exact installed npm package version, together with its artifact path and SHA-256. It can also opt in
105
+ to a versioned API manifest for static update compatibility checks. See
106
+ [`source-format-v1.md`](source-format-v1.md) for the complete schema.
94
107
 
95
108
  The extension commands have the following roles:
96
109
 
97
110
  | Command | Network | Resolve ref | Metadata update | Purpose |
98
111
  | ----------------------- | ------- | ----------- | --------------- | ------------------------------------------- |
99
- | `extensions status` | Yes | Yes | No | Check whether a tracked ref has an update |
100
- | `extensions sync` | Yes | No | No | Restore files from the pinned commit |
101
- | `extensions update` | Yes | Yes | Yes | Explicitly update to the latest ref commit |
112
+ | `extensions status` | GitHub | GitHub | No | Check the upstream or installed package |
113
+ | `extensions sync` | GitHub | No | No | Restore files from the declared source |
114
+ | `extensions update` | GitHub | GitHub | Yes | Adopt the upstream or installed package |
102
115
  | `extensions migrate-id` | No | No | IDs/references | Migrate an extension ID used by the project |
103
116
  | `extensions bundle` | No | No | Bundle config | Combine extensions into one permission unit |
104
117
  | `extensions unbundle` | No | No | Config or SB3 | Restore output with individual extensions |
@@ -109,8 +122,8 @@ The extension commands have the following roles:
109
122
  sb3-toolchain extensions status app
110
123
  ```
111
124
 
112
- `status` does not change local files. Review upstream changes for extensions whose tracked ref differs
113
- from `resolvedCommit`, then decide whether to update.
125
+ `status` does not change local files. GitHub sources compare the tracked ref with `resolvedCommit`.
126
+ npm sources compare the declared exact version with the installed package without network access.
114
127
 
115
128
  ### Restore from a pinned commit
116
129
 
@@ -119,9 +132,9 @@ sb3-toolchain extensions sync app
119
132
  sb3-toolchain check app
120
133
  ```
121
134
 
122
- `sync` does not resolve a mutable branch or tag. It downloads from the recorded `resolvedCommit` and
123
- replaces local files only when JavaScript and an optional API manifest match their recorded IDs and
124
- SHA-256 values.
135
+ `sync` does not resolve a mutable branch or tag. GitHub sources download from `resolvedCommit`; npm
136
+ sources read from the exact package installed in the nearest ancestor `node_modules`. It replaces
137
+ local files only when JavaScript and an optional API manifest match recorded IDs and SHA-256 values.
125
138
 
126
139
  ### Update a tracked ref
127
140
 
@@ -135,6 +148,10 @@ git diff -- app
135
148
  Omitting the ID updates all managed extensions as one transaction. If any download or validation
136
149
  fails, neither files nor metadata are changed.
137
150
 
151
+ For an npm source, first use the project package manager to install a new exact dependency version,
152
+ then run `extensions status` and `extensions update`. The update copies the installed artifacts and
153
+ records their package `version` and integrity. It never queries the npm registry itself.
154
+
138
155
  When `source.apiManifest` is present, the update downloads JavaScript and the API manifest from the
139
156
  same resolved commit. Compatible additions are reported. A removed block, changed block type,
140
157
  argument-contract change, removed referenced menu, or `acceptReporters` change is rejected before
@@ -148,8 +165,9 @@ sb3-toolchain extensions update app EXTENSION_ID --allow-breaking-api --yes
148
165
  See [`extension-api-compatibility.md`](extension-api-compatibility.md) for the versioned manifest
149
166
  contract, classification table, default-off behavior, and rollback.
150
167
 
151
- In an update PR, review `resolvedCommit`, JavaScript and manifest integrity, compatibility paths, and
152
- both artifacts together, then test the extension's primary features in the generated SB3.
168
+ In an update PR, review `resolvedCommit` or npm `version`, JavaScript and manifest integrity,
169
+ compatibility paths, and both artifacts together, then test the extension's primary features in the
170
+ generated SB3.
153
171
 
154
172
  ## Migrate an extension ID
155
173
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/sb3-toolchain",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",
package/src/build.js CHANGED
@@ -152,9 +152,15 @@ export async function writeSb3Archive({
152
152
  };
153
153
  }
154
154
 
155
- export async function buildSb3({confirmReplace, outputPath, sourceDirectory, yes = false}) {
155
+ export async function buildSb3({
156
+ cleanUpBlocks = false,
157
+ confirmReplace,
158
+ outputPath,
159
+ sourceDirectory,
160
+ yes = false,
161
+ }) {
156
162
  assert(typeof sourceDirectory === 'string', 'SB3 source directory is required.');
157
- const built = await createDeterministicSb3(sourceDirectory);
163
+ const built = await createDeterministicSb3(sourceDirectory, {cleanUpBlocks});
158
164
  const written = await writeSb3Archive({
159
165
  archive: built.archive,
160
166
  confirmReplace,
package/src/cli.js CHANGED
@@ -23,7 +23,7 @@ export function usage() {
23
23
  return `Usage:
24
24
  sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]
25
25
  sb3-toolchain check SOURCE_DIR
26
- sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--yes]
26
+ sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--clean-up-blocks] [--yes]
27
27
  sb3-toolchain extensions status SOURCE_DIR
28
28
  sb3-toolchain extensions sync SOURCE_DIR [--yes]
29
29
  sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]
@@ -38,6 +38,12 @@ Commands:
38
38
  build Build a deterministic SB3 from expanded sources.
39
39
  extensions Inspect, restore, or update managed embedded extensions.
40
40
 
41
+ Build layout cleanup:
42
+ --clean-up-blocks applies a deterministic TurboWarp-style "Clean up Blocks"
43
+ layout to every target in the generated SB3. It never deletes blocks,
44
+ variables, lists, or comments. The expanded source is unchanged, but the
45
+ generated SB3 might not be able to undo the coordinate changes.
46
+
41
47
  Replacement safety:
42
48
  Differing outputs require interactive confirmation or --yes.
43
49
  Import refuses to discard uncommitted Git changes unless
@@ -91,13 +97,16 @@ function parseCheckArguments(arguments_) {
91
97
  }
92
98
 
93
99
  function parseBuildArguments(arguments_) {
100
+ let cleanUpBlocks = false;
94
101
  let sourceDirectory;
95
102
  let outputPath;
96
103
  let yes = false;
97
104
 
98
105
  for (let index = 0; index < arguments_.length; index += 1) {
99
106
  const argument = arguments_[index];
100
- if (argument === '--output') {
107
+ if (argument === '--clean-up-blocks') {
108
+ cleanUpBlocks = true;
109
+ } else if (argument === '--output') {
101
110
  outputPath = path.resolve(takeValue(arguments_, index, '--output'));
102
111
  index += 1;
103
112
  } else if (argument === '--yes') {
@@ -111,7 +120,13 @@ function parseBuildArguments(arguments_) {
111
120
 
112
121
  assert(sourceDirectory, 'The build command requires SOURCE_DIR.');
113
122
  assert(outputPath, 'The build command requires --output OUTPUT.sb3.');
114
- return {command: 'build', outputPath, sourceDirectory, yes};
123
+ return {
124
+ ...(cleanUpBlocks ? {cleanUpBlocks} : {}),
125
+ command: 'build',
126
+ outputPath,
127
+ sourceDirectory,
128
+ yes,
129
+ };
115
130
  }
116
131
 
117
132
  function parseExtensionMutationArguments(action, arguments_) {
@@ -481,15 +496,20 @@ export async function runCli(
481
496
  }
482
497
  if (options.command === 'build' && 'outputPath' in options) {
483
498
  const result = await buildSb3({
499
+ cleanUpBlocks: options.cleanUpBlocks,
484
500
  confirmReplace: confirmBuildReplacement,
485
501
  outputPath: options.outputPath,
486
502
  sourceDirectory: options.sourceDirectory,
487
503
  yes: options.yes,
488
504
  });
489
505
  const action = result.changed ? 'Built' : 'Already up to date';
506
+ const cleanUpMessage = result.blockCleanUp
507
+ ? `, ${result.blockCleanUp.movedScriptCount}/${result.blockCleanUp.scriptCount} scripts laid out`
508
+ : '';
490
509
  log(
491
510
  `${action}: ${result.outputPath} (${result.entryCount} entries, ` +
492
- `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions).`,
511
+ `${result.assetCount} assets, ${result.embeddedExtensionCount} embedded extensions` +
512
+ `${cleanUpMessage}).`,
493
513
  );
494
514
  if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);
495
515
  return;
@@ -557,6 +577,13 @@ export async function runCli(
557
577
  return;
558
578
  }
559
579
  for (const status of statuses) {
580
+ if (status.package) {
581
+ log(
582
+ `${status.id}: ${status.state}; local=${status.local}; ` +
583
+ `${status.package}@${status.version} (installed ${status.installedVersion})`,
584
+ );
585
+ continue;
586
+ }
560
587
  log(
561
588
  `${status.id}: ${status.state}; local=${status.local}; ` +
562
589
  `${status.ref} -> ${status.remoteCommit} ` +
package/src/constants.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
 
3
3
  export const packageName = '@kubohiroya/sb3-toolchain';
4
- export const packageVersion = '0.4.0';
4
+ export const packageVersion = '0.5.0';
@@ -205,6 +205,14 @@ export function createStaticExtensionBundle(bundle, components, originalProject
205
205
  : opcode;
206
206
  };
207
207
 
208
+ const rewriteBundleOpcode = (opcode) => {
209
+ for (const componentId of COMPONENT_IDS) {
210
+ const rewritten = rewriteOpcode(componentId, opcode);
211
+ if (rewritten !== opcode) return rewritten;
212
+ }
213
+ return opcode;
214
+ };
215
+
208
216
  const xmlEscape = (value) => String(value).replace(/[<>&'"]/gu, (character) => ({
209
217
  '<': '&lt;',
210
218
  '>': '&gt;',
@@ -261,6 +269,9 @@ export function createStaticExtensionBundle(bundle, components, originalProject
261
269
  if (property === 'startHats') {
262
270
  return (opcode, ...args) => target.startHats(rewriteOpcode(componentId, opcode), ...args);
263
271
  }
272
+ if (property === 'getOpcodeFunction') {
273
+ return (opcode, ...args) => target.getOpcodeFunction(rewriteBundleOpcode(opcode), ...args);
274
+ }
264
275
  const value = Reflect.get(target, property, target);
265
276
  return typeof value === 'function' ? value.bind(target) : value;
266
277
  },