@kubohiroya/turbowarp-named-functions 0.1.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/LICENSE +373 -0
- package/README.ja.md +209 -0
- package/README.md +258 -0
- package/dist/composition.js +398 -0
- package/dist/extension-manifest.json +133 -0
- package/dist/turbowarp-named-functions.js +701 -0
- package/dist/types/composition.d.ts +49 -0
- package/dist/types/config.d.ts +11 -0
- package/dist/types/extension-manifest.d.ts +30 -0
- package/dist/types/extension.d.ts +29 -0
- package/dist/types/function-dispatcher.d.ts +60 -0
- package/dist/types/function-registry.d.ts +28 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/runtime-types.d.ts +37 -0
- package/dist/types/schema-validator.d.ts +9 -0
- package/package.json +75 -0
- package/schemas/extension-manifest.schema.json +49 -0
- package/src/block-definitions.json +168 -0
- package/src/composition.ts +220 -0
- package/src/config.ts +12 -0
- package/src/extension-manifest.ts +149 -0
- package/src/extension.ts +200 -0
- package/src/function-dispatcher.ts +208 -0
- package/src/function-registry.ts +124 -0
- package/src/globals.d.ts +26 -0
- package/src/index.ts +14 -0
- package/src/runtime-types.ts +42 -0
- package/src/schema-validator.ts +101 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import type {RuntimeLike, RuntimeThread} from './runtime-types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Runs `define function` hats as named functions.
|
|
5
|
+
*
|
|
6
|
+
* A call starts every `define function` hat; the hat predicate lets only the script whose NAME
|
|
7
|
+
* matches the invocation being started continue, and binds that thread to the invocation. Extension
|
|
8
|
+
* hats are not restarted while running, so calls to the same name are queued and run one at a time.
|
|
9
|
+
*
|
|
10
|
+
* The next invocation is started only between steps (or directly from outside a step). Inside a step,
|
|
11
|
+
* the hats that failed their predicate and the script that just returned still count as running
|
|
12
|
+
* threads, so starting hats there would silently skip them.
|
|
13
|
+
*
|
|
14
|
+
* Each invocation records the chain of function names that led to it. Calling a name that is already
|
|
15
|
+
* in the chain would wait for itself in the per-name queue, so it fails immediately as reentrant.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export interface FunctionDispatcherOptions {
|
|
19
|
+
hatOpcode: string;
|
|
20
|
+
/** Names that have a `define function` hat. Used to fail fast on unknown names. */
|
|
21
|
+
knownNames: () => ReadonlySet<string>;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
setTimer?: (callback: () => void, ms: number) => unknown;
|
|
24
|
+
clearTimer?: (handle: unknown) => void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface Invocation {
|
|
28
|
+
name: string;
|
|
29
|
+
args: unknown;
|
|
30
|
+
chain: readonly string[];
|
|
31
|
+
resolve: (value: unknown) => void;
|
|
32
|
+
reject: (error: Error) => void;
|
|
33
|
+
thread: RuntimeThread | null;
|
|
34
|
+
startedAtStep: number;
|
|
35
|
+
timer: unknown;
|
|
36
|
+
settled: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const DEFAULT_FUNCTION_TIMEOUT_MS = 30_000;
|
|
40
|
+
|
|
41
|
+
export class FunctionDispatcher {
|
|
42
|
+
private readonly queue: Invocation[] = [];
|
|
43
|
+
private readonly running = new Map<string, Invocation>();
|
|
44
|
+
private readonly byThread = new Map<RuntimeThread, Invocation>();
|
|
45
|
+
private starting: Invocation | null = null;
|
|
46
|
+
private step = 0;
|
|
47
|
+
private readonly timeoutMs: number;
|
|
48
|
+
private readonly setTimer: (callback: () => void, ms: number) => unknown;
|
|
49
|
+
private readonly clearTimer: (handle: unknown) => void;
|
|
50
|
+
private readonly onAfterExecute = () => this.afterStep();
|
|
51
|
+
private readonly onStopAll = () => this.cancelAll('The project was stopped.');
|
|
52
|
+
|
|
53
|
+
public constructor(
|
|
54
|
+
private readonly runtime: RuntimeLike,
|
|
55
|
+
private readonly options: FunctionDispatcherOptions
|
|
56
|
+
) {
|
|
57
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_FUNCTION_TIMEOUT_MS;
|
|
58
|
+
this.setTimer = options.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
|
|
59
|
+
this.clearTimer = options.clearTimer ?? ((handle) => clearTimeout(handle as ReturnType<typeof setTimeout>));
|
|
60
|
+
runtime.on('AFTER_EXECUTE', this.onAfterExecute);
|
|
61
|
+
runtime.on('PROJECT_STOP_ALL', this.onStopAll);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Starts a named function. `caller` is the thread of the block making the call, if any; it is used
|
|
66
|
+
* to detect reentrant calls.
|
|
67
|
+
*/
|
|
68
|
+
public invoke(name: string, args: unknown, caller?: RuntimeThread): Promise<unknown> {
|
|
69
|
+
if (!this.options.knownNames().has(name)) {
|
|
70
|
+
return Promise.reject(new Error(`Unknown function: ${name}`));
|
|
71
|
+
}
|
|
72
|
+
const parentChain = caller ? (this.byThread.get(caller)?.chain ?? []) : [];
|
|
73
|
+
if (parentChain.includes(name)) {
|
|
74
|
+
return Promise.reject(
|
|
75
|
+
new Error(`Reentrant call: ${[...parentChain, name].join(' -> ')}. Use a custom block for recursion.`)
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
const invocation: Invocation = {
|
|
80
|
+
name,
|
|
81
|
+
args,
|
|
82
|
+
chain: [...parentChain, name],
|
|
83
|
+
resolve,
|
|
84
|
+
reject,
|
|
85
|
+
thread: null,
|
|
86
|
+
startedAtStep: -1,
|
|
87
|
+
timer: null,
|
|
88
|
+
settled: false
|
|
89
|
+
};
|
|
90
|
+
invocation.timer = this.setTimer(
|
|
91
|
+
() => this.settle(invocation, new Error(`Function ${name} timed out.`)),
|
|
92
|
+
this.timeoutMs
|
|
93
|
+
);
|
|
94
|
+
this.queue.push(invocation);
|
|
95
|
+
this.pump();
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Hat predicate: true only for the script that should run the invocation being started. */
|
|
100
|
+
public matchHat(name: string, thread: RuntimeThread | undefined): boolean {
|
|
101
|
+
const invocation = this.starting;
|
|
102
|
+
if (!invocation || !thread || invocation.name !== name.trim()) return false;
|
|
103
|
+
invocation.thread = thread;
|
|
104
|
+
this.byThread.set(thread, invocation);
|
|
105
|
+
this.starting = null;
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
public argumentsFor(thread: RuntimeThread | undefined): unknown {
|
|
110
|
+
const invocation = thread ? this.byThread.get(thread) : undefined;
|
|
111
|
+
if (!invocation) throw new Error('This block can only be used inside a running function.');
|
|
112
|
+
return invocation.args;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
public returnFrom(thread: RuntimeThread | undefined, value: unknown): void {
|
|
116
|
+
const invocation = thread ? this.byThread.get(thread) : undefined;
|
|
117
|
+
if (!invocation) throw new Error('return can only be used inside a running function.');
|
|
118
|
+
this.settle(invocation, null, value);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
public cancelAll(reason: string): void {
|
|
122
|
+
for (const invocation of [...this.queue, ...this.running.values()]) {
|
|
123
|
+
this.settle(invocation, new Error(reason));
|
|
124
|
+
}
|
|
125
|
+
if (this.starting) this.settle(this.starting, new Error(reason));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
public get pendingCount(): number {
|
|
129
|
+
return this.queue.length + this.running.size;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
public release(): void {
|
|
133
|
+
this.cancelAll('Named functions were released.');
|
|
134
|
+
this.runtime.off?.('AFTER_EXECUTE', this.onAfterExecute);
|
|
135
|
+
this.runtime.off?.('PROJECT_STOP_ALL', this.onStopAll);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private pump(): void {
|
|
139
|
+
if (this.starting) return;
|
|
140
|
+
const index = this.queue.findIndex((invocation) => !this.running.has(invocation.name));
|
|
141
|
+
if (index < 0) return;
|
|
142
|
+
const [invocation] = this.queue.splice(index, 1);
|
|
143
|
+
if (!invocation) return;
|
|
144
|
+
this.running.set(invocation.name, invocation);
|
|
145
|
+
this.starting = invocation;
|
|
146
|
+
invocation.startedAtStep = this.step;
|
|
147
|
+
this.runtime.startHats(this.options.hatOpcode);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private afterStep(): void {
|
|
151
|
+
this.step += 1;
|
|
152
|
+
const starting = this.starting;
|
|
153
|
+
// A started hat is evaluated within the current or the next step.
|
|
154
|
+
if (starting && this.step - starting.startedAtStep > 2) {
|
|
155
|
+
this.settle(starting, new Error(`Function ${starting.name} did not start. Is its script already running?`));
|
|
156
|
+
}
|
|
157
|
+
for (const invocation of this.running.values()) {
|
|
158
|
+
if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) {
|
|
159
|
+
// The script ended without `return`.
|
|
160
|
+
this.settle(invocation, null, null);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
this.pump();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private settle(invocation: Invocation, error: Error | null, value?: unknown): void {
|
|
167
|
+
if (invocation.settled) return;
|
|
168
|
+
invocation.settled = true;
|
|
169
|
+
this.clearTimer(invocation.timer);
|
|
170
|
+
const queued = this.queue.indexOf(invocation);
|
|
171
|
+
if (queued >= 0) this.queue.splice(queued, 1);
|
|
172
|
+
if (this.running.get(invocation.name) === invocation) this.running.delete(invocation.name);
|
|
173
|
+
if (invocation.thread) this.byThread.delete(invocation.thread);
|
|
174
|
+
if (this.starting === invocation) this.starting = null;
|
|
175
|
+
if (error) invocation.reject(error);
|
|
176
|
+
else invocation.resolve(value);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
|
|
181
|
+
export function readArgumentPath(args: unknown, path: string): unknown {
|
|
182
|
+
const trimmed = path.trim();
|
|
183
|
+
if (trimmed.length === 0) return args;
|
|
184
|
+
let current: unknown = args;
|
|
185
|
+
for (const segment of trimmed.split('.')) {
|
|
186
|
+
if (current === null || typeof current !== 'object') return undefined;
|
|
187
|
+
current = (current as Record<string, unknown>)[segment];
|
|
188
|
+
}
|
|
189
|
+
return current;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Converts a value for a Scratch reporter: objects and arrays become JSON text. */
|
|
193
|
+
export function toScratchValue(value: unknown): string | number | boolean {
|
|
194
|
+
if (value === undefined || value === null) return '';
|
|
195
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
|
|
196
|
+
return JSON.stringify(value);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Parses block text: JSON text becomes JSON, anything else stays a string. */
|
|
200
|
+
export function parseJsonOrText(text: string): unknown {
|
|
201
|
+
const trimmed = text.trim();
|
|
202
|
+
if (trimmed.length === 0) return '';
|
|
203
|
+
try {
|
|
204
|
+
return JSON.parse(trimmed) as unknown;
|
|
205
|
+
} catch {
|
|
206
|
+
return text;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type {RuntimeTarget, SerializedBlock} from './runtime-types.js';
|
|
2
|
+
|
|
3
|
+
/** A function exported as a tool, in the shape used by OpenAI function calling. */
|
|
4
|
+
export interface FunctionTool {
|
|
5
|
+
type: 'function';
|
|
6
|
+
name: string;
|
|
7
|
+
description: string;
|
|
8
|
+
parameters: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const FUNCTION_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/u;
|
|
12
|
+
export const MAX_DESCRIPTION_LENGTH = 1024;
|
|
13
|
+
|
|
14
|
+
export interface FunctionDefinition {
|
|
15
|
+
name: string;
|
|
16
|
+
description: string;
|
|
17
|
+
parameters: Record<string, unknown>;
|
|
18
|
+
exportAs: 'tool' | 'none';
|
|
19
|
+
targetName: string;
|
|
20
|
+
blockId: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface FunctionScan {
|
|
24
|
+
functions: FunctionDefinition[];
|
|
25
|
+
errors: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Reads every `define function` hat in the project. NAME, DESCRIPTION, and SCHEMA are part of the
|
|
30
|
+
* tool contract sent to the model before any script runs, so they must be literal text.
|
|
31
|
+
*/
|
|
32
|
+
export function scanFunctionDefinitions(targets: readonly RuntimeTarget[], hatOpcode: string): FunctionScan {
|
|
33
|
+
const functions: FunctionDefinition[] = [];
|
|
34
|
+
const errors: string[] = [];
|
|
35
|
+
const seen = new Map<string, string>();
|
|
36
|
+
|
|
37
|
+
for (const target of targets) {
|
|
38
|
+
if (target.isOriginal === false) continue;
|
|
39
|
+
const targetName = target.getName?.() ?? (target.isStage ? 'Stage' : 'sprite');
|
|
40
|
+
const blocks = target.blocks._blocks;
|
|
41
|
+
for (const block of Object.values(blocks)) {
|
|
42
|
+
if (block.opcode !== hatOpcode || block.topLevel === false) continue;
|
|
43
|
+
const where = `${targetName} (block ${block.id})`;
|
|
44
|
+
try {
|
|
45
|
+
const definition = readDefinition(block, blocks, targetName);
|
|
46
|
+
const previous = seen.get(definition.name);
|
|
47
|
+
if (previous !== undefined) {
|
|
48
|
+
throw new Error(`function "${definition.name}" is already defined in ${previous}`);
|
|
49
|
+
}
|
|
50
|
+
seen.set(definition.name, where);
|
|
51
|
+
functions.push(definition);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
errors.push(`${where}: ${error instanceof Error ? error.message : String(error)}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
functions.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
|
|
58
|
+
return {functions, errors};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function toFunctionTools(functions: readonly FunctionDefinition[]): FunctionTool[] {
|
|
62
|
+
return functions
|
|
63
|
+
.filter((definition) => definition.exportAs === 'tool')
|
|
64
|
+
.map((definition) => ({
|
|
65
|
+
type: 'function',
|
|
66
|
+
name: definition.name,
|
|
67
|
+
description: definition.description,
|
|
68
|
+
parameters: definition.parameters
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function readDefinition(
|
|
73
|
+
block: SerializedBlock,
|
|
74
|
+
blocks: Record<string, SerializedBlock>,
|
|
75
|
+
targetName: string
|
|
76
|
+
): FunctionDefinition {
|
|
77
|
+
const name = readLiteralInput(block, blocks, 'NAME').trim();
|
|
78
|
+
if (!FUNCTION_NAME_PATTERN.test(name)) {
|
|
79
|
+
throw new Error('function name must be 1-64 letters, digits, "_" or "-"');
|
|
80
|
+
}
|
|
81
|
+
const description = readLiteralInput(block, blocks, 'DESCRIPTION').trim();
|
|
82
|
+
if (description.length > MAX_DESCRIPTION_LENGTH) {
|
|
83
|
+
throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
|
|
84
|
+
}
|
|
85
|
+
const parameters = parseSchema(readLiteralInput(block, blocks, 'SCHEMA'));
|
|
86
|
+
const exportValue = String(block.fields?.EXPORT?.value ?? 'none');
|
|
87
|
+
const exportAs = exportValue === 'tool' ? 'tool' : 'none';
|
|
88
|
+
if (exportAs === 'tool' && description.length === 0) {
|
|
89
|
+
throw new Error('a function exported as a tool needs a description');
|
|
90
|
+
}
|
|
91
|
+
return {name, description, parameters, exportAs, targetName, blockId: block.id};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function readLiteralInput(
|
|
95
|
+
block: SerializedBlock,
|
|
96
|
+
blocks: Record<string, SerializedBlock>,
|
|
97
|
+
inputName: string
|
|
98
|
+
): string {
|
|
99
|
+
const input = block.inputs?.[inputName];
|
|
100
|
+
if (!input) throw new Error(`${inputName} is missing`);
|
|
101
|
+
if (input.block && input.block !== input.shadow) {
|
|
102
|
+
throw new Error(`${inputName} must be literal text, not a reporter block`);
|
|
103
|
+
}
|
|
104
|
+
const shadowId = input.shadow ?? input.block;
|
|
105
|
+
const shadow = shadowId ? blocks[shadowId] : undefined;
|
|
106
|
+
const field = shadow?.fields ? Object.values(shadow.fields)[0] : undefined;
|
|
107
|
+
if (!field) throw new Error(`${inputName} is missing`);
|
|
108
|
+
return String(field.value ?? '');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function parseSchema(text: string): Record<string, unknown> {
|
|
112
|
+
let value: unknown;
|
|
113
|
+
try {
|
|
114
|
+
value = JSON.parse(text) as unknown;
|
|
115
|
+
} catch {
|
|
116
|
+
throw new Error('args schema must be valid JSON');
|
|
117
|
+
}
|
|
118
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
119
|
+
throw new Error('args schema must be a JSON object');
|
|
120
|
+
}
|
|
121
|
+
const schema = value as Record<string, unknown>;
|
|
122
|
+
if (schema.type !== 'object') throw new Error('args schema must have "type": "object"');
|
|
123
|
+
return schema;
|
|
124
|
+
}
|
package/src/globals.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
interface TurboWarpExtension {
|
|
2
|
+
getInfo(): Record<string, unknown>;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
interface ScratchTranslate {
|
|
6
|
+
(text: string): string;
|
|
7
|
+
(message: {default: string; description?: string}, placeholders?: Record<string, string | number>): string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface ScratchApi {
|
|
11
|
+
extensions: {
|
|
12
|
+
unsandboxed: boolean;
|
|
13
|
+
register(extension: TurboWarpExtension): void;
|
|
14
|
+
};
|
|
15
|
+
vm?: {runtime: unknown};
|
|
16
|
+
BlockType: Record<'COMMAND' | 'REPORTER' | 'BOOLEAN' | 'HAT', string>;
|
|
17
|
+
ArgumentType: Record<'STRING' | 'NUMBER' | 'BOOLEAN', string>;
|
|
18
|
+
Cast: {
|
|
19
|
+
toString(value: unknown): string;
|
|
20
|
+
toNumber(value: unknown): number;
|
|
21
|
+
toBoolean(value: unknown): boolean;
|
|
22
|
+
};
|
|
23
|
+
translate: ScratchTranslate;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
declare const Scratch: ScratchApi;
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {extensionConfig} from './config.js';
|
|
2
|
+
import {NamedFunctionsExtension} from './extension.js';
|
|
3
|
+
import type {RuntimeLike} from './runtime-types.js';
|
|
4
|
+
|
|
5
|
+
if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) {
|
|
6
|
+
throw new Error(`${extensionConfig.name} must run unsandboxed.`);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const runtime = Scratch.vm?.runtime as RuntimeLike | undefined;
|
|
10
|
+
if (!runtime) {
|
|
11
|
+
throw new Error(`${extensionConfig.name} requires access to the TurboWarp VM runtime.`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
Scratch.extensions.register(new NamedFunctionsExtension({runtime}));
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** The narrow slice of the TurboWarp VM runtime this extension depends on. */
|
|
2
|
+
|
|
3
|
+
export interface SerializedField {
|
|
4
|
+
value?: unknown;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface SerializedInput {
|
|
8
|
+
block?: string | null;
|
|
9
|
+
shadow?: string | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface SerializedBlock {
|
|
13
|
+
id: string;
|
|
14
|
+
opcode: string;
|
|
15
|
+
topLevel?: boolean;
|
|
16
|
+
shadow?: boolean;
|
|
17
|
+
inputs?: Record<string, SerializedInput>;
|
|
18
|
+
fields?: Record<string, SerializedField>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RuntimeTarget {
|
|
22
|
+
isOriginal?: boolean;
|
|
23
|
+
isStage?: boolean;
|
|
24
|
+
getName?(): string;
|
|
25
|
+
blocks: {_blocks: Record<string, SerializedBlock>};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RuntimeThread {
|
|
29
|
+
topBlock?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface RuntimeLike {
|
|
33
|
+
targets: RuntimeTarget[];
|
|
34
|
+
threads: RuntimeThread[];
|
|
35
|
+
startHats(opcode: string, matchFields?: Record<string, string>): RuntimeThread[] | undefined;
|
|
36
|
+
on(event: string, listener: (...args: unknown[]) => void): void;
|
|
37
|
+
off?(event: string, listener: (...args: unknown[]) => void): void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface BlockUtilityLike {
|
|
41
|
+
thread?: RuntimeThread;
|
|
42
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small JSON Schema validator for function arguments. It interprets the schema at run time and
|
|
3
|
+
* never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
|
|
4
|
+
*
|
|
5
|
+
* Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
|
|
6
|
+
* const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
|
|
7
|
+
* description and title, are ignored.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export function validateAgainstSchema(value: unknown, schema: unknown, path = '$'): string[] {
|
|
11
|
+
const rule = asRecord(schema);
|
|
12
|
+
if (!rule) return [];
|
|
13
|
+
const errors: string[] = [];
|
|
14
|
+
|
|
15
|
+
if (rule.type !== undefined) {
|
|
16
|
+
const types = Array.isArray(rule.type) ? rule.type : [rule.type];
|
|
17
|
+
if (!types.some((type) => matchesType(value, type))) {
|
|
18
|
+
return [`${path} must be ${types.join(' or ')}`];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => deepEqual(candidate, value))) {
|
|
22
|
+
errors.push(`${path} must be one of ${rule.enum.map((item) => JSON.stringify(item)).join(', ')}`);
|
|
23
|
+
}
|
|
24
|
+
if ('const' in rule && !deepEqual(rule.const, value)) {
|
|
25
|
+
errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (typeof value === 'number') {
|
|
29
|
+
if (typeof rule.minimum === 'number' && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
|
|
30
|
+
if (typeof rule.maximum === 'number' && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
|
|
31
|
+
}
|
|
32
|
+
if (typeof value === 'string') {
|
|
33
|
+
const length = [...value].length;
|
|
34
|
+
if (typeof rule.minLength === 'number' && length < rule.minLength) {
|
|
35
|
+
errors.push(`${path} must have at least ${rule.minLength} characters`);
|
|
36
|
+
}
|
|
37
|
+
if (typeof rule.maxLength === 'number' && length > rule.maxLength) {
|
|
38
|
+
errors.push(`${path} must have at most ${rule.maxLength} characters`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(value)) {
|
|
42
|
+
if (typeof rule.minItems === 'number' && value.length < rule.minItems) {
|
|
43
|
+
errors.push(`${path} must have at least ${rule.minItems} items`);
|
|
44
|
+
}
|
|
45
|
+
if (typeof rule.maxItems === 'number' && value.length > rule.maxItems) {
|
|
46
|
+
errors.push(`${path} must have at most ${rule.maxItems} items`);
|
|
47
|
+
}
|
|
48
|
+
if (rule.items !== undefined) {
|
|
49
|
+
value.forEach((item, index) => errors.push(...validateAgainstSchema(item, rule.items, `${path}[${index}]`)));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const object = asRecord(value);
|
|
54
|
+
if (object) {
|
|
55
|
+
const properties = asRecord(rule.properties) ?? {};
|
|
56
|
+
if (Array.isArray(rule.required)) {
|
|
57
|
+
for (const name of rule.required) {
|
|
58
|
+
if (typeof name === 'string' && !(name in object)) errors.push(`${path}.${name} is required`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
for (const [name, child] of Object.entries(object)) {
|
|
62
|
+
if (name in properties) {
|
|
63
|
+
errors.push(...validateAgainstSchema(child, properties[name], `${path}.${name}`));
|
|
64
|
+
} else if (rule.additionalProperties === false) {
|
|
65
|
+
errors.push(`${path}.${name} is not allowed`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return errors;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function matchesType(value: unknown, type: unknown): boolean {
|
|
73
|
+
switch (type) {
|
|
74
|
+
case 'object':
|
|
75
|
+
return asRecord(value) !== null;
|
|
76
|
+
case 'array':
|
|
77
|
+
return Array.isArray(value);
|
|
78
|
+
case 'string':
|
|
79
|
+
return typeof value === 'string';
|
|
80
|
+
case 'number':
|
|
81
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
82
|
+
case 'integer':
|
|
83
|
+
return typeof value === 'number' && Number.isInteger(value);
|
|
84
|
+
case 'boolean':
|
|
85
|
+
return typeof value === 'boolean';
|
|
86
|
+
case 'null':
|
|
87
|
+
return value === null;
|
|
88
|
+
default:
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function deepEqual(left: unknown, right: unknown): boolean {
|
|
94
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
98
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
99
|
+
? (value as Record<string, unknown>)
|
|
100
|
+
: null;
|
|
101
|
+
}
|