@kubohiroya/turbowarp-react-islands 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/index.html CHANGED
@@ -9,8 +9,17 @@
9
9
  code{background:#f3f3f3;padding:.1em .3em;border-radius:.25em}
10
10
  pre{background:#f6f8fa;padding:1rem;overflow:auto;border-radius:.5rem}
11
11
  </style>
12
+ <style id="block-reference-style">
13
+ #extension-block-reference{max-width:72rem;margin:2rem auto;padding:1rem;line-height:1.6;overflow-wrap:anywhere}
14
+ #extension-block-reference .block-reference-entry{display:block;scroll-margin-top:6rem;margin:2rem 0;padding:1rem;border:1px solid currentColor;border-radius:.5rem}
15
+ #extension-block-reference .block-reference-table{overflow-x:auto}
16
+ #extension-block-reference table{border-collapse:collapse;width:100%}
17
+ #extension-block-reference th,#extension-block-reference td{text-align:left;vertical-align:top;border:1px solid currentColor;padding:.5rem}
18
+ #extension-block-reference code{white-space:pre-wrap}
19
+ #extension-block-reference a:focus-visible{outline:3px solid currentColor;outline-offset:3px}
20
+ </style>
12
21
  </head>
13
- <body>
22
+ <body><p lang="en" class="complete-block-reference-link"><a href="#extension-block-reference">Complete block reference (4 blocks)</a></p>
14
23
  <h1>TurboWarp React Islands</h1>
15
24
  <p>This extension describes React islands for HTML responses produced by turbowarp-http-server and turbowarp-html.</p>
16
25
 
@@ -33,5 +42,18 @@
33
42
  "mountId": "counter-root",
34
43
  "props": {"initialCount": 0}
35
44
  }</code></pre>
45
+ <!-- BEGIN COMPLETE BLOCK REFERENCE -->
46
+ <section lang="en" id="extension-block-reference" aria-labelledby="block-reference-title">
47
+ <h2 id="block-reference-title">TurboWarp React Islands: complete block reference</h2>
48
+ <p>All 4 blocks are documented below, including compatibility blocks and blocks available through optional features. Select a block to read its behavior, arguments, default values, and menu choices. Each block has a permanent link.</p>
49
+ <nav aria-label="Block reference"><ul><li><a href="#block-registerComponent"><code>register React component [COMPONENT] from [MODULE]</code></a></li>
50
+ <li><a href="#block-reactIsland"><code>React island [COMPONENT] at [MOUNT_ID] props [PROPS_JSON]</code></a></li>
51
+ <li><a href="#block-reactIslandHtml"><code>React island HTML [COMPONENT] at [MOUNT_ID] props [PROPS_JSON]</code></a></li>
52
+ <li><a href="#block-componentRegistryJson"><code>React component registry JSON</code></a></li>
53
+ </ul></nav>
54
+ <article id="block-registerComponent" class="block-reference-entry"><h3><code>register React component [COMPONENT] from [MODULE]</code></h3><p>Registers a React component name and the browser module that will hydrate it later.</p><p>Block type: COMMAND. Opcode: <code>registerComponent</code>. <a href="#block-registerComponent">Permanent link</a></p><div class="block-reference-table"><table><thead><tr><th>Argument</th><th>Type</th><th>Default value</th><th>Menu choices</th></tr></thead><tbody><tr><th scope="row"><code>COMPONENT</code></th><td>STRING</td><td><code>Counter</code></td><td></td></tr><tr><th scope="row"><code>MODULE</code></th><td>STRING</td><td><code>/assets/react-islands.js</code></td><td></td></tr></tbody></table></div></article><article id="block-reactIsland" class="block-reference-entry"><h3><code>React island [COMPONENT] at [MOUNT_ID] props [PROPS_JSON]</code></h3><p>Returns a JSON mount descriptor for a React island.</p><p>Block type: REPORTER. Opcode: <code>reactIsland</code>. <a href="#block-reactIsland">Permanent link</a></p><div class="block-reference-table"><table><thead><tr><th>Argument</th><th>Type</th><th>Default value</th><th>Menu choices</th></tr></thead><tbody><tr><th scope="row"><code>COMPONENT</code></th><td>STRING</td><td><code>Counter</code></td><td></td></tr><tr><th scope="row"><code>MOUNT_ID</code></th><td>STRING</td><td><code>counter-root</code></td><td></td></tr><tr><th scope="row"><code>PROPS_JSON</code></th><td>STRING</td><td><code>{&quot;initialCount&quot;:0}</code></td><td></td></tr></tbody></table></div></article><article id="block-reactIslandHtml" class="block-reference-entry"><h3><code>React island HTML [COMPONENT] at [MOUNT_ID] props [PROPS_JSON]</code></h3><p>Returns a safe HTML fragment that marks where a React island should be mounted.</p><p>Block type: REPORTER. Opcode: <code>reactIslandHtml</code>. <a href="#block-reactIslandHtml">Permanent link</a></p><div class="block-reference-table"><table><thead><tr><th>Argument</th><th>Type</th><th>Default value</th><th>Menu choices</th></tr></thead><tbody><tr><th scope="row"><code>COMPONENT</code></th><td>STRING</td><td><code>Counter</code></td><td></td></tr><tr><th scope="row"><code>MOUNT_ID</code></th><td>STRING</td><td><code>counter-root</code></td><td></td></tr><tr><th scope="row"><code>PROPS_JSON</code></th><td>STRING</td><td><code>{&quot;initialCount&quot;:0}</code></td><td></td></tr></tbody></table></div></article><article id="block-componentRegistryJson" class="block-reference-entry"><h3><code>React component registry JSON</code></h3><p>Returns the registered React component registry as JSON.</p><p>Block type: REPORTER. Opcode: <code>componentRegistryJson</code>. <a href="#block-componentRegistryJson">Permanent link</a></p><p>This block has no arguments.</p></article>
55
+ <p><a href="https://github.com/kubohiroya/turbowarp-react-islands/blob/main/README.md">Repository guide and examples</a></p>
56
+ </section>
57
+ <!-- END COMPLETE BLOCK REFERENCE -->
36
58
  </body>
37
59
  </html>
@@ -0,0 +1,20 @@
1
+ # 段階2 Source/Form編集
2
+
3
+ この文書はローカル実装時の契約を示す。npm公開は実施しない。
4
+
5
+ - 対象: reactIsland.PROPS_JSON / reactIslandHtml.PROPS_JSON
6
+ - 契約: react-props
7
+ - Schema正本: schemas/react-props.schema.json。Schema文書はcanonical-schema、bundleは正本参照とprovenanceを保持する。
8
+ - owner受理条件: src/island.ts の parsePropsJson。propsはobjectのみ。空白sourceは既存挙動の{}として編集表示するが、無変更時のsourceは空白のまま。component名候補は段階4。
9
+
10
+ UIはSourceとFormを切り替える。無変更・cancel・編集後の元の値への復帰は入力文字列をそのまま保持する。Formの部分編集でも未知キー・null・空文字・配列の順序と重複・未編集箇所の表記を維持する。既定値の暗黙補完、variant/formatの暗黙移行、runtime正規化後の値の書き戻しは行わない。不正なsourceもSourceとして開き修復できるが、ownerに拒否される候補は保存できない。
11
+
12
+ 利用条件は、GUI起動時に `blockEditorDialogs=1` と `blockEditorSourceForms=1` の両方を指定し、信頼した拡張をunsandboxedで読み込むこと。`Scratch.gui.blockEditors` はunsandboxed拡張APIにのみ提供される。既存のsandbox実行権限や拡張の既定の読み込み方法は変更しない。sandboxed実行では従来のブロックを使用し、編集capabilityがないためフォーム登録を省略する。
13
+
14
+ 登録入口はoptionalな `Scratch.gui.blockEditors.registerSourceEditor`。GUIの起動時固定 `blockEditorSourceForms` は既定OFF、既存 `blockEditorDialogs` が前提となる。旧GUIやcapabilityを持たないhostでは登録を行わず、既存ブロックのAPI・引数・実行挙動は維持する。`dispose()` またはruntime破棄で登録を解除する。既存のruntime処理を実行せず、pure parser/validatorで保存候補の同じsourceを検査する。複数入力のブロックは単一editor definitionとして一度に検査・commitする。
15
+
16
+ 依存: 共通エディターの新 `./schema` 型・json-value契約と新prepared save経路、およびGUIのcapabilityが必要。ローカル検証は独立cloneから新共通artifactへaliasする。遠隔配布用のpin・lockは最終共通artifactのSHA確定後に揃える。架空のSHAを記載しない。
17
+
18
+ 受け入れ基準: 全対象inputの登録、既存受理との互換、Source修復、不正保存の拒否、no-opでundoを作らないこと、部分編集でraw値を維持すること、runtime破棄時の解除、既存APIのテスト・型検査・buildを確認する。原文不変・部分編集・拒否は `tests/source-editor.test.ts` から実際の共通serviceと接続して検証する。
19
+
20
+ ロールバック: 起動時 `blockEditorSourceForms` をOFFに戻してGUIを再起動する。登録capabilityを外すと新フォームは使用されず、既存のブロックと保存済みsourceは引き続き実行できる。Schema自体の編集・実行時の値からの動的Schema・値候補との接続は別工程。
@@ -0,0 +1,26 @@
1
+ # 段階2の安定版検証記録
2
+
3
+ 公開予定版: `@kubohiroya/turbowarp-react-islands@0.3.0`。PROPS_JSON のobject固定Schemaを接続します。空propsの無変更保存で空文字を{}へ変換しません。
4
+
5
+ | opcode | 入力 |
6
+ | --- | --- |
7
+ | reactIsland, reactIslandHtml | PROPS_JSON |
8
+
9
+ 正本は `schemas/react-props.schema.json` と既存 `src/island.ts` のpure検証です。object rootと未知プロパティを編集し、空入力のraw互換性を維持します。
10
+
11
+ 共通依存は `76fa1d50a3c188082ceef723ea018a9d8769ea6e`(`@kubohiroya/turbowarp-extension-data-editor` 0.2.0)へGitの完全SHAで固定しています。manifest・lock・build許可・fresh実解決を揃え、直接・AJV経由のfast-uriを3.1.8へ統一しています。古い共有aliasの実解決を安定版の検証として流用していません。
12
+
13
+ `react-dom@18.3.1` は実際のRJSF registration回帰テストに必要なdev依存として追加しました。拡張のruntimeコードはGUIのoptional APIを使い、ReactDOMを拡張bundleへ追加しません。
14
+
15
+ Node v22.23.3 / pnpm 11.11.0で、空の専用storeからscripts有効の `pnpm install --frozen-lockfile` を実施しました。Git prepareから得た共通packageにはsrcが含まれず、build-infoは上記SHAと一致します。
16
+
17
+ - 全テスト 17件、型検査、全lint、build、文書/リポジトリ検査、pack検査が成功しました。
18
+ - production auditはcritical/high/moderate/lowすべて0件です。
19
+ - dist 5件は2回のbuildでSHA-256が一致し、異なるcheckout pathのfresh fixtureと作業cloneでも全件のbytesが一致しました。
20
+ - Vite8を使う場合の生成region行にはpackage storeのpathが入るため、そのマーカー行だけを省きます。licenseコメントと実行コードは保持します。Vite7のrepoにはこの追加処理を適用しません。
21
+
22
+ 過去の段階2ローカル全体659件・実GUI5ケース(各8手順)は別の保存済み記録です。今回の数は当該repoのfresh full結果であり、繰り返し実行を合算していません。GitHub CIの結果はPRで別途確認します。
23
+
24
+ GUIの起動時固定・既定OFFの `blockEditorSourceForms` と `blockEditorDialogs` の両方、および信頼した拡張のunsandboxed読込を必要とします。旧API、ブロックのopcode/入力、raw保存形式を保持し、無変更・Cancelでは元の入力を維持します。検査した候補だけを保存し、複数入力はatomicに保存します。Schema自体の編集・動的Schema・既存候補への新規項目追加はこの段階に含みません。
25
+
26
+ ロールバックはflagをOFFにして再読込します。コードを戻す場合はconsumer→producer→共通の逆順でrevertし、manifest・lock・実解決を一体で戻します。以前の公開版 `@kubohiroya/turbowarp-react-islands@0.2.0` へ固定できます。保存形式を自動移行しません。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-react-islands",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "TurboWarp extension and helpers for describing React islands in turbowarp-http-server HTML responses.",
5
5
  "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
6
6
  "license": "MPL-2.0",
@@ -27,11 +27,11 @@
27
27
  "files": [
28
28
  "dist/",
29
29
  "docs/",
30
- "schemas/",
31
30
  "src/",
32
31
  "README.md",
33
32
  "README.ja.md",
34
- "LICENSE"
33
+ "LICENSE",
34
+ "schemas/"
35
35
  ],
36
36
  "exports": {
37
37
  "./island": {
@@ -62,12 +62,23 @@
62
62
  },
63
63
  "devDependencies": {
64
64
  "@eslint/js": "^9.39.5",
65
- "@kubohiroya/vite-plugin-turbowarp-extension": "0.1.1",
65
+ "@kubohiroya/turbowarp-extension-manifest": "0.3.2",
66
+ "@kubohiroya/vite-plugin-turbowarp-extension": "0.6.1",
66
67
  "@types/node": "^24.13.3",
67
68
  "eslint": "^9.39.5",
68
69
  "typescript": "^5.9.3",
69
70
  "typescript-eslint": "^8.66.0",
70
- "vite": "^7.3.6",
71
- "vitest": "^4.1.10"
71
+ "vite": "^8.2.2",
72
+ "vitest": "^4.1.10",
73
+ "react-dom": "18.3.1"
74
+ },
75
+ "dependencies": {
76
+ "@kubohiroya/turbowarp-extension-data-editor": "0.2.1"
77
+ },
78
+ "gitHead": "07b524c620ad8a8a491fc3d33d87dad584235354",
79
+ "x-turbowarp-source": {
80
+ "revision": "07b524c620ad8a8a491fc3d33d87dad584235354",
81
+ "revisionRole": "base-commit",
82
+ "sourceState": "local-release-overlay"
72
83
  }
73
84
  }
@@ -0,0 +1,5 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://kubohiroya.github.io/turbowarp-http-server-react/schemas/react-props.schema.json",
4
+ "type": "object"
5
+ }
@@ -0,0 +1,13 @@
1
+ import type {SourceEditorOptions} from '@kubohiroya/turbowarp-extension-data-editor/schema';
2
+ import {extensionConfig} from './config.js';
3
+ import {canonicalBundle, sourceBinding} from './source-editor.js';
4
+ import document from '../schemas/react-props.schema.json' with {type: 'json'};
5
+ import {parsePropsJson} from './island.js';
6
+ export const reactPropsSchemaBundle = canonicalBundle('turbowarp-http-server-react', 'react-props', document, {path: 'src/island.ts', symbol: 'parsePropsJson'});
7
+ const definitions = [{editorId: 'react-props-source', opcodes: ['reactIsland', 'reactIslandHtml'],
8
+ bindings: [sourceBinding('PROPS_JSON', reactPropsSchemaBundle, parsePropsJson)]}];
9
+
10
+ export const sourceEditorDefinitions: readonly SourceEditorOptions[] = definitions.map(({editorId, opcodes, bindings}) => ({
11
+ apiVersion: 1, extensionId: extensionConfig.id, editorId, opcodes: opcodes.map(opcode => `${extensionConfig.id}_${opcode}`), bindings,
12
+ validationContext: () => ({consumerId: extensionConfig.id, nowMs: Date.now(), settings: null})
13
+ }));
package/src/extension.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import {sourceEditorDefinitions} from './editor-schema.js';
2
+ import {registerSourceEditors} from './source-editor.js';
1
3
  import {extensionConfig} from './config';
