@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.
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Composition API: named functions without TurboWarp block definitions.
3
+ *
4
+ * A consumer extension owns its `define function` hat (and its opcode) and forwards the hat
5
+ * predicate and the argument/return blocks here. Importing this module does not register a
6
+ * TurboWarp extension and does not touch the `Scratch` global.
7
+ */
8
+ import {FunctionDispatcher} from './function-dispatcher.js';
9
+ import {
10
+ scanFunctionDefinitions,
11
+ toFunctionTools,
12
+ type FunctionScan,
13
+ type FunctionTool
14
+ } from './function-registry.js';
15
+ import type {RuntimeLike, RuntimeThread} from './runtime-types.js';
16
+ import {validateAgainstSchema} from './schema-validator.js';
17
+
18
+ export type {FunctionDefinition, FunctionScan, FunctionTool} from './function-registry.js';
19
+ export {FUNCTION_NAME_PATTERN, scanFunctionDefinitions, toFunctionTools} from './function-registry.js';
20
+ export type {RuntimeLike, RuntimeThread, BlockUtilityLike} from './runtime-types.js';
21
+ export {parseJsonOrText, readArgumentPath, toScratchValue} from './function-dispatcher.js';
22
+ export {validateAgainstSchema} from './schema-validator.js';
23
+
24
+ export interface PromiseRef {
25
+ $promise: string;
26
+ }
27
+
28
+ export interface CallOptions {
29
+ /** Thread of the calling block, used to detect reentrant calls. */
30
+ caller?: RuntimeThread;
31
+ /** Refuse functions that are not exported as tools (for calls chosen by a model). */
32
+ exportedOnly?: boolean;
33
+ }
34
+
35
+ export interface NamedFunctionsOptions {
36
+ runtime: RuntimeLike;
37
+ /** Opcode of the consumer extension's `define function` hat, e.g. `myextension_defineFunction`. */
38
+ functionHatOpcode: string;
39
+ timeoutMs?: number;
40
+ /** Maximum concurrently running `start`ed calls; further starts wait for a slot. Default 8. */
41
+ maxInFlight?: number;
42
+ /** Settled promise results kept for `await`; the oldest settled ones are dropped first. Default 256. */
43
+ maxRetainedPromises?: number;
44
+ setTimer?: (callback: () => void, ms: number) => unknown;
45
+ clearTimer?: (handle: unknown) => void;
46
+ }
47
+
48
+ export interface NamedFunctions {
49
+ scan(): FunctionScan;
50
+ /** Functions exported as tools, in OpenAI function-calling shape. Throws if any definition is invalid. */
51
+ tools(): FunctionTool[];
52
+ isDefined(name: string): boolean;
53
+
54
+ /** Calls a function and waits for its result. Arguments are always validated against its schema. */
55
+ call(name: string, args: unknown, options?: CallOptions): Promise<unknown>;
56
+ /** Starts a function and returns a reference to await later. */
57
+ start(name: string, args: unknown, options?: CallOptions): PromiseRef;
58
+ await(ref: unknown): Promise<unknown>;
59
+ /** Waits for every reference; failed ones become `{"$error": message}` in place. */
60
+ awaitAll(refs: unknown): Promise<unknown[]>;
61
+ isSettled(ref: unknown): boolean;
62
+
63
+ /** Call from the `define function` hat predicate. */
64
+ matchHat(name: string, thread: RuntimeThread | undefined): boolean;
65
+ argumentsFor(thread: RuntimeThread | undefined): unknown;
66
+ returnFrom(thread: RuntimeThread | undefined, value: unknown): void;
67
+
68
+ cancelAll(reason: string): void;
69
+ release(): void;
70
+ }
71
+
72
+ export function createNamedFunctions(options: NamedFunctionsOptions): NamedFunctions {
73
+ return new NamedFunctionsImpl(options);
74
+ }
75
+
76
+ interface PromiseEntry {
77
+ promise: Promise<unknown>;
78
+ settled: boolean;
79
+ }
80
+
81
+ class NamedFunctionsImpl implements NamedFunctions {
82
+ private readonly dispatcher: FunctionDispatcher;
83
+ private readonly promises = new Map<string, PromiseEntry>();
84
+ private readonly waiting: Array<() => void> = [];
85
+ private inFlight = 0;
86
+ private nextPromiseId = 1;
87
+ private readonly maxInFlight: number;
88
+ private readonly maxRetained: number;
89
+
90
+ public constructor(private readonly options: NamedFunctionsOptions) {
91
+ this.maxInFlight = Math.max(1, options.maxInFlight ?? 8);
92
+ this.maxRetained = Math.max(1, options.maxRetainedPromises ?? 256);
93
+ const dispatcherOptions = {
94
+ hatOpcode: options.functionHatOpcode,
95
+ knownNames: () => new Set(this.scan().functions.map((definition) => definition.name)),
96
+ ...(options.timeoutMs === undefined ? {} : {timeoutMs: options.timeoutMs}),
97
+ ...(options.setTimer ? {setTimer: options.setTimer} : {}),
98
+ ...(options.clearTimer ? {clearTimer: options.clearTimer} : {})
99
+ };
100
+ this.dispatcher = new FunctionDispatcher(options.runtime, dispatcherOptions);
101
+ options.runtime.on('PROJECT_STOP_ALL', () => this.promises.clear());
102
+ }
103
+
104
+ public scan(): FunctionScan {
105
+ return scanFunctionDefinitions(this.options.runtime.targets, this.options.functionHatOpcode);
106
+ }
107
+
108
+ public tools(): FunctionTool[] {
109
+ const scan = this.scan();
110
+ if (scan.errors.length > 0) throw new Error(`Invalid function definitions: ${scan.errors.join('; ')}`);
111
+ return toFunctionTools(scan.functions);
112
+ }
113
+
114
+ public isDefined(name: string): boolean {
115
+ return this.scan().functions.some((definition) => definition.name === name.trim());
116
+ }
117
+
118
+ public call(name: string, args: unknown, options: CallOptions = {}): Promise<unknown> {
119
+ const trimmed = name.trim();
120
+ const definition = this.scan().functions.find((candidate) => candidate.name === trimmed);
121
+ if (!definition) return Promise.reject(new Error(`Unknown function: ${trimmed}`));
122
+ if (options.exportedOnly && definition.exportAs !== 'tool') {
123
+ return Promise.reject(new Error(`Function ${trimmed} is not exported as a tool.`));
124
+ }
125
+ const errors = validateAgainstSchema(args, definition.parameters);
126
+ if (errors.length > 0) {
127
+ return Promise.reject(new Error(`Invalid arguments for ${trimmed}: ${errors.join('; ')}`));
128
+ }
129
+ return this.dispatcher.invoke(trimmed, args, options.caller);
130
+ }
131
+
132
+ public start(name: string, args: unknown, options: CallOptions = {}): PromiseRef {
133
+ const id = `p_${this.nextPromiseId++}`;
134
+ const promise = this.acquireSlot().then(() =>
135
+ this.call(name, args, options).finally(() => this.releaseSlot())
136
+ );
137
+ const entry: PromiseEntry = {promise, settled: false};
138
+ promise.then(
139
+ () => (entry.settled = true),
140
+ () => (entry.settled = true)
141
+ );
142
+ this.promises.set(id, entry);
143
+ this.evictSettled();
144
+ return {$promise: id};
145
+ }
146
+
147
+ public await(ref: unknown): Promise<unknown> {
148
+ const entry = this.lookup(ref);
149
+ return entry ? entry.promise : Promise.reject(new Error('Unknown or expired promise reference.'));
150
+ }
151
+
152
+ public async awaitAll(refs: unknown): Promise<unknown[]> {
153
+ if (!Array.isArray(refs)) throw new Error('await all needs a JSON array of promise references.');
154
+ const results = await Promise.allSettled(refs.map((ref) => this.await(ref)));
155
+ return results.map((result) =>
156
+ result.status === 'fulfilled' ? result.value : {$error: messageOf(result.reason)}
157
+ );
158
+ }
159
+
160
+ public isSettled(ref: unknown): boolean {
161
+ return this.lookup(ref)?.settled ?? false;
162
+ }
163
+
164
+ public matchHat(name: string, thread: RuntimeThread | undefined): boolean {
165
+ return this.dispatcher.matchHat(name, thread);
166
+ }
167
+
168
+ public argumentsFor(thread: RuntimeThread | undefined): unknown {
169
+ return this.dispatcher.argumentsFor(thread);
170
+ }
171
+
172
+ public returnFrom(thread: RuntimeThread | undefined, value: unknown): void {
173
+ this.dispatcher.returnFrom(thread, value);
174
+ }
175
+
176
+ public cancelAll(reason: string): void {
177
+ this.dispatcher.cancelAll(reason);
178
+ }
179
+
180
+ public release(): void {
181
+ this.dispatcher.release();
182
+ this.promises.clear();
183
+ }
184
+
185
+ private lookup(ref: unknown): PromiseEntry | undefined {
186
+ const id =
187
+ typeof ref === 'object' && ref !== null && typeof (ref as PromiseRef).$promise === 'string'
188
+ ? (ref as PromiseRef).$promise
189
+ : undefined;
190
+ return id ? this.promises.get(id) : undefined;
191
+ }
192
+
193
+ private acquireSlot(): Promise<void> {
194
+ if (this.inFlight < this.maxInFlight) {
195
+ this.inFlight += 1;
196
+ return Promise.resolve();
197
+ }
198
+ return new Promise((resolve) => this.waiting.push(() => {
199
+ this.inFlight += 1;
200
+ resolve();
201
+ }));
202
+ }
203
+
204
+ private releaseSlot(): void {
205
+ this.inFlight -= 1;
206
+ this.waiting.shift()?.();
207
+ }
208
+
209
+ private evictSettled(): void {
210
+ if (this.promises.size <= this.maxRetained) return;
211
+ for (const [id, entry] of this.promises) {
212
+ if (this.promises.size <= this.maxRetained) break;
213
+ if (entry.settled) this.promises.delete(id);
214
+ }
215
+ }
216
+ }
217
+
218
+ function messageOf(error: unknown): string {
219
+ return error instanceof Error ? error.message : String(error);
220
+ }
package/src/config.ts ADDED
@@ -0,0 +1,12 @@
1
+ export const extensionConfig = {
2
+ id: 'kubohiroyanamedfunctions',
3
+ slug: 'turbowarp-named-functions',
4
+ name: 'TurboWarp-Named-Functions',
5
+ description: 'Named JSON functions that scripts can call by name, synchronously or asynchronously.',
6
+ author: 'Hiroya Kubo',
7
+ license: 'MPL-2.0',
8
+ unsandboxed: true,
9
+ docsURI: 'https://kubohiroya.github.io/turbowarp-named-functions/',
10
+ blockIconURI:
11
+ 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNCIgeT0iOCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjMyIiByeD0iNiIgZmlsbD0iIzhBNTVENyIvPjx0ZXh0IHg9IjI0IiB5PSIzMSIgZm9udC1mYW1pbHk9Im1vbm9zcGFjZSIgZm9udC1zaXplPSIxNiIgZm9udC13ZWlnaHQ9ImJvbGQiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNmZmYiPmYoeCk8L3RleHQ+PC9zdmc+'
12
+ } as const;
@@ -0,0 +1,149 @@
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
+ }
@@ -0,0 +1,200 @@
1
+ import {extensionConfig} from './config';
2
+ import definitions from './block-definitions.json';
3
+ import {
4
+ createNamedFunctions,
5
+ parseJsonOrText,
6
+ readArgumentPath,
7
+ toScratchValue,
8
+ type NamedFunctions,
9
+ type NamedFunctionsOptions
10
+ } from './composition.js';
11
+ import type {BlockUtilityLike} from './runtime-types.js';
12
+
13
+ type BlockTypeName = 'COMMAND' | 'REPORTER' | 'BOOLEAN' | 'HAT';
14
+ type ArgumentTypeName = 'STRING' | 'NUMBER' | 'BOOLEAN';
15
+
16
+ interface DefinitionArgument {
17
+ type: ArgumentTypeName;
18
+ defaultValue: string;
19
+ menu?: string;
20
+ }
21
+
22
+ interface BlockDefinition {
23
+ opcode: string;
24
+ blockType: BlockTypeName;
25
+ text: string;
26
+ arguments: Record<string, DefinitionArgument>;
27
+ }
28
+
29
+ interface MenuDefinition {
30
+ acceptReporters: boolean;
31
+ items: string[];
32
+ }
33
+
34
+ const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
35
+ const menuDefinitions = definitions.menus as Record<string, MenuDefinition>;
36
+
37
+ export const DEFINE_FUNCTION_OPCODE = `${extensionConfig.id}_defineFunction`;
38
+
39
+ export type NamedFunctionsExtensionDependencies = Omit<NamedFunctionsOptions, 'functionHatOpcode'>;
40
+
41
+ type Args = Record<string, unknown>;
42
+ type Util = BlockUtilityLike & {stopThisScript?: () => void};
43
+
44
+ /** Block surface over the named-functions composition. */
45
+ export class NamedFunctionsExtension implements TurboWarpExtension {
46
+ private lastErrorMessage = '';
47
+ private readonly functions: NamedFunctions;
48
+
49
+ public constructor(deps: NamedFunctionsExtensionDependencies) {
50
+ this.functions = createNamedFunctions({...deps, functionHatOpcode: DEFINE_FUNCTION_OPCODE});
51
+ }
52
+
53
+ public getInfo(): Record<string, unknown> {
54
+ return {
55
+ id: extensionConfig.id,
56
+ name: Scratch.translate(definitions.extensionName),
57
+ docsURI: extensionConfig.docsURI,
58
+ blockIconURI: extensionConfig.blockIconURI,
59
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
60
+ menus: Object.fromEntries(
61
+ Object.entries(menuDefinitions).map(([id, menu]) => [
62
+ id,
63
+ {acceptReporters: menu.acceptReporters, items: [...menu.items]}
64
+ ])
65
+ )
66
+ };
67
+ }
68
+
69
+ // ---- definition ---------------------------------------------------------------------------
70
+
71
+ public defineFunction(args: Args, util?: Util): boolean {
72
+ return this.functions.matchHat(Scratch.Cast.toString(args.NAME), util?.thread);
73
+ }
74
+
75
+ public functionArgument(args: Args, util?: Util): string | number | boolean {
76
+ return this.guard('', () =>
77
+ toScratchValue(readArgumentPath(this.functions.argumentsFor(util?.thread), Scratch.Cast.toString(args.PATH)))
78
+ );
79
+ }
80
+
81
+ public functionArgumentsJson(_args: Args, util?: Util): string {
82
+ return this.guard('', () => JSON.stringify(this.functions.argumentsFor(util?.thread) ?? null));
83
+ }
84
+
85
+ public returnValue(args: Args, util?: Util): void {
86
+ this.guard(undefined, () => {
87
+ this.functions.returnFrom(util?.thread, parseJsonOrText(Scratch.Cast.toString(args.VALUE)));
88
+ util?.stopThisScript?.();
89
+ });
90
+ }
91
+
92
+ // ---- calls --------------------------------------------------------------------------------
93
+
94
+ public async callFunction(args: Args, util?: Util): Promise<string | number | boolean> {
95
+ try {
96
+ const result = await this.functions.call(
97
+ Scratch.Cast.toString(args.NAME),
98
+ parseArguments(Scratch.Cast.toString(args.ARGS)),
99
+ util?.thread ? {caller: util.thread} : {}
100
+ );
101
+ this.lastErrorMessage = '';
102
+ return toScratchValue(result);
103
+ } catch (error) {
104
+ this.lastErrorMessage = messageOf(error);
105
+ return '';
106
+ }
107
+ }
108
+
109
+ public startFunction(args: Args, util?: Util): string {
110
+ return this.guard('', () => {
111
+ const ref = this.functions.start(
112
+ Scratch.Cast.toString(args.NAME),
113
+ parseArguments(Scratch.Cast.toString(args.ARGS)),
114
+ util?.thread ? {caller: util.thread} : {}
115
+ );
116
+ return JSON.stringify(ref);
117
+ });
118
+ }
119
+
120
+ public async awaitResult(args: Args): Promise<string | number | boolean> {
121
+ try {
122
+ const result = await this.functions.await(parseJsonOrText(Scratch.Cast.toString(args.PROMISE)));
123
+ this.lastErrorMessage = '';
124
+ return toScratchValue(result);
125
+ } catch (error) {
126
+ this.lastErrorMessage = messageOf(error);
127
+ return '';
128
+ }
129
+ }
130
+
131
+ public async awaitAll(args: Args): Promise<string> {
132
+ try {
133
+ const results = await this.functions.awaitAll(parseJsonOrText(Scratch.Cast.toString(args.PROMISES)));
134
+ this.lastErrorMessage = '';
135
+ return JSON.stringify(results);
136
+ } catch (error) {
137
+ this.lastErrorMessage = messageOf(error);
138
+ return '';
139
+ }
140
+ }
141
+
142
+ public isSettled(args: Args): boolean {
143
+ return this.functions.isSettled(parseJsonOrText(Scratch.Cast.toString(args.PROMISE)));
144
+ }
145
+
146
+ public isDefined(args: Args): boolean {
147
+ return this.functions.isDefined(Scratch.Cast.toString(args.NAME));
148
+ }
149
+
150
+ public lastError(): string {
151
+ return this.lastErrorMessage;
152
+ }
153
+
154
+ // ---- internals ----------------------------------------------------------------------------
155
+
156
+ private guard<T>(fallback: T, action: () => T): T {
157
+ try {
158
+ const result = action();
159
+ this.lastErrorMessage = '';
160
+ return result;
161
+ } catch (error) {
162
+ this.lastErrorMessage = messageOf(error);
163
+ return fallback;
164
+ }
165
+ }
166
+
167
+ private toScratchBlock(block: BlockDefinition): Record<string, unknown> {
168
+ const scratchBlock: Record<string, unknown> = {
169
+ opcode: block.opcode,
170
+ blockType: Scratch.BlockType[block.blockType],
171
+ text: Scratch.translate(block.text),
172
+ arguments: Object.fromEntries(
173
+ Object.entries(block.arguments).map(([name, argument]) => [
174
+ name,
175
+ {
176
+ type: Scratch.ArgumentType[argument.type],
177
+ defaultValue: argument.defaultValue,
178
+ ...(argument.menu ? {menu: argument.menu} : {})
179
+ }
180
+ ])
181
+ )
182
+ };
183
+ if (block.blockType === 'HAT') scratchBlock.isEdgeActivated = false;
184
+ return scratchBlock;
185
+ }
186
+ }
187
+
188
+ /** ARGS text: empty means `{}`; otherwise it must be JSON. */
189
+ function parseArguments(text: string): unknown {
190
+ if (text.trim().length === 0) return {};
191
+ try {
192
+ return JSON.parse(text) as unknown;
193
+ } catch {
194
+ throw new Error('ARGS must be JSON text, for example {"a":1}.');
195
+ }
196
+ }
197
+
198
+ function messageOf(error: unknown): string {
199
+ return error instanceof Error ? error.message : String(error);
200
+ }