@kubohiroya/turbowarp-named-functions 0.4.2 → 0.5.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/README.ja.md CHANGED
@@ -47,7 +47,7 @@ JSONの引数を受け取りJSONの結果を返す「名前を持つ関数」を
47
47
  npm packageとして使う場合は、検証済みのversionをexact pinします。
48
48
 
49
49
  ```bash
50
- pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.4.2
50
+ pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.5.1
51
51
  ```
52
52
 
53
53
  ## クイックスタート
package/README.md CHANGED
@@ -51,7 +51,7 @@ Run `pnpm run samples:build` after source/bundle changes and `pnpm run samples:c
51
51
  ### npm package
52
52
 
53
53
  ```bash
54
- pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.4.2
54
+ pnpm add --save-exact @kubohiroya/turbowarp-named-functions@0.5.1
55
55
  ```
56
56
 
57
57
  Standalone bundle:
@@ -401,7 +401,16 @@ var block_editor_fixed_inputs_schema_default = {
401
401
  "EXPORT": {
402
402
  "type": "string",
403
403
  "enum": ["none", "tool"]
404
- }
404
+ },
405
+ "DESCRIPTION": {
406
+ "type": "string",
407
+ "maxLength": 1024
408
+ },
409
+ "SCHEMA": { "anyOf": [{
410
+ "type": "string",
411
+ "minLength": 1
412
+ }, { "type": "object" }] },
413
+ "RETURNS": { "anyOf": [{ "type": "string" }, { "type": "object" }] }
405
414
  },
406
415
  "required": ["EXPORT"],
407
416
  "additionalProperties": true
@@ -409,7 +418,7 @@ var block_editor_fixed_inputs_schema_default = {
409
418
  };
410
419
  //#endregion
411
420
  //#region src/fixed-input-schema.ts
412
- var FIXED_INPUT_CONTRACT_REVISION = "fixed-inputs-v2";
421
+ var FIXED_INPUT_CONTRACT_REVISION = "fixed-inputs-v3";
413
422
  /** The on-disk owner Schema is canonical; each bundle is its single-field projection. */
414
423
  function fixedInputSchemaBundle(argument) {
415
424
  const source = {
@@ -483,6 +492,91 @@ var choiceBinding = (argument, choices, labels) => ({
483
492
  }];
484
493
  }
485
494
  });
495
+ var literalAt = (snapshot, name) => {
496
+ const slot = snapshot.arguments[name];
497
+ return slot?.kind === "literal" ? String(slot.value) : "";
498
+ };
499
+ /** EXPORT `tool` needs a description and `all sprites`, as `readDefinition` requires. */
500
+ var exportBinding = () => {
501
+ const base = choiceBinding("EXPORT", exportChoices, {});
502
+ return {
503
+ ...base,
504
+ validateCandidate(value, context, snapshot) {
505
+ const issues = base.validateCandidate(value, context, snapshot);
506
+ if (issues.length || value !== "tool") return issues;
507
+ if (snapshot.arguments.DESCRIPTION?.kind === "literal" && literalAt(snapshot, "DESCRIPTION").trim() === "") return [{
508
+ path: "/inputs/DESCRIPTION",
509
+ message: "A function exported as a tool needs a description."
510
+ }];
511
+ return literalAt(snapshot, "SCOPE") === "sprite" ? [{
512
+ path: "/inputs/SCOPE",
513
+ message: "A function exported as a tool must be for all sprites."
514
+ }] : [];
515
+ }
516
+ };
517
+ };
518
+ var descriptionBinding = () => ({
519
+ argument: "DESCRIPTION",
520
+ schemaBundle: fixedInputSchemaBundle("DESCRIPTION"),
521
+ control: {
522
+ kind: "text",
523
+ label: "DESCRIPTION"
524
+ },
525
+ read: literalString,
526
+ encode(value) {
527
+ if (typeof value !== "string") throw new TypeError("Expected a description.");
528
+ return value;
529
+ },
530
+ validateCandidate(value) {
531
+ return typeof value === "string" && value.trim().length <= 1024 ? [] : [{
532
+ path: "/inputs/DESCRIPTION",
533
+ message: `Descriptions are at most ${MAX_DESCRIPTION_LENGTH} characters.`
534
+ }];
535
+ }
536
+ });
537
+ /**
538
+ * SCHEMA and RETURNS hold JSON Schema text or a schema name. The dialog value is the parsed object
539
+ * for JSON text and the text itself otherwise, so a string always means a name.
540
+ */
541
+ var schemaBinding = (argument, schemas) => {
542
+ const label = argument === "SCHEMA" ? "args schema" : "returns schema";
543
+ return {
544
+ argument,
545
+ schemaBundle: fixedInputSchemaBundle(argument),
546
+ control: {
547
+ kind: "json",
548
+ label: argument,
549
+ basic: "json-schema"
550
+ },
551
+ read(value) {
552
+ const text = literalString(value);
553
+ try {
554
+ const parsed = JSON.parse(text);
555
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : text;
556
+ } catch {
557
+ return text;
558
+ }
559
+ },
560
+ encode(value) {
561
+ if (typeof value === "string") return value.trim();
562
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`Unsupported ${argument}.`);
563
+ return JSON.stringify(value);
564
+ },
565
+ listNames: () => schemas.list(),
566
+ validateCandidate(value) {
567
+ if (argument === "RETURNS" && value === "") return [];
568
+ try {
569
+ parseSchema(typeof value === "string" ? value.trim() : JSON.stringify(value), label, argument === "SCHEMA", { resolveSchema: schemas.resolve });
570
+ return [];
571
+ } catch (error) {
572
+ return [{
573
+ path: `/inputs/${argument}`,
574
+ message: error instanceof Error ? error.message : String(error)
575
+ }];
576
+ }
577
+ }
578
+ };
579
+ };
486
580
  /** NAME is checked against the other hats in the scope the dialog currently selects. */
487
581
  var nameBinding = (scope, conflicts) => ({
488
582
  argument: "NAME",
@@ -511,11 +605,11 @@ var nameBinding = (scope, conflicts) => ({
511
605
  }
512
606
  });
513
607
  /**
514
- * The `define function` dialog: NAME, SCOPE, and EXPORT. NAME is validated against the scope chosen
515
- * in the dialog, so a name already used in that scope disables Save. DESCRIPTION, SCHEMA, and RETURNS
516
- * are left to the block.
608
+ * The `define function` dialog: every input in one save. NAME is validated against the scope chosen
609
+ * in the dialog, so a name already used in that scope disables Save. SCHEMA and RETURNS are edited
610
+ * by name, in a form, or as JSON text.
517
611
  */
518
- function createFixedInputEditorDefinitions(conflicts) {
612
+ function createFixedInputEditorDefinitions(conflicts, schemas) {
519
613
  return [{
520
614
  apiVersion: 1,
521
615
  extensionId: extensionConfig.id,
@@ -529,7 +623,10 @@ function createFixedInputEditorDefinitions(conflicts) {
529
623
  global: "all sprites",
530
624
  sprite: "this sprite only"
531
625
  }),
532
- choiceBinding("EXPORT", exportChoices, {})
626
+ descriptionBinding(),
627
+ schemaBinding("SCHEMA", schemas),
628
+ schemaBinding("RETURNS", schemas),
629
+ exportBinding()
533
630
  ],
534
631
  dependencies: [{
535
632
  selector: "SCOPE",
@@ -581,6 +678,146 @@ function registerFixedInputEditors(scratch, definitions, runtimeOverride) {
581
678
  }
582
679
  return dispose;
583
680
  }
681
+ //#endregion
682
+ //#region src/json-input-editors.ts
683
+ /**
684
+ * JSON editors for the inputs that hold JSON text, opened from the block's editor icon.
685
+ *
686
+ * `define function` is not here: the editor registry allows one editor per opcode, and that block
687
+ * already has the fixed-input editor for EXPORT.
688
+ */
689
+ var PROMISE_REF_SCHEMA = {
690
+ type: "object",
691
+ properties: { $promise: {
692
+ type: "string",
693
+ pattern: "^p_[0-9]+$"
694
+ } },
695
+ required: ["$promise"],
696
+ additionalProperties: false
697
+ };
698
+ var SCHEMAS = {
699
+ args: { type: "object" },
700
+ promise: PROMISE_REF_SCHEMA,
701
+ promises: {
702
+ type: "array",
703
+ items: PROMISE_REF_SCHEMA
704
+ }
705
+ };
706
+ function bundle(key) {
707
+ const source = {
708
+ repository: "turbowarp-named-functions",
709
+ path: "src/json-input-editors.ts",
710
+ symbol: `SCHEMAS.${key}`
711
+ };
712
+ return {
713
+ identity: {
714
+ ownerId: "turbowarp-named-functions",
715
+ contractId: `json-input.${key}`,
716
+ revision: "json-inputs-v1",
717
+ variantId: "default"
718
+ },
719
+ dialect: "2020-12",
720
+ root: {
721
+ retrievalUri: `https://kubohiroya.github.io/turbowarp-named-functions/schemas/json-input-${key}.schema.json`,
722
+ document: SCHEMAS[key],
723
+ artifact: {
724
+ role: "canonical-schema",
725
+ source
726
+ }
727
+ },
728
+ resources: [],
729
+ provenance: {
730
+ canonicalSources: [source],
731
+ generatedFiles: [],
732
+ referenceSchemas: [],
733
+ generationSources: []
734
+ }
735
+ };
736
+ }
737
+ /** Checks call arguments against the schema of the function named by the block's NAME (or FUNCTION) literal. */
738
+ function validateCallArguments(data, snapshot, functions) {
739
+ const input = snapshot.arguments.FUNCTION ? "FUNCTION" : "NAME";
740
+ const slot = snapshot.arguments[input];
741
+ if (!slot || slot.kind !== "literal") return [];
742
+ const name = String(slot.value).trim();
743
+ const definition = functions(snapshot.targetId).find((candidate) => candidate.name === name);
744
+ if (!definition) return [{
745
+ path: `/inputs/${input}`,
746
+ message: `Unknown function: ${name}`
747
+ }];
748
+ return validateAgainstSchema(data, definition.parameters).map((message) => ({
749
+ path: "/inputs/ARGS",
750
+ message
751
+ }));
752
+ }
753
+ function jsonInputEditorDefinitions(functions) {
754
+ const common = {
755
+ apiVersion: 1,
756
+ extensionId: extensionConfig.id,
757
+ format: "json",
758
+ validationContext: () => ({
759
+ consumerId: extensionConfig.id,
760
+ nowMs: Date.now(),
761
+ settings: null
762
+ })
763
+ };
764
+ const id = (opcode) => `${extensionConfig.id}_${opcode}`;
765
+ return [
766
+ {
767
+ ...common,
768
+ editorId: "call-arguments",
769
+ opcodes: [
770
+ id("callFunction"),
771
+ id("callFunctionFromMenu"),
772
+ id("startFunction")
773
+ ],
774
+ argument: "ARGS",
775
+ schemaBundle: bundle("args"),
776
+ validateData: (data, snapshot) => validateCallArguments(data, snapshot, functions)
777
+ },
778
+ {
779
+ ...common,
780
+ editorId: "promise-reference",
781
+ opcodes: [id("awaitResult"), id("isSettled")],
782
+ argument: "PROMISE",
783
+ schemaBundle: bundle("promise")
784
+ },
785
+ {
786
+ ...common,
787
+ editorId: "promise-references",
788
+ opcodes: [id("awaitAll")],
789
+ argument: "PROMISES",
790
+ schemaBundle: bundle("promises")
791
+ }
792
+ ];
793
+ }
794
+ /** Registers the editors when the GUI offers schema bundle editors; otherwise does nothing. */
795
+ function registerJsonInputEditors(scratch, definitions, runtimeOverride) {
796
+ const host = scratch;
797
+ const api = host.gui?.blockEditors;
798
+ if (!definitions.length || api?.apiVersion !== 1 || typeof api.registerSchemaBundle !== "function") return () => {};
799
+ const runtime = runtimeOverride ?? host.vm?.runtime;
800
+ const removers = [];
801
+ let active = true;
802
+ const dispose = () => {
803
+ if (!active) return;
804
+ active = false;
805
+ runtime?.off?.("RUNTIME_DISPOSED", dispose);
806
+ for (const remove of removers.splice(0).reverse()) remove();
807
+ };
808
+ try {
809
+ for (const definition of definitions) {
810
+ const remove = api.registerSchemaBundle.call(api, definition);
811
+ if (typeof remove !== "function") throw new TypeError("Invalid JSON input editor registration disposer.");
812
+ removers.push(remove);
813
+ }
814
+ runtime?.on?.("RUNTIME_DISPOSED", dispose);
815
+ } catch (error) {
816
+ dispose();
817
+ throw error;
818
+ }
819
+ return dispose;
820
+ }
584
821
  var block_definitions_default = {
585
822
  extensionName: "Named Functions",
586
823
  blocks: [
@@ -1833,16 +2070,32 @@ var NamedFunctionsExtension = class {
1833
2070
  lastError() {
1834
2071
  return this.lastErrorMessage;
1835
2072
  }
2073
+ /** Registers every data editor; the returned function removes them all. */
1836
2074
  registerEditors() {
1837
- return registerFixedInputEditors(typeof Scratch === "undefined" ? {} : Scratch, createFixedInputEditorDefinitions((where, name, scope) => {
1838
- const target = this.runtime.getTargetById?.(where.targetId);
1839
- return target !== void 0 && hasNameConflict(this.runtime.targets, DEFINE_FUNCTION_OPCODE, {
1840
- target,
1841
- blockId: where.blockId,
1842
- name,
1843
- scope
1844
- });
1845
- }), this.runtime);
2075
+ const scratch = typeof Scratch === "undefined" ? {} : Scratch;
2076
+ const removers = [];
2077
+ const unregister = () => {
2078
+ for (const remove of removers.splice(0).reverse()) remove();
2079
+ };
2080
+ try {
2081
+ removers.push(registerFixedInputEditors(scratch, createFixedInputEditorDefinitions((where, name, scope) => {
2082
+ const target = this.runtime.getTargetById?.(where.targetId);
2083
+ return target !== void 0 && hasNameConflict(this.runtime.targets, DEFINE_FUNCTION_OPCODE, {
2084
+ target,
2085
+ blockId: where.blockId,
2086
+ name,
2087
+ scope
2088
+ });
2089
+ }, {
2090
+ list: () => schemaNames(this.functions.schemas().schemas),
2091
+ resolve: (reference, label) => resolveSchemaReference(this.functions.schemas().schemas, reference, label)
2092
+ }), this.runtime));
2093
+ removers.push(registerJsonInputEditors(scratch, jsonInputEditorDefinitions((targetId) => this.functions.visible(this.runtime.getTargetById?.(targetId))), this.runtime));
2094
+ } catch (error) {
2095
+ unregister();
2096
+ throw error;
2097
+ }
2098
+ return unregister;
1846
2099
  }
1847
2100
  callByName(nameArg, argsArg, util) {
1848
2101
  const succeed = (result) => {
@@ -1887,6 +2140,13 @@ var NamedFunctionsExtension = class {
1887
2140
  return scratchBlock;
1888
2141
  }
1889
2142
  };
2143
+ /** `Name`, or `Name@version` for every version of a name defined more than once. */
2144
+ function schemaNames(schemas) {
2145
+ const counts = /* @__PURE__ */ new Map();
2146
+ for (const schema of schemas) counts.set(schema.name, (counts.get(schema.name) ?? 0) + 1);
2147
+ const names = schemas.map((schema) => counts.get(schema.name) > 1 ? `${schema.name}@${schema.version}` : schema.name);
2148
+ return [...new Set(names)].sort();
2149
+ }
1890
2150
  /** ARGS text: empty means `{}`; otherwise it must be JSON. */
1891
2151
  function parseArguments(text) {
1892
2152
  if (text.trim().length === 0) return {};
@@ -62,6 +62,7 @@ export declare class NamedFunctionsExtension implements TurboWarpExtension {
62
62
  isSettled(args: Args): boolean;
63
63
  isDefined(args: Args, util?: Util): boolean;
64
64
  lastError(): string;
65
+ /** Registers every data editor; the returned function removes them all. */
65
66
  private registerEditors;
66
67
  private callByName;
67
68
  private guard;
@@ -1,16 +1,23 @@
1
1
  import type { FixedInputEditorOptions } from '@kubohiroya/turbowarp-extension-data-editor';
2
2
  import { type FunctionScope } from './function-registry.js';
3
+ /** The `define schema` hats a SCHEMA or RETURNS input can name. */
4
+ export interface SchemaNames {
5
+ /** `Name`, or `Name@1.0.0` for each version when a name has several. */
6
+ list(): readonly string[];
7
+ /** Resolves a name the way a running project does; throws when it cannot. */
8
+ resolve(reference: string, label: string): Record<string, unknown>;
9
+ }
3
10
  /** Reports whether another `define function` hat already uses `name` within `scope`. */
4
11
  export type NameConflictCheck = (where: {
5
12
  targetId: string;
6
13
  blockId: string;
7
14
  }, name: string, scope: FunctionScope) => boolean;
8
15
  /**
9
- * The `define function` dialog: NAME, SCOPE, and EXPORT. NAME is validated against the scope chosen
10
- * in the dialog, so a name already used in that scope disables Save. DESCRIPTION, SCHEMA, and RETURNS
11
- * are left to the block.
16
+ * The `define function` dialog: every input in one save. NAME is validated against the scope chosen
17
+ * in the dialog, so a name already used in that scope disables Save. SCHEMA and RETURNS are edited
18
+ * by name, in a form, or as JSON text.
12
19
  */
13
- export declare function createFixedInputEditorDefinitions(conflicts: NameConflictCheck): readonly FixedInputEditorOptions[];
20
+ export declare function createFixedInputEditorDefinitions(conflicts: NameConflictCheck, schemas: SchemaNames): readonly FixedInputEditorOptions[];
14
21
  interface RuntimeLifetime {
15
22
  on?: (event: string, listener: () => void) => void;
16
23
  off?: (event: string, listener: () => void) => void;
@@ -1,6 +1,6 @@
1
1
  import type { SchemaBundle } from '@kubohiroya/turbowarp-extension-data-editor/schema';
2
2
  /** The `define function` inputs the fixed-input editor changes. */
3
- export type FixedInputArgument = 'NAME' | 'SCOPE' | 'EXPORT';
4
- export declare const FIXED_INPUT_CONTRACT_REVISION = "fixed-inputs-v2";
3
+ export type FixedInputArgument = 'NAME' | 'SCOPE' | 'EXPORT' | 'DESCRIPTION' | 'SCHEMA' | 'RETURNS';
4
+ export declare const FIXED_INPUT_CONTRACT_REVISION = "fixed-inputs-v3";
5
5
  /** The on-disk owner Schema is canonical; each bundle is its single-field projection. */
6
6
  export declare function fixedInputSchemaBundle(argument: FixedInputArgument): SchemaBundle;
@@ -78,3 +78,9 @@ export declare function resolveFunction(functions: readonly FunctionDefinition[]
78
78
  /** Functions a script of `caller` can call: its sprite's own functions, then the global ones. */
79
79
  export declare function visibleFunctions(functions: readonly FunctionDefinition[], caller?: RuntimeTarget): FunctionDefinition[];
80
80
  export declare function toFunctionTools(functions: readonly FunctionDefinition[]): FunctionTool[];
81
+ /**
82
+ * SCHEMA and RETURNS hold either JSON Schema text or, when the consumer supports it, the name of a
83
+ * `define schema` hat. Text that is not JSON is treated as a name, so existing JSON projects are
84
+ * unaffected.
85
+ */
86
+ export declare function parseSchema(text: string, label: string, requireObjectType: boolean, options: FunctionScanOptions): Record<string, unknown>;
@@ -0,0 +1,15 @@
1
+ import type { SchemaBundleEditorOptions } from '@kubohiroya/turbowarp-extension-data-editor/rjsf';
2
+ import type { BlockSnapshot, JsonValue, ValidationIssue } from '@kubohiroya/turbowarp-extension-data-editor';
3
+ import type { FunctionDefinition } from './function-registry.js';
4
+ /** Lists the functions the sprite with this id can call. */
5
+ export type FunctionLookup = (targetId: string) => readonly FunctionDefinition[];
6
+ /** Checks call arguments against the schema of the function named by the block's NAME (or FUNCTION) literal. */
7
+ export declare function validateCallArguments(data: JsonValue, snapshot: BlockSnapshot, functions: FunctionLookup): ValidationIssue[];
8
+ export declare function jsonInputEditorDefinitions(functions: FunctionLookup): SchemaBundleEditorOptions[];
9
+ interface RuntimeLifetime {
10
+ on?: (event: string, listener: () => void) => void;
11
+ off?: (event: string, listener: () => void) => void;
12
+ }
13
+ /** Registers the editors when the GUI offers schema bundle editors; otherwise does nothing. */
14
+ export declare function registerJsonInputEditors(scratch: unknown, definitions: readonly SchemaBundleEditorOptions[], runtimeOverride?: RuntimeLifetime): () => void;
15
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-named-functions",
3
- "version": "0.4.2",
3
+ "version": "0.5.1",
4
4
  "description": "Named, JSON-in/JSON-out functions for TurboWarp that can be called by name, synchronously or asynchronously, and exported as tools.",
5
5
  "author": {
6
6
  "name": "Hiroya Kubo",
@@ -65,16 +65,18 @@
65
65
  },
66
66
  "devDependencies": {
67
67
  "@eslint/js": "^9.39.5",
68
+ "@kubohiroya/turbowarp-extension-data-editor": "^0.11.0",
68
69
  "@kubohiroya/turbowarp-extension-manifest": "^0.5.0",
69
70
  "@kubohiroya/vite-plugin-turbowarp-extension": "^0.11.0",
70
71
  "@types/node": "^24.13.3",
71
72
  "eslint": "^9.39.5",
72
73
  "jiti": "^2.7.0",
74
+ "react": "18.3.1",
75
+ "react-dom": "18.3.1",
73
76
  "typescript": "^5.9.3",
74
77
  "typescript-eslint": "^8.66.0",
75
78
  "vite": "^8.2.2",
76
- "vitest": "^5.0.0",
77
- "@kubohiroya/turbowarp-extension-data-editor": "^0.9.0"
79
+ "vitest": "^5.0.0"
78
80
  },
79
81
  "exports": {
80
82
  "./composition": {
@@ -83,5 +85,11 @@
83
85
  },
84
86
  "./turbowarp-named-functions.js": "./dist/turbowarp-named-functions.js",
85
87
  "./package.json": "./package.json"
88
+ },
89
+ "turbowarpExtension": {
90
+ "resourceDeclaration": {
91
+ "schemaVersion": 1,
92
+ "resources": []
93
+ }
86
94
  }
87
95
  }
@@ -22,6 +22,31 @@
22
22
  "none",
23
23
  "tool"
24
24
  ]
25
+ },
26
+ "DESCRIPTION": {
27
+ "type": "string",
28
+ "maxLength": 1024
29
+ },
30
+ "SCHEMA": {
31
+ "anyOf": [
32
+ {
33
+ "type": "string",
34
+ "minLength": 1
35
+ },
36
+ {
37
+ "type": "object"
38
+ }
39
+ ]
40
+ },
41
+ "RETURNS": {
42
+ "anyOf": [
43
+ {
44
+ "type": "string"
45
+ },
46
+ {
47
+ "type": "object"
48
+ }
49
+ ]
25
50
  }
26
51
  },
27
52
  "required": [
package/src/extension.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {createFixedInputEditorDefinitions, registerFixedInputEditors} from './fixed-input-editors.js';
2
2
  import {hasNameConflict} from './function-registry.js';
3
+ import {jsonInputEditorDefinitions, registerJsonInputEditors} from './json-input-editors.js';
3
4
  import {extensionConfig} from './config';
4
5
  import definitions from './block-definitions.json';
5
6
  import {
@@ -281,16 +282,37 @@ export class NamedFunctionsExtension implements TurboWarpExtension {
281
282
 
282
283
  // ---- internals ----------------------------------------------------------------------------
283
284
 
285
+ /** Registers every data editor; the returned function removes them all. */
284
286
  private registerEditors(): () => void {
285
- return registerFixedInputEditors(
286
- typeof Scratch === 'undefined' ? {} : Scratch,
287
- createFixedInputEditorDefinitions((where, name, scope) => {
288
- const target = this.runtime.getTargetById?.(where.targetId);
289
- return target !== undefined &&
290
- hasNameConflict(this.runtime.targets, DEFINE_FUNCTION_OPCODE, {target, blockId: where.blockId, name, scope});
291
- }),
292
- this.runtime
293
- );
287
+ const scratch = typeof Scratch === 'undefined' ? {} : Scratch;
288
+ const removers: (() => void)[] = [];
289
+ const unregister = () => {
290
+ for (const remove of removers.splice(0).reverse()) remove();
291
+ };
292
+ try {
293
+ removers.push(registerFixedInputEditors(
294
+ scratch,
295
+ createFixedInputEditorDefinitions((where, name, scope) => {
296
+ const target = this.runtime.getTargetById?.(where.targetId);
297
+ return target !== undefined &&
298
+ hasNameConflict(this.runtime.targets, DEFINE_FUNCTION_OPCODE, {target, blockId: where.blockId, name, scope});
299
+ }, {
300
+ list: () => schemaNames(this.functions.schemas().schemas),
301
+ resolve: (reference, label) => resolveSchemaReference(this.functions.schemas().schemas, reference, label)
302
+ }),
303
+ this.runtime
304
+ ));
305
+ // Called only while a dialog is open, after the constructor has created the functions.
306
+ removers.push(registerJsonInputEditors(
307
+ scratch,
308
+ jsonInputEditorDefinitions((targetId) => this.functions.visible(this.runtime.getTargetById?.(targetId))),
309
+ this.runtime
310
+ ));
311
+ } catch (error) {
312
+ unregister();
313
+ throw error;
314
+ }
315
+ return unregister;
294
316
  }
295
317
 
296
318
  private callByName(
@@ -352,6 +374,14 @@ export class NamedFunctionsExtension implements TurboWarpExtension {
352
374
  }
353
375
  }
354
376
 
377
+ /** `Name`, or `Name@version` for every version of a name defined more than once. */
378
+ function schemaNames(schemas: readonly {name: string; version: string}[]): string[] {
379
+ const counts = new Map<string, number>();
380
+ for (const schema of schemas) counts.set(schema.name, (counts.get(schema.name) ?? 0) + 1);
381
+ const names = schemas.map((schema) => counts.get(schema.name)! > 1 ? `${schema.name}@${schema.version}` : schema.name);
382
+ return [...new Set(names)].sort();
383
+ }
384
+
355
385
  /** ARGS text: empty means `{}`; otherwise it must be JSON. */
356
386
  function parseArguments(text: string): unknown {
357
387
  if (text.trim().length === 0) return {};
@@ -1,11 +1,19 @@
1
1
  import type {FixedInputBinding, FixedInputEditorOptions} from '@kubohiroya/turbowarp-extension-data-editor';
2
2
  import {extensionConfig} from './config.js';
3
- import {FUNCTION_NAME_PATTERN, type FunctionScope} from './function-registry.js';
3
+ import {FUNCTION_NAME_PATTERN, MAX_DESCRIPTION_LENGTH, parseSchema, type FunctionScope} from './function-registry.js';
4
4
  import {FIXED_INPUT_CONTRACT_REVISION, fixedInputSchemaBundle} from './fixed-input-schema.js';
5
5
 
6
6
  const exportChoices: readonly string[] = ['none', 'tool'];
7
7
  const scopeChoices: readonly string[] = ['global', 'sprite'];
8
8
 
9
+ /** The `define schema` hats a SCHEMA or RETURNS input can name. */
10
+ export interface SchemaNames {
11
+ /** `Name`, or `Name@1.0.0` for each version when a name has several. */
12
+ list(): readonly string[];
13
+ /** Resolves a name the way a running project does; throws when it cannot. */
14
+ resolve(reference: string, label: string): Record<string, unknown>;
15
+ }
16
+
9
17
  /** Reports whether another `define function` hat already uses `name` within `scope`. */
10
18
  export type NameConflictCheck = (where: {targetId: string; blockId: string}, name: string, scope: FunctionScope) => boolean;
11
19
 
@@ -29,6 +37,76 @@ const choiceBinding = (argument: 'SCOPE' | 'EXPORT', choices: readonly string[],
29
37
  }
30
38
  });
31
39
 
40
+ const literalAt = (snapshot: {arguments: Readonly<Record<string, {kind: string; value?: unknown}>>}, name: string): string => {
41
+ const slot = snapshot.arguments[name];
42
+ return slot?.kind === 'literal' ? String(slot.value) : '';
43
+ };
44
+
45
+ /** EXPORT `tool` needs a description and `all sprites`, as `readDefinition` requires. */
46
+ const exportBinding = (): FixedInputBinding => {
47
+ const base = choiceBinding('EXPORT', exportChoices, {});
48
+ return {...base, validateCandidate(value, context, snapshot) {
49
+ const issues = base.validateCandidate!(value, context, snapshot);
50
+ if (issues.length || value !== 'tool') return issues;
51
+ if (snapshot.arguments.DESCRIPTION?.kind === 'literal' && literalAt(snapshot, 'DESCRIPTION').trim() === '') {
52
+ return [{path: '/inputs/DESCRIPTION', message: 'A function exported as a tool needs a description.'}];
53
+ }
54
+ return literalAt(snapshot, 'SCOPE') === 'sprite'
55
+ ? [{path: '/inputs/SCOPE', message: 'A function exported as a tool must be for all sprites.'}] : [];
56
+ }};
57
+ };
58
+
59
+ const descriptionBinding = (): FixedInputBinding => ({
60
+ argument: 'DESCRIPTION', schemaBundle: fixedInputSchemaBundle('DESCRIPTION'),
61
+ control: {kind: 'text', label: 'DESCRIPTION'},
62
+ read: literalString,
63
+ encode(value) {
64
+ if (typeof value !== 'string') throw new TypeError('Expected a description.');
65
+ return value;
66
+ },
67
+ validateCandidate(value) {
68
+ return typeof value === 'string' && value.trim().length <= MAX_DESCRIPTION_LENGTH ? []
69
+ : [{path: '/inputs/DESCRIPTION', message: `Descriptions are at most ${MAX_DESCRIPTION_LENGTH} characters.`}];
70
+ }
71
+ });
72
+
73
+ /**
74
+ * SCHEMA and RETURNS hold JSON Schema text or a schema name. The dialog value is the parsed object
75
+ * for JSON text and the text itself otherwise, so a string always means a name.
76
+ */
77
+ const schemaBinding = (argument: 'SCHEMA' | 'RETURNS', schemas: SchemaNames): FixedInputBinding => {
78
+ const label = argument === 'SCHEMA' ? 'args schema' : 'returns schema';
79
+ return {
80
+ argument, schemaBundle: fixedInputSchemaBundle(argument),
81
+ control: {kind: 'json', label: argument, basic: 'json-schema'},
82
+ read(value) {
83
+ const text = literalString(value);
84
+ try {
85
+ const parsed = JSON.parse(text) as unknown;
86
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as never : text;
87
+ } catch {
88
+ return text;
89
+ }
90
+ },
91
+ encode(value) {
92
+ if (typeof value === 'string') return value.trim();
93
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new TypeError(`Unsupported ${argument}.`);
94
+ return JSON.stringify(value);
95
+ },
96
+ listNames: () => schemas.list(),
97
+ validateCandidate(value) {
98
+ if (argument === 'RETURNS' && value === '') return [];
99
+ try {
100
+ parseSchema(typeof value === 'string' ? value.trim() : JSON.stringify(value), label, argument === 'SCHEMA',
101
+ {resolveSchema: schemas.resolve});
102
+ return [];
103
+ } catch (error) {
104
+ return [{path: `/inputs/${argument}`, message: error instanceof Error ? error.message : String(error)}];
105
+ }
106
+ }
107
+ };
108
+ };
109
+
32
110
  /** NAME is checked against the other hats in the scope the dialog currently selects. */
33
111
  const nameBinding = (scope: FunctionScope, conflicts: NameConflictCheck): FixedInputBinding => ({
34
112
  argument: 'NAME', schemaBundle: fixedInputSchemaBundle('NAME'),
@@ -49,11 +127,13 @@ const nameBinding = (scope: FunctionScope, conflicts: NameConflictCheck): FixedI
49
127
  });
50
128
 
51
129
  /**
52
- * The `define function` dialog: NAME, SCOPE, and EXPORT. NAME is validated against the scope chosen
53
- * in the dialog, so a name already used in that scope disables Save. DESCRIPTION, SCHEMA, and RETURNS
54
- * are left to the block.
130
+ * The `define function` dialog: every input in one save. NAME is validated against the scope chosen
131
+ * in the dialog, so a name already used in that scope disables Save. SCHEMA and RETURNS are edited
132
+ * by name, in a form, or as JSON text.
55
133
  */
56
- export function createFixedInputEditorDefinitions(conflicts: NameConflictCheck): readonly FixedInputEditorOptions[] {
134
+ export function createFixedInputEditorDefinitions(
135
+ conflicts: NameConflictCheck, schemas: SchemaNames
136
+ ): readonly FixedInputEditorOptions[] {
57
137
  return [{
58
138
  apiVersion: 1, extensionId: extensionConfig.id, editorId: 'defineFunction-fixed-inputs',
59
139
  opcodes: [`${extensionConfig.id}_defineFunction`],
@@ -61,7 +141,10 @@ export function createFixedInputEditorDefinitions(conflicts: NameConflictCheck):
61
141
  bindings: [
62
142
  nameBinding('global', conflicts),
63
143
  choiceBinding('SCOPE', scopeChoices, {global: 'all sprites', sprite: 'this sprite only'}),
64
- choiceBinding('EXPORT', exportChoices, {})
144
+ descriptionBinding(),
145
+ schemaBinding('SCHEMA', schemas),
146
+ schemaBinding('RETURNS', schemas),
147
+ exportBinding()
65
148
  ],
66
149
  dependencies: [{selector: 'SCOPE', dependents: ['NAME']}],
67
150
  branchPolicies: [{
@@ -2,9 +2,9 @@ import type {SchemaBundle} from '@kubohiroya/turbowarp-extension-data-editor/sch
2
2
  import document from '../schemas/block-editor-fixed-inputs.schema.json';
3
3
 
4
4
  /** The `define function` inputs the fixed-input editor changes. */
5
- export type FixedInputArgument = 'NAME' | 'SCOPE' | 'EXPORT';
5
+ export type FixedInputArgument = 'NAME' | 'SCOPE' | 'EXPORT' | 'DESCRIPTION' | 'SCHEMA' | 'RETURNS';
6
6
 
7
- export const FIXED_INPUT_CONTRACT_REVISION = 'fixed-inputs-v2';
7
+ export const FIXED_INPUT_CONTRACT_REVISION = 'fixed-inputs-v3';
8
8
 
9
9
  /** The on-disk owner Schema is canonical; each bundle is its single-field projection. */
10
10
  export function fixedInputSchemaBundle(argument: FixedInputArgument): SchemaBundle {
@@ -273,7 +273,7 @@ function readScope(block: SerializedBlock): FunctionScope {
273
273
  * `define schema` hat. Text that is not JSON is treated as a name, so existing JSON projects are
274
274
  * unaffected.
275
275
  */
276
- function parseSchema(
276
+ export function parseSchema(
277
277
  text: string,
278
278
  label: string,
279
279
  requireObjectType: boolean,
@@ -0,0 +1,116 @@
1
+ import type {SchemaBundleEditorOptions} from '@kubohiroya/turbowarp-extension-data-editor/rjsf';
2
+ import type {SchemaBundle, SchemaJsonObject} from '@kubohiroya/turbowarp-extension-data-editor/schema';
3
+ import type {BlockSnapshot, JsonValue, ValidationIssue} from '@kubohiroya/turbowarp-extension-data-editor';
4
+ import {extensionConfig} from './config.js';
5
+ import type {FunctionDefinition} from './function-registry.js';
6
+ import {validateAgainstSchema} from './schema-validator.js';
7
+
8
+ /**
9
+ * JSON editors for the inputs that hold JSON text, opened from the block's editor icon.
10
+ *
11
+ * `define function` is not here: the editor registry allows one editor per opcode, and that block
12
+ * already has the fixed-input editor for EXPORT.
13
+ */
14
+
15
+ const PROMISE_REF_SCHEMA: SchemaJsonObject = {
16
+ type: 'object',
17
+ properties: {$promise: {type: 'string', pattern: '^p_[0-9]+$'}},
18
+ required: ['$promise'],
19
+ additionalProperties: false
20
+ };
21
+
22
+ const SCHEMAS = {
23
+ args: {type: 'object'},
24
+ promise: PROMISE_REF_SCHEMA,
25
+ promises: {type: 'array', items: PROMISE_REF_SCHEMA}
26
+ } satisfies Record<string, SchemaJsonObject>;
27
+
28
+ type SchemaKey = keyof typeof SCHEMAS;
29
+
30
+ function bundle(key: SchemaKey): SchemaBundle {
31
+ const source = {repository: 'turbowarp-named-functions', path: 'src/json-input-editors.ts', symbol: `SCHEMAS.${key}`};
32
+ return {
33
+ identity: {ownerId: 'turbowarp-named-functions', contractId: `json-input.${key}`, revision: 'json-inputs-v1', variantId: 'default'},
34
+ dialect: '2020-12',
35
+ root: {
36
+ retrievalUri: `https://kubohiroya.github.io/turbowarp-named-functions/schemas/json-input-${key}.schema.json`,
37
+ document: SCHEMAS[key],
38
+ artifact: {role: 'canonical-schema', source}
39
+ },
40
+ resources: [],
41
+ provenance: {canonicalSources: [source], generatedFiles: [], referenceSchemas: [], generationSources: []}
42
+ };
43
+ }
44
+
45
+ /** Lists the functions the sprite with this id can call. */
46
+ export type FunctionLookup = (targetId: string) => readonly FunctionDefinition[];
47
+
48
+ /** Checks call arguments against the schema of the function named by the block's NAME (or FUNCTION) literal. */
49
+ export function validateCallArguments(
50
+ data: JsonValue, snapshot: BlockSnapshot, functions: FunctionLookup
51
+ ): ValidationIssue[] {
52
+ const input = snapshot.arguments.FUNCTION ? 'FUNCTION' : 'NAME';
53
+ const slot = snapshot.arguments[input];
54
+ // A reporter in NAME is only known at run time.
55
+ if (!slot || slot.kind !== 'literal') return [];
56
+ const name = String(slot.value).trim();
57
+ const definition = functions(snapshot.targetId).find((candidate) => candidate.name === name);
58
+ if (!definition) return [{path: `/inputs/${input}`, message: `Unknown function: ${name}`}];
59
+ return validateAgainstSchema(data, definition.parameters).map((message) => ({path: '/inputs/ARGS', message}));
60
+ }
61
+
62
+ export function jsonInputEditorDefinitions(functions: FunctionLookup): SchemaBundleEditorOptions[] {
63
+ const common = {
64
+ apiVersion: 1 as const,
65
+ extensionId: extensionConfig.id,
66
+ format: 'json' as const,
67
+ validationContext: () => ({consumerId: extensionConfig.id, nowMs: Date.now(), settings: null})
68
+ };
69
+ const id = (opcode: string) => `${extensionConfig.id}_${opcode}`;
70
+ return [
71
+ {
72
+ ...common,
73
+ editorId: 'call-arguments',
74
+ opcodes: [id('callFunction'), id('callFunctionFromMenu'), id('startFunction')],
75
+ argument: 'ARGS',
76
+ schemaBundle: bundle('args'),
77
+ validateData: (data, snapshot) => validateCallArguments(data, snapshot, functions)
78
+ },
79
+ {...common, editorId: 'promise-reference', opcodes: [id('awaitResult'), id('isSettled')], argument: 'PROMISE', schemaBundle: bundle('promise')},
80
+ {...common, editorId: 'promise-references', opcodes: [id('awaitAll')], argument: 'PROMISES', schemaBundle: bundle('promises')}
81
+ ];
82
+ }
83
+
84
+ interface RuntimeLifetime {
85
+ on?: (event: string, listener: () => void) => void;
86
+ off?: (event: string, listener: () => void) => void;
87
+ }
88
+
89
+ /** Registers the editors when the GUI offers schema bundle editors; otherwise does nothing. */
90
+ export function registerJsonInputEditors(
91
+ scratch: unknown, definitions: readonly SchemaBundleEditorOptions[], runtimeOverride?: RuntimeLifetime
92
+ ): () => void {
93
+ const host = scratch as {gui?: {blockEditors?: {apiVersion?: number;
94
+ registerSchemaBundle?: (options: SchemaBundleEditorOptions) => () => void}};
95
+ vm?: {runtime?: RuntimeLifetime}};
96
+ const api = host.gui?.blockEditors;
97
+ if (!definitions.length || api?.apiVersion !== 1 || typeof api.registerSchemaBundle !== 'function') return () => {};
98
+ const runtime = runtimeOverride ?? host.vm?.runtime;
99
+ const removers: (() => void)[] = [];
100
+ let active = true;
101
+ const dispose = () => {
102
+ if (!active) return;
103
+ active = false;
104
+ runtime?.off?.('RUNTIME_DISPOSED', dispose);
105
+ for (const remove of removers.splice(0).reverse()) remove();
106
+ };
107
+ try {
108
+ for (const definition of definitions) {
109
+ const remove = api.registerSchemaBundle.call(api, definition);
110
+ if (typeof remove !== 'function') throw new TypeError('Invalid JSON input editor registration disposer.');
111
+ removers.push(remove);
112
+ }
113
+ runtime?.on?.('RUNTIME_DISPOSED', dispose);
114
+ } catch (error) {dispose(); throw error;}
115
+ return dispose;
116
+ }