2
4
  import definitions from './block-definitions.json';
3
5
  import {
@@ -27,6 +29,10 @@ interface BlockDefinition {
27
29
  const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
28
30
 
29
31
  export class TurboWarpHttpServerReactExtension implements TurboWarpExtension {
32
+ private readonly unregisterSourceEditors: () => void;
33
+ public constructor() {this.unregisterSourceEditors = registerSourceEditors(Scratch, sourceEditorDefinitions);}
34
+ public dispose(): void {this.unregisterSourceEditors();}
35
+
30
36
  private readonly registry = new ComponentRegistry();
31
37
 
32
38
  public getInfo(): Record<string, unknown> {
@@ -0,0 +1,57 @@
1
+ import {compileSchemaBundle, validateSchemaInput} from '@kubohiroya/turbowarp-extension-data-editor/schema';
2
+ import type {SchemaBundle, SchemaDocument, SchemaJsonValue, SourceBinding, SourceEditorOptions} from '@kubohiroya/turbowarp-extension-data-editor/schema';
3
+
4
+ export function canonicalBundle(ownerId: string, contractId: string, document: SchemaDocument, ownerSource: {path: string; symbol: string}): SchemaBundle {
5
+ const path = `schemas/${contractId}.schema.json`;
6
+ const source = {repository: ownerId, path};
7
+ return {
8
+ identity: {ownerId, contractId, revision: 'source-forms-v1', variantId: 'default'},
9
+ dialect: '2020-12',
10
+ root: {retrievalUri: `https://kubohiroya.github.io/${ownerId}/schemas/${contractId}.schema.json`, document,
11
+ artifact: {role: 'canonical-schema', source}},
12
+ resources: [], provenance: {canonicalSources: [source, {repository: ownerId, ...ownerSource}], generatedFiles: [], referenceSchemas: [], generationSources: []}
13
+ };
14
+ }
15
+
16
+ export function sourceBinding(argument: string, bundle: SchemaBundle,
17
+ read: (source: string) => unknown, check: (source: string) => unknown = read,
18
+ format: 'json' | 'yaml' = 'json', uiSchema?: SourceBinding['variants'][number]['uiSchema']): SourceBinding {
19
+ const compiled = compileSchemaBundle(bundle);
20
+ return {
21
+ argument,
22
+ variants: [{variantId: 'default', format, schemaBundle: bundle, ...(uiSchema ? {uiSchema} : {})}],
23
+ decode(source) {return {source, format, variantId: 'default', data: read(source) as SchemaJsonValue};},
24
+ validateSource(source, context) {
25
+ if (compiled.kind !== 'compiled') return {source, result: {kind: 'schema-error', diagnostics: [{code: 'source-schema-invalid'}]}};
26
+ try {
27
+ const data = read(source) as SchemaJsonValue;
28
+ return {source, result: validateSchemaInput(compiled.validator, data, {context,
29
+ ownerValidate: () => {
30
+ try {check(source); return {kind: 'valid', issues: []};}
31
+ catch {return {kind: 'invalid', issues: [{dataPath: '', ruleId: 'source-owner-invalid'}]};}
32
+ }})};
33
+ } catch {return {source, result: {kind: 'invalid', diagnostics: [{code: 'source-decode-invalid'}]}};}
34
+ }
35
+ };
36
+ }
37
+
38
+ /** The optional capability keeps legacy hosts and the startup flag safely inactive. */
39
+ export function registerSourceEditors(scratch: unknown, definitions: readonly SourceEditorOptions[]): () => void {
40
+ const host = scratch as {gui?: {blockEditors?: {apiVersion?: number; registerSourceEditor?: (options: SourceEditorOptions) => () => void}};
41
+ vm?: {runtime?: {on?: (event: string, listener: () => void) => void; off?: (event: string, listener: () => void) => void}}};
42
+ const api = host.gui?.blockEditors;
43
+ if (api?.apiVersion !== 1 || typeof api.registerSourceEditor !== 'function') return () => {};
44
+ const removers: (() => void)[] = [];
45
+ let active = true;
46
+ const dispose = () => {
47
+ if (!active) return;
48
+ active = false;
49
+ host.vm?.runtime?.off?.('RUNTIME_DISPOSED', dispose);
50
+ for (const remove of removers.splice(0).reverse()) remove();
51
+ };
52
+ try {
53
+ for (const definition of definitions) removers.push(api.registerSourceEditor.call(api, definition));
54
+ host.vm?.runtime?.on?.('RUNTIME_DISPOSED', dispose);
55
+ } catch (error) {dispose(); throw error;}
56
+ return dispose;
57
+ }
@@ -1,49 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://raw.githubusercontent.com/kubohiroya/turbowarp-react-islands/main/schemas/extension-manifest.schema.json",
4
- "title": "TurboWarp Extension API Manifest",
5
- "type": "object",
6
- "additionalProperties": false,
7
- "required": ["formatVersion", "id", "blocks", "menus"],
8
- "properties": {
9
- "formatVersion": {"const": 1},
10
- "id": {"type": "string", "pattern": "^[a-z0-9]+$"},
11
- "blocks": {
12
- "type": "array",
13
- "items": {
14
- "type": "object",
15
- "additionalProperties": false,
16
- "required": ["opcode", "blockType", "arguments"],
17
- "properties": {
18
- "opcode": {"type": "string", "minLength": 1},
19
- "blockType": {"type": "string", "minLength": 1},
20
- "arguments": {
21
- "type": "array",
22
- "items": {
23
- "type": "object",
24
- "additionalProperties": false,
25
- "required": ["id", "type"],
26
- "properties": {
27
- "id": {"type": "string", "minLength": 1},
28
- "type": {"type": "string", "minLength": 1},
29
- "menu": {"type": "string", "minLength": 1}
30
- }
31
- }
32
- }
33
- }
34
- }
35
- },
36
- "menus": {
37
- "type": "array",
38
- "items": {
39
- "type": "object",
40
- "additionalProperties": false,
41
- "required": ["id", "acceptReporters"],
42
- "properties": {
43
- "id": {"type": "string", "minLength": 1},
44
- "acceptReporters": {"type": "boolean"}
45
- }
46
- }
47
- }
48
- }
49
- }
@@ -1,149 +0,0 @@
1
- import type {Plugin} from 'vite';
2
-
3
- export const EXTENSION_MANIFEST_FORMAT_VERSION = 1 as const;
4
-
5
- export interface ExtensionManifestArgument {
6
- id: string;
7
- type: string;
8
- menu?: string;
9
- }
10
-
11
- export interface ExtensionManifestBlock {
12
- opcode: string;
13
- blockType: string;
14
- arguments: ExtensionManifestArgument[];
15
- }
16
-
17
- export interface ExtensionManifestMenu {
18
- id: string;
19
- acceptReporters: boolean;
20
- }
21
-
22
- export interface ExtensionManifest {
23
- formatVersion: typeof EXTENSION_MANIFEST_FORMAT_VERSION;
24
- id: string;
25
- blocks: ExtensionManifestBlock[];
26
- menus: ExtensionManifestMenu[];
27
- }
28
-
29
- export interface ExtensionManifestPluginOptions {
30
- id: string;
31
- definitions: unknown;
32
- fileName?: string;
33
- }
34
-
35
- export function createExtensionManifest(id: string, definitions: unknown): ExtensionManifest {
36
- if (!/^[a-z0-9]+$/.test(id)) {
37
- throw new TypeError('Extension manifest ID must contain only lowercase letters and numbers.');
38
- }
39
-
40
- const source = requireRecord(definitions, 'Block definitions');
41
- const sourceBlocks = source.blocks;
42
- if (!Array.isArray(sourceBlocks)) {
43
- throw new TypeError('Block definitions must contain a blocks array.');
44
- }
45
-
46
- const menus = normalizeMenus(source.menus);
47
- const menuIds = new Set(menus.map((menu) => menu.id));
48
- const seenOpcodes = new Set<string>();
49
- const blocks = sourceBlocks.map((block, index) => {
50
- const normalized = normalizeBlock(block, index, menuIds);
51
- if (seenOpcodes.has(normalized.opcode)) {
52
- throw new TypeError(`Duplicate block opcode: ${normalized.opcode}`);
53
- }
54
- seenOpcodes.add(normalized.opcode);
55
- return normalized;
56
- });
57
-
58
- return {
59
- formatVersion: EXTENSION_MANIFEST_FORMAT_VERSION,
60
- id,
61
- blocks: blocks.sort((left, right) => compareIds(left.opcode, right.opcode)),
62
- menus
63
- };
64
- }
65
-
66
- export function serializeExtensionManifest(id: string, definitions: unknown): string {
67
- return `${JSON.stringify(createExtensionManifest(id, definitions), null, 2)}\n`;
68
- }
69
-
70
- export function extensionManifestPlugin(options: ExtensionManifestPluginOptions): Plugin {
71
- return {
72
- name: 'extension-api-manifest',
73
- apply: 'build',
74
- enforce: 'post',
75
- generateBundle() {
76
- this.emitFile({
77
- type: 'asset',
78
- fileName: options.fileName ?? 'extension-manifest.json',
79
- source: serializeExtensionManifest(options.id, options.definitions)
80
- });
81
- }
82
- };
83
- }
84
-
85
- function normalizeBlock(
86
- value: unknown,
87
- index: number,
88
- menuIds: ReadonlySet<string>
89
- ): ExtensionManifestBlock {
90
- const block = requireRecord(value, `Block at index ${index}`);
91
- const opcode = requireNonEmptyString(block.opcode, `Block at index ${index} opcode`);
92
- const blockType = requireNonEmptyString(block.blockType, `Block ${opcode} blockType`);
93
- const sourceArguments = block.arguments ?? {};
94
- const argumentRecord = requireRecord(sourceArguments, `Block ${opcode} arguments`);
95
- const argumentsList = Object.entries(argumentRecord).map(([argumentId, argument]) => {
96
- requireNonEmptyString(argumentId, `Block ${opcode} argument ID`);
97
- const definition = requireRecord(argument, `Block ${opcode} argument ${argumentId}`);
98
- const type = requireNonEmptyString(
99
- definition.type,
100
- `Block ${opcode} argument ${argumentId} type`
101
- );
102
- const menu = definition.menu;
103
- if (menu !== undefined && (typeof menu !== 'string' || !menuIds.has(menu))) {
104
- throw new TypeError(`Block ${opcode} argument ${argumentId} references unknown menu: ${menu}`);
105
- }
106
- return menu === undefined ? {id: argumentId, type} : {id: argumentId, type, menu};
107
- });
108
-
109
- return {
110
- opcode,
111
- blockType,
112
- arguments: argumentsList.sort((left, right) => compareIds(left.id, right.id))
113
- };
114
- }
115
-
116
- function normalizeMenus(value: unknown): ExtensionManifestMenu[] {
117
- const menuRecord = requireRecord(value ?? {}, 'Block definition menus');
118
- return Object.entries(menuRecord)
119
- .map(([id, menu]) => {
120
- requireNonEmptyString(id, 'Menu ID');
121
- const definition = requireRecord(menu, `Menu ${id}`);
122
- const acceptReporters = definition.acceptReporters ?? false;
123
- if (typeof acceptReporters !== 'boolean') {
124
- throw new TypeError(`Menu ${id} acceptReporters must be a boolean.`);
125
- }
126
- return {id, acceptReporters};
127
- })
128
- .sort((left, right) => compareIds(left.id, right.id));
129
- }
130
-
131
- function requireRecord(value: unknown, label: string): Record<string, unknown> {
132
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
133
- throw new TypeError(`${label} must be an object.`);
134
- }
135
- return value as Record<string, unknown>;
136
- }
137
-
138
- function requireNonEmptyString(value: unknown, label: string): string {
139
- if (typeof value !== 'string' || value.length === 0) {
140
- throw new TypeError(`${label} must be a non-empty string.`);
141
- }
142
- return value;
143
- }
144
-
145
- function compareIds(left: string, right: string): number {
146
- if (left < right) return -1;
147
- if (left > right) return 1;
148
- return 0;
149
- }