logic-mesh 0.1.9 → 0.9.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,49 @@
1
+ import type { BlockDesc, Kind } from "./index";
2
+ import type { BlocksEngine } from "./logic_mesh";
3
+ import { z, type ZodType } from "zod";
4
+ type InferType<T> = {
5
+ -readonly [K in keyof T]: z.infer<ExtractZodType<T[K]>>;
6
+ };
7
+ type ExtractZodType<T> = T extends readonly [string, infer U extends ZodType] ? U : never;
8
+ type BlockDetails = Omit<BlockDesc, "inputs" | "outputs" | "implementation">;
9
+ type TupleType = readonly (readonly [string, ZodType])[];
10
+ /**
11
+ * Defines a new block type with the specified configuration.
12
+ * @param config - The block configuration, including description, input/output types, and execution logic.
13
+ * @returns A class that extends TypedBlock, which can be registered with the BlocksEngine.
14
+ */
15
+ export declare function defineBlock<I extends TupleType, O extends TupleType>(config: {
16
+ desc: BlockDetails;
17
+ inputs: I;
18
+ outputs: O;
19
+ execute?: (inputs: InferType<I>) => Promise<InferType<O> | undefined>;
20
+ }): {
21
+ new (): {
22
+ execute(inputs: InferType<I>): Promise<InferType<O> | undefined>;
23
+ readonly desc: BlockDesc;
24
+ readonly inputs: string[];
25
+ readonly inputTypes: InferType<I>;
26
+ readonly outputs: string[];
27
+ readonly outputTypes: InferType<O>;
28
+ executeImpl(inputs: InferType<I>): Promise<unknown[] | undefined>;
29
+ zodToKind(kind: ZodType | undefined): Kind;
30
+ };
31
+ register(engine: BlocksEngine): void;
32
+ };
33
+ export declare class TypedBlock<I extends TupleType, O extends TupleType> {
34
+ readonly desc: BlockDesc;
35
+ readonly inputs: string[];
36
+ readonly inputTypes: InferType<I>;
37
+ readonly outputs: string[];
38
+ readonly outputTypes: InferType<O>;
39
+ constructor({ desc, inputs, outputs, }: {
40
+ desc: BlockDetails;
41
+ inputs: I;
42
+ outputs: O;
43
+ });
44
+ execute([..._inputs]: InferType<I>): Promise<unknown[] | undefined>;
45
+ static register(_engine: BlocksEngine): void;
46
+ executeImpl(inputs: InferType<I>): Promise<unknown[] | undefined>;
47
+ zodToKind(kind: ZodType | undefined): Kind;
48
+ }
49
+ export {};
@@ -0,0 +1,118 @@
1
+ import { ZodArray, ZodBoolean, ZodDefault, ZodEnum, ZodNumber, ZodObject, ZodOptional, ZodString, ZodUnknown, } from "zod";
2
+ /**
3
+ * Defines a new block type with the specified configuration.
4
+ * @param config - The block configuration, including description, input/output types, and execution logic.
5
+ * @returns A class that extends TypedBlock, which can be registered with the BlocksEngine.
6
+ */
7
+ export function defineBlock(config) {
8
+ const { execute: executeFn, ...blockConfig } = config;
9
+ return class extends TypedBlock {
10
+ constructor() {
11
+ super(blockConfig);
12
+ }
13
+ execute(inputs) {
14
+ if (executeFn)
15
+ return executeFn(inputs);
16
+ throw new Error("Not implemented");
17
+ }
18
+ static register(engine) {
19
+ const executor = new this();
20
+ if (executeFn) {
21
+ engine.registerBlock(executor.desc, () => executor.executeImpl.bind(executor));
22
+ }
23
+ else {
24
+ engine.registerBlock(executor.desc);
25
+ }
26
+ }
27
+ };
28
+ }
29
+ export class TypedBlock {
30
+ desc;
31
+ inputs;
32
+ inputTypes;
33
+ outputs;
34
+ outputTypes;
35
+ constructor({ desc, inputs, outputs, }) {
36
+ this.inputs = inputs.map(([name, _]) => name);
37
+ this.inputTypes = inputs.map(([, type]) => type);
38
+ this.outputs = outputs.map(([name, _]) => name);
39
+ this.outputTypes = outputs.map(([, type]) => type);
40
+ const blockDescription = desc;
41
+ blockDescription.implementation = "external";
42
+ blockDescription.inputs = this.inputs.map((name, i) => ({
43
+ name,
44
+ kind: this.zodToKind(this.inputTypes.at(i)),
45
+ }));
46
+ blockDescription.outputs = this.outputs.map((name, i) => ({
47
+ name,
48
+ kind: this.zodToKind(this.outputTypes.at(i)),
49
+ }));
50
+ this.desc = blockDescription;
51
+ }
52
+ execute([..._inputs]) {
53
+ throw new Error("Not implemented");
54
+ }
55
+ static register(_engine) {
56
+ throw new Error("Not implemented");
57
+ }
58
+ async executeImpl(inputs) {
59
+ // Validate inputs
60
+ if (inputs.length !== this.inputs.length) {
61
+ throw new Error("Invalid number of inputs");
62
+ }
63
+ this.inputs.map((_, i) => {
64
+ const val = inputs.at(i);
65
+ const kind = this.inputTypes[i];
66
+ inputs[i] = kind.parse(val);
67
+ });
68
+ const res = await this.execute(inputs);
69
+ if (res === undefined) {
70
+ return undefined;
71
+ }
72
+ // Validate outputs
73
+ if (res.length !== this.outputs.length) {
74
+ throw new Error("Invalid number of outputs");
75
+ }
76
+ this.outputs.forEach((_, i) => {
77
+ const val = res.at(i);
78
+ const kind = this.outputTypes[i];
79
+ kind.parse(val);
80
+ });
81
+ return res;
82
+ }
83
+ zodToKind(kind) {
84
+ if (kind === undefined) {
85
+ throw new Error("Unspecified kind");
86
+ }
87
+ if (kind instanceof ZodOptional) {
88
+ kind = kind.def.innerType;
89
+ }
90
+ if (kind instanceof ZodBoolean) {
91
+ return "bool";
92
+ }
93
+ else if (kind instanceof ZodNumber) {
94
+ return "number";
95
+ }
96
+ else if (kind instanceof ZodString) {
97
+ return "str";
98
+ }
99
+ else if (kind instanceof ZodEnum) {
100
+ return "str";
101
+ }
102
+ else if (kind instanceof ZodArray) {
103
+ return "list";
104
+ }
105
+ else if (kind instanceof ZodObject) {
106
+ return "dict";
107
+ }
108
+ else if (kind instanceof ZodUnknown) {
109
+ return "null";
110
+ }
111
+ else if (kind instanceof ZodDefault) {
112
+ return this.zodToKind(kind.def.innerType);
113
+ }
114
+ else {
115
+ throw new Error(`Invalid kind: ${kind?.constructor.name}`);
116
+ }
117
+ }
118
+ }
@@ -0,0 +1,208 @@
1
+ export { BlocksEngine, initEngine, EngineCommand } from "./logic_mesh.js";
2
+ export { defineBlock, TypedBlock } from "./TypedBlock";
3
+ /**
4
+ * The kind of the block pin.
5
+ */
6
+ export type Kind = "null" | "remove" | "marker" | "na" | "bool" | "number" | "str" | "uri" | "ref" | "symbol" | "date" | "time" | "dateTime" | "coord" | "xstr" | "list" | "dict" | "grid";
7
+ /**
8
+ * A block that is implemented in JS
9
+ */
10
+ export type JsBlock = {
11
+ /**
12
+ * The block description
13
+ */
14
+ desc: BlockDesc;
15
+ /**
16
+ * An optional block factory function that returns a function that is called when the block is executed.
17
+ *
18
+ * The execute function is called with the block inputs and should return the block outputs.
19
+ * The order of the inputs and outputs is the same as the order of the pins in the block description.
20
+ * Returning `undefined` will not change the output value.
21
+ *
22
+ * @returns The execute function that is called when the block is executed.
23
+ */
24
+ executor?: () => (inputs: unknown[]) => Promise<unknown[] | undefined>;
25
+ };
26
+ /**
27
+ * A block pin.
28
+ *
29
+ * Pins are the inputs and outputs of a block.
30
+ */
31
+ export interface BlockPin {
32
+ /**
33
+ * The pin name
34
+ */
35
+ name: string;
36
+ /**
37
+ * The pin kind
38
+ * Must be a valid haystack type kind.
39
+ * See https://project-haystack.org/doc/docHaystack/Kinds
40
+ */
41
+ kind: Kind;
42
+ /**
43
+ * The pin value
44
+ * Value is a Haystack value encoded as JSON.
45
+ */
46
+ value?: unknown;
47
+ /**
48
+ * True if the pin is connected to another pin.
49
+ */
50
+ isConnected?: boolean;
51
+ }
52
+ /**
53
+ * Describe a block that is available in block library.
54
+ */
55
+ export interface BlockDesc {
56
+ /**
57
+ * The block name
58
+ */
59
+ name: string;
60
+ /**
61
+ * The block display name
62
+ */
63
+ dis: string;
64
+ /**
65
+ * The block library name
66
+ */
67
+ lib: string;
68
+ /**
69
+ * The block library version
70
+ */
71
+ ver: string;
72
+ /**
73
+ * The block category
74
+ */
75
+ category: string;
76
+ /**
77
+ * The block documentation
78
+ */
79
+ doc: string;
80
+ /**
81
+ * The block implementation
82
+ */
83
+ implementation: "native" | "external";
84
+ /**
85
+ * The block inputs
86
+ */
87
+ inputs: BlockPin[];
88
+ /**
89
+ * The block outputs
90
+ */
91
+ outputs: BlockPin[];
92
+ /**
93
+ * The block run condition.
94
+ *
95
+ * If not set, the block will be executed when any of its inputs change.
96
+ * Otherwise, the block will execute regularly according to the run condition.
97
+ *
98
+ * Default: 'change'
99
+ */
100
+ runCondition?: "change" | "always";
101
+ }
102
+ /**
103
+ * Notification on a block change
104
+ */
105
+ export interface BlockNotification {
106
+ /**
107
+ * The block id
108
+ */
109
+ id: string;
110
+ /**
111
+ * The changes
112
+ */
113
+ changes: {
114
+ /**
115
+ * The block pin name
116
+ */
117
+ name: string;
118
+ /**
119
+ * The block pin source
120
+ */
121
+ source: string;
122
+ /**
123
+ * The value that was changed on this pin
124
+ */
125
+ value: {};
126
+ }[];
127
+ /**
128
+ * The block's operational state at the time of the notification.
129
+ * Drives fault visualization on the UI.
130
+ */
131
+ state: "running" | "fault" | "disabled" | "terminated";
132
+ /**
133
+ * Optional reason associated with `state === "fault"`.
134
+ */
135
+ faultReason?: string;
136
+ }
137
+ export interface LinkData {
138
+ /**
139
+ * The link id
140
+ */
141
+ id?: string;
142
+ /**
143
+ * The link source block pin name
144
+ */
145
+ sourceBlockPinName: string;
146
+ /**
147
+ * The link source block uuid
148
+ */
149
+ sourceBlockUuid: string;
150
+ /**
151
+ * The link target block pin name
152
+ */
153
+ targetBlockPinName: string;
154
+ /**
155
+ * The link target block uuid
156
+ */
157
+ targetBlockUuid: string;
158
+ }
159
+ /**
160
+ * Describes a program that would be loaded in the engine.
161
+ *
162
+ * The program is a set of blocks and links between them.
163
+ * The program and the blocks have meta data that would be used in the editor
164
+ * for example to position the blocks.
165
+ */
166
+ export interface Program {
167
+ /**
168
+ * The program name
169
+ */
170
+ name: string;
171
+ /**
172
+ * Optional program description
173
+ */
174
+ description?: string;
175
+ /**
176
+ * Blocks used in the program
177
+ */
178
+ blocks: {
179
+ [blockUuid: string]: {
180
+ name: string;
181
+ lib: string;
182
+ /** User-supplied display label shown alongside the block-type name. */
183
+ label?: string;
184
+ positions: {
185
+ x: number;
186
+ y: number;
187
+ };
188
+ inputs?: {
189
+ [pinName: string]: {
190
+ value?: unknown;
191
+ isConnected?: boolean;
192
+ };
193
+ };
194
+ outputs?: {
195
+ [pinName: string]: {
196
+ value?: unknown;
197
+ isConnected?: boolean;
198
+ };
199
+ };
200
+ };
201
+ };
202
+ /**
203
+ * Links between blocks
204
+ */
205
+ links: {
206
+ [linkUuid: string]: LinkData;
207
+ };
208
+ }
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { BlocksEngine, initEngine, EngineCommand } from "./logic_mesh.js";
2
+ export { defineBlock, TypedBlock } from "./TypedBlock";
@@ -0,0 +1,183 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /**
5
+ * Controls the execution or the blocks.
6
+ * Loads programs and enables inspection and debugging
7
+ * of the blocks and their inputs and outputs.
8
+ */
9
+ export class BlocksEngine {
10
+ free(): void;
11
+ [Symbol.dispose](): void;
12
+ engineCommand(): EngineCommand;
13
+ /**
14
+ * Lists all available blocks
15
+ */
16
+ listBlocks(): Array<any>;
17
+ /**
18
+ * Create a new instance of an engine
19
+ */
20
+ constructor(sleep_duration?: bigint | null);
21
+ /**
22
+ * Register a new JS block in the registry
23
+ * The block is described by a JsBlockDesc object
24
+ *
25
+ * # Arguments
26
+ * * `desc` - The description of the block
27
+ * * `func` - Optional function that implements the block
28
+ * logic. If not provided, the block would do nothing.
29
+ *
30
+ * # Returns
31
+ * The name of the block
32
+ */
33
+ registerBlock(desc: any, func?: Function | null): string;
34
+ /**
35
+ * Runs the engine asynchronously
36
+ * After this is called, the engine instance can't be used directly
37
+ * Instead use the command object to communicate with the engine.
38
+ */
39
+ run(): Promise<void>;
40
+ }
41
+
42
+ /**
43
+ * Commands a running instance of a Block Engine.
44
+ */
45
+ export class EngineCommand {
46
+ private constructor();
47
+ free(): void;
48
+ [Symbol.dispose](): void;
49
+ /**
50
+ * Adds a block instance to the engine
51
+ * to be immediately scheduled for execution
52
+ */
53
+ addBlock(block_name: string, block_uuid?: string | null, lib?: string | null): Promise<string>;
54
+ /**
55
+ * Creates a link between two blocks
56
+ *
57
+ * # Arguments
58
+ * * `source_block_uuid` - The UUID of the source block
59
+ * * `target_block_uuid` - The UUID of the target block
60
+ * * `source_block_pin_name` - The name of the output pin of the source block
61
+ * * `target_block_input_name` - The name of the input pin of the target block
62
+ *
63
+ * # Returns
64
+ * A `LinkData` object with the following properties:
65
+ * * `source_block_uuid` - The UUID of the source block
66
+ * * `target_block_uuid` - The UUID of the target block
67
+ * * `source_block_pin_name` - The name of the output pin of the source block
68
+ * * `target_block_input_name` - The name of the input pin of the target block
69
+ */
70
+ createLink(source_block_uuid: string, target_block_uuid: string, source_block_pin_name: string, target_block_pin_name: string): Promise<any>;
71
+ /**
72
+ * Creates a watch on block changes.
73
+ *
74
+ * The engine→UI watch channel is **unbounded**. The producer rate is
75
+ * capped by per-block execution cadence and the payload is tiny
76
+ * (one `WatchMessage` per changed block per cycle); a bounded channel
77
+ * (we had 32) was undersized for bursty loads — e.g., dozens of
78
+ * blocks faulting simultaneously during program load — and silently
79
+ * dropped fault notifications, which the UI is now load-bearing on
80
+ * (red ring/edge rendering).
81
+ */
82
+ createWatch(callback: Function): Promise<void>;
83
+ /**
84
+ * Evaluates a block by name
85
+ * This will create a block instance and execute it.
86
+ *
87
+ * # Arguments
88
+ * * `block_name` - The name of the block to evaluate
89
+ * * `inputs` - The input values to the block
90
+ * * `lib` - Optional, the library to load the block from, defaults to "core"
91
+ *
92
+ * # Returns
93
+ * A list of values representing the outputs of the block
94
+ */
95
+ evalBlock(block_name: string, inputs: any[], lib?: string | null): Promise<any>;
96
+ /**
97
+ * Get the current running engine program in the canonical save
98
+ * format (Program struct serialized as JSON). Round-trips through
99
+ * `loadProgram` without re-assembly.
100
+ */
101
+ getProgram(): Promise<any>;
102
+ /**
103
+ * Inspects the current state of a block
104
+ */
105
+ inspectBlock(block_uuid: string): Promise<any>;
106
+ /**
107
+ * Atomically load a full program (blocks + links + pin values +
108
+ * UI metadata) into the engine. Replaces the previous JS-side
109
+ * `addBlock` + `createLink` + `writeBlockInput` chain. The engine
110
+ * is expected to be empty (call `resetEngine` first if reloading).
111
+ */
112
+ loadProgram(program: any): Promise<void>;
113
+ /**
114
+ * Pauses the execution of the engine
115
+ * If the engine is already paused, this does nothing
116
+ */
117
+ pauseExecution(): Promise<void>;
118
+ /**
119
+ * Removes a block instance from the engine
120
+ * to be immediately unscheduled for execution
121
+ * and removed from the engine together with all its links.
122
+ *
123
+ * # Arguments
124
+ * * `block_uuid` - The UUID of the block to be removed
125
+ *
126
+ * # Returns
127
+ * The UUID of the removed block
128
+ */
129
+ removeBlock(block_uuid: string): Promise<string>;
130
+ /**
131
+ * Removes a link between two blocks
132
+ *
133
+ * # Arguments
134
+ * * `link_uuid` - The UUID of the link to be removed
135
+ *
136
+ * # Returns
137
+ * True if the link was removed, false otherwise
138
+ */
139
+ removeLink(link_uuid: string): Promise<boolean>;
140
+ /**
141
+ * Resets the engine state, clears all blocks and links
142
+ */
143
+ resetEngine(): Promise<void>;
144
+ /**
145
+ * Resumes the execution of the engine
146
+ * If the engine is not paused, this does nothing
147
+ */
148
+ resumeExecution(): Promise<void>;
149
+ /**
150
+ * Stop the engine's execution
151
+ */
152
+ stopEngine(): Promise<void>;
153
+ /**
154
+ * Writes the given block input with a value
155
+ *
156
+ * # Arguments
157
+ * * `block_uuid` - The UUID of the block to write to
158
+ * * `input_name` - The name of the input to write to
159
+ * * `value` - The value to write
160
+ *
161
+ * # Returns
162
+ * The previous value of the input
163
+ */
164
+ writeBlockInput(block_uuid: string, input_name: string, value: any): Promise<any>;
165
+ /**
166
+ * Writes the given block out with a value
167
+ *
168
+ * # Arguments
169
+ * * `block_uuid` - The UUID of the block to write to
170
+ * * `output_name` - The name of the output to write to
171
+ * * `value` - The value to write
172
+ *
173
+ * # Returns
174
+ * The block data
175
+ */
176
+ writeBlockOutput(block_uuid: string, output_name: string, value: any): Promise<any>;
177
+ }
178
+
179
+ export function initEngine(sleep_duration?: number | null): BlocksEngine;
180
+
181
+ export function init_panic_hook(): void;
182
+
183
+ export function start(): void;
@@ -1,6 +1,9 @@
1
+ /* @ts-self-types="./logic_mesh.d.ts" */
1
2
  import * as wasm from "./logic_mesh_bg.wasm";
2
3
  import { __wbg_set_wasm } from "./logic_mesh_bg.js";
3
- __wbg_set_wasm(wasm);
4
- export * from "./logic_mesh_bg.js";
5
4
 
5
+ __wbg_set_wasm(wasm);
6
6
  wasm.__wbindgen_start();
7
+ export {
8
+ BlocksEngine, EngineCommand, initEngine, init_panic_hook, start
9
+ } from "./logic_mesh_bg.js";