logic-mesh 1.0.0 → 2.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 +11 -0
- package/README.md +376 -43
- package/dist/EngineSession.d.ts +206 -0
- package/dist/EngineSession.js +277 -0
- package/dist/JsBlocks.d.ts +150 -0
- package/dist/JsBlocks.js +211 -0
- package/dist/LogicMeshError.d.ts +38 -0
- package/dist/LogicMeshError.js +9 -0
- package/dist/ProgramSchema.d.ts +57 -0
- package/dist/ProgramSchema.js +103 -0
- package/dist/ProgramVersion.d.ts +10 -0
- package/dist/ProgramVersion.js +13 -0
- package/dist/TypedBlock.d.ts +32 -2
- package/dist/TypedBlock.js +100 -22
- package/dist/index.d.ts +236 -49
- package/dist/index.js +7 -2
- package/dist/logic_mesh.d.ts +295 -104
- package/dist/logic_mesh.js +1 -1
- package/dist/logic_mesh_bg.js +904 -452
- package/dist/logic_mesh_bg.wasm +0 -0
- package/dist/logic_mesh_bg.wasm.d.ts +45 -26
- package/package.json +39 -21
package/LICENSE
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Copyright 2022-2024 Radu Racariu
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
4
|
+
|
|
5
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
6
|
+
|
|
7
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
8
|
+
|
|
9
|
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
10
|
+
|
|
11
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# Logic Mesh
|
|
2
2
|
|
|
3
3
|
A logic engine that is fully async, dynamic, and reactive written in Rust.
|
|
4
|
-
The engine is compiled to WebAssembly and
|
|
4
|
+
The engine is compiled to WebAssembly and runs in the browser (through a
|
|
5
|
+
bundler) and in Node.js — see [Environment support](#environment-support).
|
|
5
6
|
|
|
6
7
|
## Applications
|
|
7
8
|
|
|
@@ -12,79 +13,255 @@ The engine is compiled to WebAssembly and can be used in the browser, or in a No
|
|
|
12
13
|
|
|
13
14
|
- Fully async and reactive
|
|
14
15
|
- Extensible with custom blocks, either in Rust or JavaScript when running in a WASM environment
|
|
16
|
+
- Protocol-agnostic connectors for external data — implement subscribe/publish/request in JavaScript and bind them to blocks with the generic `ExternalIn`, `ExternalOut`, and `Request` blocks
|
|
17
|
+
- Plain JavaScript functions callable as blocks via `defineJsBlocks`
|
|
15
18
|
|
|
16
|
-
##
|
|
19
|
+
## Installation
|
|
17
20
|
|
|
18
|
-
|
|
21
|
+
```sh
|
|
22
|
+
npm install logic-mesh zod
|
|
23
|
+
```
|
|
19
24
|
|
|
20
|
-
|
|
25
|
+
Upgrading from 1.x? The
|
|
26
|
+
[migration guide](https://github.com/rracariu/logic-mesh/blob/main/docs/migration-2.0.md#9-the-javascript-api)
|
|
27
|
+
lists what changed in the JavaScript API.
|
|
21
28
|
|
|
22
|
-
|
|
29
|
+
[Zod](https://zod.dev) 4.6 or newer is a peer dependency: `defineBlock`
|
|
30
|
+
describes pins with your Zod schemas, so the package must use the same `zod`
|
|
31
|
+
your code imports. Upgrade an app on an older Zod first: npm refuses to
|
|
32
|
+
install the package next to it (`ERESOLVE ... peer zod@"^4.6.0"`), even in
|
|
33
|
+
apps that never call `defineBlock`.
|
|
23
34
|
|
|
24
|
-
|
|
25
|
-
import { initEngine } from 'logic-mesh';
|
|
35
|
+
## Environment support
|
|
26
36
|
|
|
27
|
-
|
|
28
|
-
|
|
37
|
+
The package is ESM only. It ships the wasm-pack `bundler` build, whose glue
|
|
38
|
+
module imports the `.wasm` file directly (the WebAssembly ESM integration)
|
|
39
|
+
and instantiates it on first import.
|
|
29
40
|
|
|
30
|
-
|
|
31
|
-
|
|
41
|
+
### Node.js
|
|
42
|
+
|
|
43
|
+
Node.js `^22.19.0` or `>=24.5.0` loads the package with a plain `import`,
|
|
44
|
+
without flags or loaders:
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import { startEngine } from 'logic-mesh';
|
|
48
|
+
|
|
49
|
+
const { command } = startEngine();
|
|
50
|
+
console.log(await command.evalBlock('Add', [1, 2])); // [ 3 ]
|
|
32
51
|
```
|
|
33
52
|
|
|
34
|
-
|
|
53
|
+
- Node prints an `ExperimentalWarning` ("Importing WebAssembly module
|
|
54
|
+
instances is an experimental feature"). Run
|
|
55
|
+
`node --disable-warning=ExperimentalWarning` to silence it.
|
|
56
|
+
- From CommonJS use `await import('logic-mesh')`. `require('logic-mesh')`
|
|
57
|
+
fails before Node.js 26 (`WASM is currently unsupported by require(esm)`).
|
|
58
|
+
- Older releases (Node.js 20, 22.12–22.18, 24.0–24.4) load the package only
|
|
59
|
+
with `node --experimental-wasm-modules`, and are outside the supported
|
|
60
|
+
`engines` range.
|
|
61
|
+
|
|
62
|
+
### Bundlers
|
|
63
|
+
|
|
64
|
+
- **Vite** needs [vite-plugin-wasm](https://github.com/Menci/vite-plugin-wasm).
|
|
65
|
+
Without it, Vite 7 and earlier fail to build the package, and Vite 8's dev
|
|
66
|
+
server serves it broken (only Vite 8's production build copes). The plugin
|
|
67
|
+
instantiates the module with a top-level `await`, which the default build
|
|
68
|
+
target of Vite 6 and earlier rejects, so set `build.target` too. The
|
|
69
|
+
[demo app](https://github.com/rracariu/logic-mesh/blob/main/web/app/vite.config.ts)
|
|
70
|
+
uses this configuration:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// vite.config.ts
|
|
74
|
+
import { defineConfig } from 'vite';
|
|
75
|
+
import wasm from 'vite-plugin-wasm';
|
|
76
|
+
|
|
77
|
+
export default defineConfig({
|
|
78
|
+
plugins: [wasm()],
|
|
79
|
+
build: {
|
|
80
|
+
// Needed on Vite 6 and earlier; harmless on Vite 7 and 8.
|
|
81
|
+
target: 'esnext',
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- **webpack 5** needs `experiments: { asyncWebAssembly: true }`.
|
|
87
|
+
|
|
88
|
+
### TypeScript
|
|
89
|
+
|
|
90
|
+
Type declarations ship with the package. The declarations use
|
|
91
|
+
`Symbol.dispose` and `Symbol.asyncDispose`, so compile with
|
|
92
|
+
`skipLibCheck: true` or add `ESNext.Disposable` (or `ESNext`) to `lib`.
|
|
35
93
|
|
|
36
|
-
|
|
37
|
-
import { initEngine } from 'logic-mesh';
|
|
94
|
+
## UI Editor
|
|
38
95
|
|
|
39
|
-
|
|
40
|
-
const engine = initEngine();
|
|
96
|
+
There is a sample low code editor that is built on top of Logic Mesh, which can be found [here](https://rracariu.github.io/logic-mesh/). It serves as an example of how Logic Mesh can be used, and as a simple way to experiment with the Logic Mesh engine.
|
|
41
97
|
|
|
42
|
-
|
|
43
|
-
|
|
98
|
+
## Examples
|
|
99
|
+
|
|
100
|
+
### Start the engine and wire blocks together
|
|
101
|
+
|
|
102
|
+
`startEngine()` creates the engine, prepares the command handles, and
|
|
103
|
+
starts the engine's message loop — in the one order that works.
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { startEngine } from 'logic-mesh';
|
|
107
|
+
|
|
108
|
+
// Engine created and running; `command` is ready to use. The scan
|
|
109
|
+
// interval — how often the blocks that poll check their state — is in
|
|
110
|
+
// milliseconds, 200 by default.
|
|
111
|
+
const session = startEngine({ scanInterval: 100 });
|
|
112
|
+
const { command } = session;
|
|
44
113
|
|
|
45
114
|
// Add a SineWave block
|
|
46
115
|
const sineWaveId = await command.addBlock('SineWave');
|
|
47
116
|
// Add a StrLen block
|
|
48
117
|
const strLenId = await command.addBlock('StrLen');
|
|
49
118
|
|
|
50
|
-
// Connect the blocks, sineWave -> strLen (sineWave's out port to strLen's in port)
|
|
51
|
-
|
|
119
|
+
// Connect the blocks, sineWave -> strLen (sineWave's out port to strLen's in port).
|
|
120
|
+
// A handle takes overlapping calls too: each promise settles with the
|
|
121
|
+
// engine's answer to its own call.
|
|
122
|
+
await command.createLink(sineWaveId, strLenId, 'out', 'in');
|
|
52
123
|
|
|
53
|
-
//
|
|
54
|
-
|
|
124
|
+
// Read a block's state and pin values, as plain objects
|
|
125
|
+
const block = await command.inspectBlock(strLenId);
|
|
126
|
+
console.log(block.state, block.outputs.out.val);
|
|
127
|
+
|
|
128
|
+
// Stop the engine; the promise resolves once it has stopped
|
|
129
|
+
await session.stop();
|
|
55
130
|
```
|
|
56
131
|
|
|
57
|
-
|
|
132
|
+
Values reach JavaScript in one JSON-compatible encoding, from every command,
|
|
133
|
+
watch notification and JS block call: a Haystack Dict is a plain object, and
|
|
134
|
+
Null or a missing value is `null`.
|
|
135
|
+
|
|
136
|
+
Under the hood the sequence matters, and getting it wrong fails in
|
|
137
|
+
confusing ways — which is why the wrapper owns it:
|
|
58
138
|
|
|
59
139
|
```ts
|
|
60
140
|
import { initEngine } from 'logic-mesh';
|
|
61
141
|
|
|
62
|
-
// Initialize the engine
|
|
63
142
|
const engine = initEngine();
|
|
64
143
|
|
|
65
|
-
//
|
|
144
|
+
// Command handles must be created before `run()`: `engineCommand()`
|
|
145
|
+
// borrows the engine mutably, and `run()`'s future holds that borrow
|
|
146
|
+
// from its first poll onward ("recursive use of an object detected").
|
|
66
147
|
const command = engine.engineCommand();
|
|
67
148
|
|
|
68
|
-
//
|
|
69
|
-
|
|
149
|
+
// Start the engine without awaiting it: commands are only serviced by
|
|
150
|
+
// the running engine's message loop, and `run()`'s promise resolves
|
|
151
|
+
// only on shutdown — awaiting it first deadlocks.
|
|
152
|
+
engine.run();
|
|
153
|
+
```
|
|
70
154
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
155
|
+
`startEngine` returns an `EngineSession`, which also carries a second
|
|
156
|
+
handle for connector attachment (`connectorCommand`), `watch()` /
|
|
157
|
+
`unwatch()`, and `reset()`/`stop()` that are safe to call at any point
|
|
158
|
+
after start and resolve once the engine has reset or stopped. Hosts that need to create the
|
|
159
|
+
handles early but start the engine later (say, at component mount) can
|
|
160
|
+
use `createEngineSession()` and call `session.start()` when ready.
|
|
161
|
+
|
|
162
|
+
### Watch for block changes
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import { startEngine } from 'logic-mesh';
|
|
166
|
+
|
|
167
|
+
const session = startEngine();
|
|
168
|
+
|
|
169
|
+
// Register a callback that will be called when a block changes. The
|
|
170
|
+
// promise resolves with the watch once the engine opened it.
|
|
171
|
+
const watch = await session.watch((notification) => {
|
|
75
172
|
console.log('Block changed', JSON.stringify(notification));
|
|
76
173
|
});
|
|
77
174
|
|
|
78
|
-
|
|
175
|
+
const sineWave = await session.command.addBlock('SineWave');
|
|
176
|
+
|
|
177
|
+
// Stop the notifications. `await using watch = ...` closes it at the
|
|
178
|
+
// end of the scope instead.
|
|
179
|
+
await watch.close();
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### Handle errors
|
|
183
|
+
|
|
184
|
+
A command that fails rejects with a `LogicMeshError`: an `Error` whose
|
|
185
|
+
`code` names the failure — `'BlockInstanceNotFound'`,
|
|
186
|
+
`'UnsupportedProgramVersion'`, … (the `LogicMeshErrorCode` union) — and
|
|
187
|
+
whose `message` describes it. The codes are stable; the messages are
|
|
188
|
+
for people. The synchronous calls — `initEngine`, `registerBlock`,
|
|
189
|
+
`registerConnector`, `setLogLevel` — throw `LogicMeshError`s too.
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
import { isLogicMeshError, startEngine } from 'logic-mesh';
|
|
193
|
+
|
|
194
|
+
const { command } = startEngine();
|
|
195
|
+
|
|
196
|
+
try {
|
|
197
|
+
await command.loadProgram(saved);
|
|
198
|
+
} catch (err) {
|
|
199
|
+
if (isLogicMeshError(err) && err.code === 'UnsupportedProgramVersion') {
|
|
200
|
+
console.warn('Saved by a newer version:', err.message);
|
|
201
|
+
} else {
|
|
202
|
+
throw err;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Logging
|
|
208
|
+
|
|
209
|
+
The engine logs warnings and errors to the console. `setLogLevel` makes
|
|
210
|
+
it more verbose, or silences it:
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
import { setLogLevel } from 'logic-mesh';
|
|
214
|
+
|
|
215
|
+
setLogLevel('debug'); // 'off' | 'error' | 'warn' | 'info' | 'debug' | 'trace'
|
|
79
216
|
```
|
|
80
217
|
|
|
218
|
+
### Expose JavaScript functions as blocks
|
|
219
|
+
|
|
220
|
+
`defineJsBlocks` turns plain JS functions — sync or async — into
|
|
221
|
+
engine blocks. Each function becomes addressable through a `Request`
|
|
222
|
+
block: the block's `in` pin carries the argument, `out` carries the
|
|
223
|
+
returned (and awaited) result, and a rejection surfaces as the block's
|
|
224
|
+
fault. The `Request` block's `timeout` pin bounds functions that never
|
|
225
|
+
settle.
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
import { defineJsBlocks, startEngine } from 'logic-mesh';
|
|
229
|
+
|
|
230
|
+
const session = startEngine();
|
|
231
|
+
|
|
232
|
+
const jsBlocks = defineJsBlocks({
|
|
233
|
+
scale: (value) => (value as number) * 2,
|
|
234
|
+
fetchTemp: async (zone) => {
|
|
235
|
+
const response = await fetch(`/api/temp/${zone as string}`);
|
|
236
|
+
return response.json();
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
// Register the backing connector and attach it to the running engine
|
|
241
|
+
await jsBlocks.attach(session.command);
|
|
242
|
+
|
|
243
|
+
// Add a block that calls `scale` — a `Request` block wired to it
|
|
244
|
+
const id = await jsBlocks.addBlock(session.command, 'scale');
|
|
245
|
+
await session.command.writeBlockInput(id, 'in', 21); // out becomes 42
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Functions taking several inputs receive them as one object: write a
|
|
249
|
+
dict value to the `in` pin and the function is handed a plain JS
|
|
250
|
+
object (nested dicts included). `jsBlocks.detach(command)` removes the
|
|
251
|
+
connector again; after an engine `reset()` (which detaches all managed
|
|
252
|
+
connectors) calling `attach` once more restores it.
|
|
253
|
+
|
|
81
254
|
### Add a custom JavaScript block
|
|
82
255
|
|
|
256
|
+
For blocks with typed, named pins that show up in the block library
|
|
257
|
+
like the built-ins do, register a full block description instead:
|
|
258
|
+
|
|
83
259
|
```ts
|
|
84
|
-
import {
|
|
260
|
+
import { createEngineSession, type BlockDesc, type JsBlock } from 'logic-mesh';
|
|
85
261
|
|
|
86
|
-
//
|
|
87
|
-
|
|
262
|
+
// Blocks must be registered before the engine starts, so create the
|
|
263
|
+
// session first and start it after registration
|
|
264
|
+
const session = createEngineSession();
|
|
88
265
|
|
|
89
266
|
/**
|
|
90
267
|
* Defines a block that is implemented in JS
|
|
@@ -100,18 +277,174 @@ const JsAddBlock = {
|
|
|
100
277
|
doc: 'Adds two numbers',
|
|
101
278
|
implementation: 'external',
|
|
102
279
|
inputs: [
|
|
103
|
-
{ name: 'in1', kind: '
|
|
104
|
-
{ name: 'in2', kind: '
|
|
280
|
+
{ name: 'in1', kind: 'number' },
|
|
281
|
+
{ name: 'in2', kind: 'number' },
|
|
105
282
|
],
|
|
106
|
-
outputs: [{ name: 'out', kind: '
|
|
283
|
+
outputs: [{ name: 'out', kind: 'number' }],
|
|
107
284
|
} satisfies BlockDesc,
|
|
108
|
-
// The block
|
|
109
|
-
function
|
|
110
|
-
|
|
285
|
+
// The block factory: called once per block instance, it returns the
|
|
286
|
+
// execute function. Inputs and outputs are arrays in pin order.
|
|
287
|
+
executor: () => async (inputs: unknown[]) => {
|
|
288
|
+
return [Number(inputs[0]) + Number(inputs[1])];
|
|
111
289
|
},
|
|
112
290
|
} satisfies JsBlock;
|
|
113
291
|
|
|
114
|
-
engine.registerBlock(JsAddBlock.desc, JsAddBlock.
|
|
292
|
+
session.engine.registerBlock(JsAddBlock.desc, JsAddBlock.executor);
|
|
115
293
|
|
|
116
|
-
|
|
294
|
+
session.start();
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
The executor may be re-invoked with the same inputs if the engine
|
|
298
|
+
interrupts a call mid-flight (at-least-once), so side-effecting
|
|
299
|
+
executors should be idempotent.
|
|
300
|
+
|
|
301
|
+
A registered block runs when its inputs change: a value delivered over a
|
|
302
|
+
link, or one written with `writeBlockInput`, whether or not the pin is
|
|
303
|
+
linked.
|
|
304
|
+
|
|
305
|
+
### Which extension point to use
|
|
306
|
+
|
|
307
|
+
The three JS extension points overlap on purpose — each trades ergonomics
|
|
308
|
+
for capability at a different spot. Pick by the shape of what you are adding:
|
|
309
|
+
|
|
310
|
+
| You are adding… | Use | Because |
|
|
311
|
+
| --------------------------------------------------------------------------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
312
|
+
| A function the graph calls with one value (a transform, a lookup, a service call) | `defineJsBlocks` | One `in` → one `out` through a `Request` block: attach/detach on a **running** engine, a `timeout` pin, and a cancelled call is retried automatically (at-least-once — make handlers idempotent). Several inputs travel as one object on the single `in` pin. |
|
|
313
|
+
| A real block: several **independently wired** input pins, typed pins, an entry in the block library | `registerBlock` / `defineBlock` (TypedBlock) | Only registered blocks get named pins that separate upstream blocks can each link to, per-pin kinds (defaults come from `defineBlock`'s schema layer — raw `registerBlock` pins carry name and kind only), and a catalog entry. Register **before** `session.start()` — block registration is not available on a running engine. |
|
|
314
|
+
| A stream of values pushed _into_ the graph, a sink, or a whole protocol (MQTT, WebSocket, …) | a custom connector | `subscribe`/`publish`/`request` with engine-managed lifecycle; `ExternalIn`/`ExternalOut`/`Request` blocks bind to it by name and address, so the binding is data and serializes with the program. `defineJsBlocks` is itself a connector specialized to the request case. |
|
|
315
|
+
|
|
316
|
+
Rule of thumb: start with `defineJsBlocks`; move to `registerBlock` the moment
|
|
317
|
+
you need a second independently-linked input pin or a library entry; drop to a
|
|
318
|
+
custom connector when values flow on their own schedule rather than
|
|
319
|
+
per-request.
|
|
320
|
+
|
|
321
|
+
### Add a custom JavaScript connector
|
|
322
|
+
|
|
323
|
+
Connectors bridge the engine to external systems (MQTT, WebSockets, HTTP, …).
|
|
324
|
+
A connector implements `subscribe`, `publish`, and `request` (plus optional
|
|
325
|
+
`start`/`stop`); the generic `ExternalIn`/`ExternalOut`/`Request` blocks bind
|
|
326
|
+
to it by connector name and address.
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
import { registerConnector, startEngine, type JsConnector } from 'logic-mesh';
|
|
330
|
+
|
|
331
|
+
const connector = {
|
|
332
|
+
subscribe(address, callback) {
|
|
333
|
+
// Push values with callback(value); report an error with
|
|
334
|
+
// callback(undefined, detail); end the stream with callback().
|
|
335
|
+
const timer = setInterval(() => callback(Math.random() * 100), 1000);
|
|
336
|
+
// Return an unsubscribe function (or a Promise of one)
|
|
337
|
+
return () => clearInterval(timer);
|
|
338
|
+
},
|
|
339
|
+
publish(address, value) {
|
|
340
|
+
console.log(`publish ${value} to ${address}`);
|
|
341
|
+
},
|
|
342
|
+
request(address, value) {
|
|
343
|
+
return Promise.resolve({ echo: value });
|
|
344
|
+
},
|
|
345
|
+
} satisfies JsConnector;
|
|
346
|
+
|
|
347
|
+
// Put the connector in the process-wide registry
|
|
348
|
+
registerConnector('demo', connector);
|
|
349
|
+
|
|
350
|
+
const { command } = startEngine();
|
|
351
|
+
|
|
352
|
+
// ExternalIn streams subscribed values into the graph via its `out` pin
|
|
353
|
+
const inputId = await command.addBlock('ExternalIn');
|
|
354
|
+
await command.writeBlockInput(inputId, 'connector', 'demo');
|
|
355
|
+
await command.writeBlockInput(inputId, 'address', 'sensor/1');
|
|
356
|
+
|
|
357
|
+
// ExternalOut publishes whatever is wired to its `in` pin
|
|
358
|
+
const outputId = await command.addBlock('ExternalOut');
|
|
359
|
+
await command.writeBlockInput(outputId, 'connector', 'demo');
|
|
360
|
+
await command.writeBlockInput(outputId, 'address', 'actuator/1');
|
|
361
|
+
|
|
362
|
+
// Attach the connector to the running engine; the engine manages its
|
|
363
|
+
// lifecycle from here (it is stopped and detached on engine reset)
|
|
364
|
+
await command.addConnector('demo');
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Save and load programs
|
|
368
|
+
|
|
369
|
+
`getProgram()` resolves with the engine's program in the save format, as
|
|
370
|
+
plain JSON: store it with `JSON.stringify` and hand it back to
|
|
371
|
+
`loadProgram()`. A load is all or nothing, and a program saved by a newer
|
|
372
|
+
release rejects with code `'UnsupportedProgramVersion'`. Programs saved by
|
|
373
|
+
logic-mesh 1.x load as they are.
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { startEngine, type Program } from 'logic-mesh';
|
|
377
|
+
|
|
378
|
+
const { command } = startEngine();
|
|
379
|
+
|
|
380
|
+
const program = await command.getProgram();
|
|
381
|
+
localStorage.setItem('program', JSON.stringify(program));
|
|
382
|
+
|
|
383
|
+
// Later, on an engine with no blocks of its own
|
|
384
|
+
await command.resetEngine();
|
|
385
|
+
await command.loadProgram(
|
|
386
|
+
JSON.parse(localStorage.getItem('program')!) as Program,
|
|
387
|
+
);
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
A block can carry the editor's own state in `editor`, any JSON object
|
|
391
|
+
the engine saves back unchanged. Type it through `Program`'s parameter,
|
|
392
|
+
and declare the type with `type`, not `interface`:
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
import type { Program } from 'logic-mesh';
|
|
396
|
+
|
|
397
|
+
type MyEditor = { widget?: string; collapsed?: boolean };
|
|
398
|
+
|
|
399
|
+
const saved = (await command.getProgram()) as Program<MyEditor>;
|
|
400
|
+
for (const block of Object.values(saved.blocks)) {
|
|
401
|
+
console.log(block.name, block.editor?.widget);
|
|
402
|
+
}
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
On a running engine, `command.setBlockMetadata(id, label, position)` and
|
|
406
|
+
`command.setBlockEditor(id, editor)` change what a block is saved with.
|
|
407
|
+
|
|
408
|
+
`ProgramSchema` is a Zod schema of the save format. It checks a program
|
|
409
|
+
without the engine, before you store an upload, say, and reports each
|
|
410
|
+
problem at its path. It reads a program as `loadProgram` does: a 1.x save
|
|
411
|
+
parses, and a newer format fails on its `version`. `programSchema(editor)`
|
|
412
|
+
also checks the editor metadata with your own schema, and types the result
|
|
413
|
+
with it:
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import { ProgramSchema, programSchema, startEngine } from 'logic-mesh';
|
|
417
|
+
import { z } from 'zod';
|
|
418
|
+
|
|
419
|
+
const { command } = startEngine();
|
|
420
|
+
|
|
421
|
+
const result = ProgramSchema.safeParse(
|
|
422
|
+
JSON.parse(localStorage.getItem('program')!),
|
|
423
|
+
);
|
|
424
|
+
if (!result.success) throw new Error(z.prettifyError(result.error));
|
|
425
|
+
await command.loadProgram(result.data);
|
|
426
|
+
|
|
427
|
+
// A loose object keeps editor keys the schema does not name.
|
|
428
|
+
const MyProgram = programSchema(
|
|
429
|
+
z.looseObject({ widget: z.string().optional() }),
|
|
430
|
+
);
|
|
431
|
+
const saved = MyProgram.parse(await command.getProgram());
|
|
432
|
+
console.log(Object.values(saved.blocks)[0]?.editor?.widget);
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
A program that passes can still fail to load: only the engine knows
|
|
436
|
+
whether its block types are registered and its pins and links exist.
|
|
437
|
+
`z.toJSONSchema(ProgramSchema, { io: 'input' })` gives the format as a
|
|
438
|
+
JSON Schema, for tools outside JavaScript.
|
|
439
|
+
|
|
440
|
+
### List all registered blocks
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
import { initEngine } from 'logic-mesh';
|
|
444
|
+
|
|
445
|
+
// Initialize the engine
|
|
446
|
+
const engine = initEngine();
|
|
447
|
+
|
|
448
|
+
// List all registered blocks
|
|
449
|
+
const blocks = engine.listBlocks();
|
|
117
450
|
```
|