@kubohiroya/turbowarp-aframe 0.7.0 → 0.8.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/src/extension.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import {registerSourceEditors} from './source-editors.js';
2
+ import {validateTemplateNode, type TemplateNode} from './template-validation.js';
1
3
  import {extensionConfig} from './config';
2
4
  import definitions from './block-definitions.json';
3
5
  import {
@@ -26,15 +28,6 @@ interface BlockDefinition {
26
28
  arguments: Record<string, DefinitionArgument>;
27
29
  }
28
30
 
29
- interface TemplateNode {
30
- type?: string;
31
- id?: string;
32
- class?: string | string[];
33
- classes?: string[];
34
- data?: Record<string, unknown>;
35
- attributes?: Record<string, unknown>;
36
- children?: TemplateNode[];
37
- }
38
31
 
39
32
  interface SceneNode {
40
33
  id: string;
@@ -141,15 +134,7 @@ interface VrmHostElement {
141
134
  const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
142
135
  const ROOT_ID = 'scene';
143
136
  const DOM_EVENT_TYPES = ['click', 'tap', 'pointerenter', 'pointerleave'] as const;
144
- const TEMPLATE_NODE_KEYS = new Set([
145
- 'attributes',
146
- 'children',
147
- 'class',
148
- 'classes',
149
- 'data',
150
- 'id',
151
- 'type'
152
- ]);
137
+
153
138
 
154
139
  export class TurboWarpAFrameExtension implements TurboWarpExtension {
155
140
  private readonly nodes = new Map<string, SceneNode>();
@@ -167,7 +152,17 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
167
152
  private disposed = false;
168
153
  private readonly vrms = new VrmAvatars(() => this.getThree() as unknown as VrmThreeApi | null);
169
154
 
155
+ private readonly removeSourceEditors: () => void;
156
+ private readonly handleSourceEditorDispose = (): void => {
157
+ this.removeSourceEditors();
158
+ const runtime = Scratch.vm?.runtime as {off?: (event: string, listener: () => void) => void} | undefined;
159
+ runtime?.off?.('RUNTIME_DISPOSED', this.handleSourceEditorDispose);
160
+ };
161
+
170
162
  public constructor() {
163
+ this.removeSourceEditors = registerSourceEditors(Scratch);
164
+ const editorRuntime = Scratch.vm?.runtime as {on?: (event: string, listener: () => void) => void} | undefined;
165
+ editorRuntime?.on?.('RUNTIME_DISPOSED', this.handleSourceEditorDispose);
171
166
  this.resetGraph();
172
167
  this.runtimeCapability = createRuntimeCapability(
173
168
  {
@@ -640,6 +635,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
640
635
  public dispose(): void {
641
636
  if (this.disposed) return;
642
637
  this.disposed = true;
638
+ this.handleSourceEditorDispose();
643
639
  for (const key of [...this.animationPlaybacks.keys()]) {
644
640
  this.stopPlayback(key, true);
645
641
  }
@@ -1235,68 +1231,10 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
1235
1231
 
1236
1232
  private parseTemplate(source: string): TemplateNode {
1237
1233
  const value: unknown = JSON.parse(source);
1238
- this.validateTemplateNode(value, 'template');
1234
+ validateTemplateNode(value, 'template');
1239
1235
  return value as TemplateNode;
1240
1236
  }
1241
1237
 
1242
- private validateTemplateNode(value: unknown, path: string): asserts value is TemplateNode {
1243
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1244
- throw new TypeError(`A-Frame ${path} must be an object.`);
1245
- }
1246
- const node = value as Record<string, unknown>;
1247
- for (const key of Object.keys(node)) {
1248
- if (!TEMPLATE_NODE_KEYS.has(key)) {
1249
- throw new TypeError(`A-Frame ${path}.${key} is not supported.`);
1250
- }
1251
- }
1252
- this.validateOptionalString(node['type'], `${path}.type`);
1253
- this.validateOptionalString(node['id'], `${path}.id`);
1254
- this.validateTemplateClass(node['class'], `${path}.class`);
1255
- this.validateOptionalStringArray(node['classes'], `${path}.classes`);
1256
- this.validateStringRecord(node['data'], `${path}.data`);
1257
- this.validateStringRecord(node['attributes'], `${path}.attributes`);
1258
- const children = node['children'];
1259
- if (children === undefined) return;
1260
- if (!Array.isArray(children)) {
1261
- throw new TypeError(`A-Frame ${path}.children must be an array.`);
1262
- }
1263
- children.forEach((child, index) => {
1264
- this.validateTemplateNode(child, `${path}.children[${index}]`);
1265
- });
1266
- }
1267
-
1268
- private validateTemplateClass(value: unknown, path: string): void {
1269
- if (value === undefined || typeof value === 'string') return;
1270
- if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return;
1271
- throw new TypeError(`A-Frame ${path} must be a string or string array.`);
1272
- }
1273
-
1274
- private validateOptionalStringArray(value: unknown, path: string): void {
1275
- if (value === undefined) return;
1276
- if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return;
1277
- throw new TypeError(`A-Frame ${path} must be a string array.`);
1278
- }
1279
-
1280
- private validateOptionalString(value: unknown, path: string): void {
1281
- if (value === undefined || typeof value === 'string') return;
1282
- throw new TypeError(`A-Frame ${path} must be a string.`);
1283
- }
1284
-
1285
- private validateStringRecord(value: unknown, path: string): void {
1286
- if (value === undefined) return;
1287
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1288
- throw new TypeError(`A-Frame ${path} must be an object.`);
1289
- }
1290
- for (const [key, recordValue] of Object.entries(value)) {
1291
- if (key.trim().length === 0) {
1292
- throw new TypeError(`A-Frame ${path} keys must be non-empty strings.`);
1293
- }
1294
- if (recordValue === undefined) {
1295
- throw new TypeError(`A-Frame ${path}.${key} must not be undefined.`);
1296
- }
1297
- }
1298
- }
1299
-
1300
1238
  private normalizeClasses(template: TemplateNode): string[] {
1301
1239
  const classes = [
1302
1240
  ...(Array.isArray(template.class) ? template.class : String(template.class ?? '').split(/\s+/)),
@@ -0,0 +1,30 @@
1
+ import type {SourceBinding, SourceEditorOptions, SourceValidation} from '@kubohiroya/turbowarp-extension-data-editor/schema';
2
+ import {extensionConfig} from './config.js';
3
+
4
+ function checkedSource(value: {source: string; result: {kind: 'valid' | 'invalid' | 'execution-error' | 'schema-error'; diagnostics: readonly {code: string; dataPath?: string}[]}}): SourceValidation {
5
+ return value.result.kind === 'valid'
6
+ ? {source: value.source, result: {kind: 'valid', diagnostics: []}}
7
+ : {source: value.source, result: {kind: value.result.kind, diagnostics: value.result.diagnostics}};
8
+ }
9
+ import {templateSchemaBundle, decodeTemplateSource, validateTemplateSource} from './editor-schema.js';
10
+ export function createSourceEditorOptions(nowMs: () => number = Date.now): readonly SourceEditorOptions[] {
11
+ const context = () => ({consumerId: extensionConfig.id, nowMs: nowMs(), settings: null});
12
+ return [
13
+ {apiVersion: 1, extensionId: extensionConfig.id, editorId: 'template-source', opcodes: ["loadTemplate"].map(opcode => `${extensionConfig.id}_${opcode}`), bindings: [{argument: 'SOURCE', variants: [{variantId: 'template-json', format: 'json', schemaBundle: templateSchemaBundle}], decode: source => {const decoded = decodeTemplateSource(source); return {...decoded, data: decoded.data as ReturnType<SourceBinding['decode']>['data']};}, validateSource: (source, context) => checkedSource(validateTemplateSource(source, context))}], validationContext: context}
14
+ ];
15
+ }
16
+
17
+ /** Optional capability: old GUIs continue executing blocks without editor registration. */
18
+ export function registerSourceEditors(scratch: unknown, nowMs: () => number = Date.now): () => void {
19
+ const api = (scratch as {gui?: {blockEditors?: {apiVersion?: number; registerSourceEditor?: (options: SourceEditorOptions) => () => void}}})?.gui?.blockEditors;
20
+ if (api?.apiVersion !== 1 || typeof api.registerSourceEditor !== 'function') return () => {};
21
+ const removers: (() => void)[] = [];
22
+ try {
23
+ for (const options of createSourceEditorOptions(nowMs)) removers.push(api.registerSourceEditor(options));
24
+ } catch {
25
+ for (const remove of removers.reverse()) remove();
26
+ return () => {};
27
+ }
28
+ let active = true;
29
+ return () => {if (active) {active = false; for (const remove of removers.reverse()) remove();}};
30
+ }
@@ -0,0 +1,79 @@
1
+ export interface TemplateNode {
2
+ type?: string;
3
+ id?: string;
4
+ class?: string | string[];
5
+ classes?: string[];
6
+ data?: Record<string, unknown>;
7
+ attributes?: Record<string, unknown>;
8
+ children?: TemplateNode[];
9
+ }
10
+
11
+
12
+ const TEMPLATE_NODE_KEYS = new Set([
13
+ 'attributes',
14
+ 'children',
15
+ 'class',
16
+ 'classes',
17
+ 'data',
18
+ 'id',
19
+ 'type'
20
+ ]);
21
+
22
+ export function validateTemplateNode(value: unknown, path: string): asserts value is TemplateNode {
23
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
24
+ throw new TypeError(`A-Frame ${path} must be an object.`);
25
+ }
26
+ const node = value as Record<string, unknown>;
27
+ for (const key of Object.keys(node)) {
28
+ if (!TEMPLATE_NODE_KEYS.has(key)) {
29
+ throw new TypeError(`A-Frame ${path}.${key} is not supported.`);
30
+ }
31
+ }
32
+ validateOptionalString(node['type'], `${path}.type`);
33
+ validateOptionalString(node['id'], `${path}.id`);
34
+ validateTemplateClass(node['class'], `${path}.class`);
35
+ validateOptionalStringArray(node['classes'], `${path}.classes`);
36
+ validateStringRecord(node['data'], `${path}.data`);
37
+ validateStringRecord(node['attributes'], `${path}.attributes`);
38
+ const children = node['children'];
39
+ if (children === undefined) return;
40
+ if (!Array.isArray(children)) {
41
+ throw new TypeError(`A-Frame ${path}.children must be an array.`);
42
+ }
43
+ children.forEach((child, index) => {
44
+ validateTemplateNode(child, `${path}.children[${index}]`);
45
+ });
46
+ }
47
+
48
+ function validateTemplateClass(value: unknown, path: string): void {
49
+ if (value === undefined || typeof value === 'string') return;
50
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return;
51
+ throw new TypeError(`A-Frame ${path} must be a string or string array.`);
52
+ }
53
+
54
+ function validateOptionalStringArray(value: unknown, path: string): void {
55
+ if (value === undefined) return;
56
+ if (Array.isArray(value) && value.every((item) => typeof item === 'string')) return;
57
+ throw new TypeError(`A-Frame ${path} must be a string array.`);
58
+ }
59
+
60
+ function validateOptionalString(value: unknown, path: string): void {
61
+ if (value === undefined || typeof value === 'string') return;
62
+ throw new TypeError(`A-Frame ${path} must be a string.`);
63
+ }
64
+
65
+ function validateStringRecord(value: unknown, path: string): void {
66
+ if (value === undefined) return;
67
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
68
+ throw new TypeError(`A-Frame ${path} must be an object.`);
69
+ }
70
+ for (const [key, recordValue] of Object.entries(value)) {
71
+ if (key.trim().length === 0) {
72
+ throw new TypeError(`A-Frame ${path} keys must be non-empty strings.`);
73
+ }
74
+ if (recordValue === undefined) {
75
+ throw new TypeError(`A-Frame ${path}.${key} must not be undefined.`);
76
+ }
77
+ }
78
+ }
79
+
@@ -1,49 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://raw.githubusercontent.com/kubohiroya/turbowarp-aframe/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
- }