@syntropika/tembra-sdk 0.0.0-stage → 0.2.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.
Files changed (134) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +47 -2
  3. package/dist/authoring/declaration.d.ts +48 -0
  4. package/dist/authoring/hooks.d.ts +11 -0
  5. package/dist/authoring/orb.d.ts +3 -0
  6. package/dist/authoring/service-identities.d.ts +7 -0
  7. package/dist/authoring/services.d.ts +8 -0
  8. package/dist/authoring/types.d.ts +181 -0
  9. package/dist/bridge/identifiers.d.ts +207 -0
  10. package/dist/bridge/kernel.d.ts +117 -0
  11. package/dist/bridge/protocol.d.ts +181 -0
  12. package/dist/browser.d.ts +21 -0
  13. package/dist/browser.js +3335 -0
  14. package/dist/codec.d.ts +1 -0
  15. package/dist/codecs/json.d.ts +13 -0
  16. package/dist/codecs/msgpack.d.ts +3 -0
  17. package/dist/context-key.d.ts +35 -0
  18. package/dist/coordinator.d.ts +1 -0
  19. package/dist/coordinator.js +543 -0
  20. package/dist/embedded.d.ts +1 -0
  21. package/dist/embedded.js +1 -0
  22. package/dist/error.d.ts +13 -0
  23. package/dist/errors.d.ts +122 -0
  24. package/dist/hooks.d.ts +1 -0
  25. package/dist/host.d.ts +98 -0
  26. package/dist/host.js +3278 -0
  27. package/dist/identifiers.d.ts +1 -0
  28. package/dist/index.d.ts +12 -0
  29. package/dist/index.js +864 -0
  30. package/dist/infrastructure/coordinator.d.ts +13 -0
  31. package/dist/infrastructure/manager.d.ts +23 -0
  32. package/dist/infrastructure/rpc/channel.d.ts +55 -0
  33. package/dist/infrastructure/rpc/client.d.ts +20 -0
  34. package/dist/infrastructure/rpc/server.d.ts +10 -0
  35. package/dist/infrastructure/rpc/state.d.ts +16 -0
  36. package/dist/kernel.d.ts +1 -0
  37. package/dist/manager.d.ts +1 -0
  38. package/dist/manager.js +390 -0
  39. package/dist/msgpack.d.ts +1 -0
  40. package/dist/msgpack.js +635 -0
  41. package/dist/node.d.ts +14 -0
  42. package/dist/node.js +3336 -0
  43. package/dist/orb.d.ts +1 -0
  44. package/dist/protocol.d.ts +1 -0
  45. package/dist/rpc.d.ts +3 -0
  46. package/dist/rpc.js +1091 -0
  47. package/dist/runtime/activities.d.ts +30 -0
  48. package/dist/runtime/calls.d.ts +22 -0
  49. package/dist/runtime/context.d.ts +38 -0
  50. package/dist/runtime/declaration.d.ts +1 -0
  51. package/dist/runtime/lifecycle.d.ts +28 -0
  52. package/dist/runtime/orbs.d.ts +39 -0
  53. package/dist/runtime/programs.d.ts +31 -0
  54. package/dist/runtime/records.d.ts +107 -0
  55. package/dist/runtime/references.d.ts +38 -0
  56. package/dist/runtime/reload.d.ts +17 -0
  57. package/dist/runtime/resources.d.ts +24 -0
  58. package/dist/runtime/scopes.d.ts +35 -0
  59. package/dist/runtime/session.d.ts +69 -0
  60. package/dist/state/binding.d.ts +28 -0
  61. package/dist/state/selection.d.ts +21 -0
  62. package/dist/state/types.d.ts +35 -0
  63. package/dist/state.d.ts +2 -0
  64. package/dist/telemetry.d.ts +23 -0
  65. package/dist/telemetry.js +27 -0
  66. package/dist/tooling/build.d.ts +3 -0
  67. package/dist/tooling/index.d.ts +2 -0
  68. package/dist/tooling/index.js +181 -0
  69. package/dist/tooling/resolver.d.ts +5 -0
  70. package/dist/tooling/typecheck.d.ts +2 -0
  71. package/dist/tooling/types.d.ts +29 -0
  72. package/dist/types.d.ts +1 -0
  73. package/dist/values.d.ts +23 -0
  74. package/package.json +103 -4
  75. package/src/authoring/declaration.ts +237 -0
  76. package/src/authoring/hooks.ts +101 -0
  77. package/src/authoring/orb.ts +88 -0
  78. package/src/authoring/service-identities.ts +20 -0
  79. package/src/authoring/services.ts +46 -0
  80. package/src/authoring/types.ts +256 -0
  81. package/src/bridge/identifiers.ts +212 -0
  82. package/src/bridge/kernel.ts +117 -0
  83. package/src/bridge/protocol.ts +193 -0
  84. package/src/browser.ts +59 -0
  85. package/src/codec.ts +1 -0
  86. package/src/codecs/json.ts +147 -0
  87. package/src/codecs/msgpack.ts +26 -0
  88. package/src/context-key.ts +94 -0
  89. package/src/coordinator.ts +1 -0
  90. package/src/embedded.ts +293 -0
  91. package/src/error.ts +50 -0
  92. package/src/errors.ts +237 -0
  93. package/src/hooks.ts +1 -0
  94. package/src/host.ts +173 -0
  95. package/src/identifiers.ts +1 -0
  96. package/src/index.ts +22 -0
  97. package/src/infrastructure/coordinator.ts +76 -0
  98. package/src/infrastructure/manager.ts +77 -0
  99. package/src/infrastructure/rpc/channel.ts +107 -0
  100. package/src/infrastructure/rpc/client.ts +216 -0
  101. package/src/infrastructure/rpc/server.ts +201 -0
  102. package/src/infrastructure/rpc/state.ts +70 -0
  103. package/src/kernel.ts +1 -0
  104. package/src/manager.ts +1 -0
  105. package/src/msgpack.ts +1 -0
  106. package/src/node.ts +53 -0
  107. package/src/orb.ts +1 -0
  108. package/src/protocol.ts +1 -0
  109. package/src/rpc.ts +3 -0
  110. package/src/runtime/activities.ts +197 -0
  111. package/src/runtime/calls.ts +165 -0
  112. package/src/runtime/context.ts +128 -0
  113. package/src/runtime/declaration.ts +1 -0
  114. package/src/runtime/lifecycle.ts +227 -0
  115. package/src/runtime/orbs.ts +292 -0
  116. package/src/runtime/programs.ts +274 -0
  117. package/src/runtime/records.ts +127 -0
  118. package/src/runtime/references.ts +406 -0
  119. package/src/runtime/reload.ts +161 -0
  120. package/src/runtime/resources.ts +157 -0
  121. package/src/runtime/scopes.ts +210 -0
  122. package/src/runtime/session.ts +181 -0
  123. package/src/state/binding.ts +157 -0
  124. package/src/state/selection.ts +122 -0
  125. package/src/state/types.ts +47 -0
  126. package/src/state.ts +2 -0
  127. package/src/telemetry.ts +45 -0
  128. package/src/tooling/build.ts +83 -0
  129. package/src/tooling/index.ts +8 -0
  130. package/src/tooling/resolver.ts +95 -0
  131. package/src/tooling/typecheck.ts +32 -0
  132. package/src/tooling/types.ts +32 -0
  133. package/src/types.ts +1 -0
  134. package/src/values.ts +85 -0
@@ -0,0 +1,107 @@
1
+ import { Code } from "../../bridge/identifiers.ts";
2
+ import { RpcEvent, RpcOp } from "../../bridge/protocol.ts";
3
+ import type { Codec } from "../../codecs/json.ts";
4
+ import { jsonCodec } from "../../codecs/json.ts";
5
+ import { failure, TembraError } from "../../error.ts";
6
+ import { Errors } from "../../errors.ts";
7
+
8
+ /** Adapters for WebSocket, MessagePort, or an application channel implement this byte boundary. */
9
+ export interface Transport {
10
+ /** Send one encoded frame through the application transport. */
11
+ send(frame: Uint8Array): void | Promise<void>;
12
+ /** Register frame and connection callbacks until detached. */
13
+ listen(receive: (frame: Uint8Array) => void, closed: (error?: unknown) => void): () => void;
14
+ /**
15
+ * Close after channel listeners detach, handling or ignoring the supplied terminal cause.
16
+ * Wrap platform methods; do not forward this cause to WebSocket.close(code), destroy(error), or end.
17
+ */
18
+ close(cause?: unknown): void;
19
+ }
20
+ export interface Limits {
21
+ codec?: Codec;
22
+ maxFrame?: number;
23
+ maxPending?: number;
24
+ onError?: (error: unknown) => void;
25
+ }
26
+ export interface Wire {
27
+ id?: number;
28
+ op?: RpcOp;
29
+ payload?: any;
30
+ ok?: any;
31
+ error?: { code: Code; reason: string; message: string };
32
+ event?: RpcEvent;
33
+ }
34
+ /** Produce the portable fields of a structured error. */
35
+ export function errorValue(error: unknown) {
36
+ const value = failure(error);
37
+ return { code: value.code, reason: value.reason, message: value.message };
38
+ }
39
+
40
+ export class Channel {
41
+ readonly codec: Codec;
42
+ readonly maxFrame: number;
43
+ readonly maxPending: number;
44
+ closed = false;
45
+ #detach: () => void;
46
+
47
+ /** Attach the transport with frame limits and the chosen codec. */
48
+ constructor(
49
+ readonly transport: Transport,
50
+ readonly options: Limits,
51
+ receive: (message: Wire) => void,
52
+ readonly ended: (error: unknown) => void,
53
+ ) {
54
+ this.codec = options.codec ?? jsonCodec;
55
+ this.maxFrame = options.maxFrame ?? 1024 * 1024;
56
+ this.maxPending = options.maxPending ?? 128;
57
+ this.#detach = transport.listen(
58
+ (frame) => {
59
+ if (this.closed) return;
60
+ try {
61
+ if (frame.length > this.maxFrame) throw new TembraError(Errors.Exhausted.FrameSize);
62
+ const message = this.codec.deserialize(frame);
63
+ if (!message || typeof message !== "object" || Array.isArray(message))
64
+ throw new TembraError(Errors.Invalid.RpcFrame);
65
+ receive(message);
66
+ } catch (error) {
67
+ this.#report(error);
68
+ this.close(error);
69
+ }
70
+ },
71
+ (error) => this.close(error),
72
+ );
73
+ }
74
+
75
+ /** Report adapter failures without letting a reporter prevent connection cleanup. */
76
+ #report(error: unknown): void {
77
+ try {
78
+ this.options.onError?.(error);
79
+ } catch {}
80
+ }
81
+
82
+ /** Encode and size-check a message before transport delivery. */
83
+ async send(message: Wire): Promise<void> {
84
+ if (this.closed) throw new TembraError(Errors.Gone.Connection);
85
+ const frame = this.codec.serialize(message);
86
+ if (frame.length > this.maxFrame) throw new TembraError(Errors.Exhausted.FrameSize);
87
+ await this.transport.send(frame);
88
+ }
89
+
90
+ /** Detach the transport and reject connection work once. */
91
+ close(error: unknown = new TembraError(Errors.Gone.Connection)): void {
92
+ if (this.closed) return;
93
+ this.closed = true;
94
+ try {
95
+ this.#detach?.();
96
+ } catch (detachError) {
97
+ this.#report(detachError);
98
+ }
99
+ try {
100
+ this.transport.close(error);
101
+ } catch (closeError) {
102
+ this.#report(closeError);
103
+ } finally {
104
+ this.ended(error);
105
+ }
106
+ }
107
+ }
@@ -0,0 +1,216 @@
1
+ import type { DynamicReference } from "../../authoring/types.ts";
2
+ import { Status } from "../../bridge/identifiers.ts";
3
+ import { RpcEvent, RpcOp } from "../../bridge/protocol.ts";
4
+ import { TembraError } from "../../error.ts";
5
+ import { Errors } from "../../errors.ts";
6
+ import type { Context } from "../../runtime/context.ts";
7
+
8
+ import { Channel, type Limits, type Transport } from "./channel.ts";
9
+ import { RemoteState } from "./state.ts";
10
+
11
+ /** A lost connection revokes its references. Reconnect by creating a peer and acquiring current state. */
12
+ export class RemoteHost {
13
+ readonly channel: Channel;
14
+ #next = 0;
15
+ #pending = new Map<
16
+ number,
17
+ {
18
+ /** Deliver the response to its pending caller. */
19
+ resolve(value: any): void;
20
+ /** Reject the caller when its request or connection fails. */
21
+ reject(error: unknown): void;
22
+ }
23
+ >();
24
+ #states = new Map<number, RemoteState>();
25
+
26
+ /** Attach response routing and revoke state on disconnect. */
27
+ constructor(transport: Transport, options: Limits = {}) {
28
+ this.channel = new Channel(
29
+ transport,
30
+ options,
31
+ (message) => {
32
+ if (message.event === RpcEvent.State) {
33
+ this.#states.get(message.payload.reference)?.adopt(message.payload.value);
34
+ return;
35
+ }
36
+ const pending = message.id && this.#pending.get(message.id);
37
+ if (!pending) return;
38
+ this.#pending.delete(message.id!);
39
+ if (message.error) pending.reject(new TembraError(message.error));
40
+ else pending.resolve(message.ok);
41
+ },
42
+ (error) => {
43
+ for (const pending of this.#pending.values()) pending.reject(error);
44
+ this.#pending.clear();
45
+ this.#states.clear();
46
+ },
47
+ );
48
+ }
49
+
50
+ /** Correlate one bounded remote request with optional cancellation. */
51
+ request(op: RpcOp, payload: unknown, signal?: AbortSignal): Promise<any> {
52
+ return this.#request(op, payload, signal);
53
+ }
54
+
55
+ /** Apply a response before resolving its caller so following frames see acquired state. */
56
+ async #request(
57
+ op: RpcOp,
58
+ payload: unknown,
59
+ signal?: AbortSignal,
60
+ received?: (value: any) => void,
61
+ ): Promise<any> {
62
+ signal?.throwIfAborted();
63
+ if (this.#pending.size >= this.channel.maxPending)
64
+ throw new TembraError(Errors.Exhausted.PendingRequests);
65
+ const id = ++this.#next;
66
+ if (!Number.isSafeInteger(id)) throw new TembraError(Errors.Exhausted.RequestIds);
67
+ let abort: (() => void) | undefined;
68
+ const result = new Promise((resolve, reject) => {
69
+ const pending = {
70
+ resolve: (value: any) => {
71
+ try {
72
+ received?.(value);
73
+ resolve(value);
74
+ } catch (error) {
75
+ if (op === RpcOp.Get) this.#release(value?.reference);
76
+ reject(error);
77
+ }
78
+ },
79
+ reject,
80
+ };
81
+ this.#pending.set(id, pending);
82
+ abort = () => {
83
+ if (this.#pending.get(id) !== pending) return;
84
+ if (op === RpcOp.Get) {
85
+ this.#pending.set(id, {
86
+ resolve: (value) => this.#release(value?.reference),
87
+ reject: () => {},
88
+ });
89
+ } else {
90
+ this.#pending.delete(id);
91
+ }
92
+ reject(signal?.reason ?? new TembraError(Errors.Cancelled.Request));
93
+ void this.channel.send({ op: RpcOp.Cancel, payload: { id } }).catch(() => {});
94
+ };
95
+ signal?.addEventListener("abort", abort, { once: true });
96
+ void this.channel.send({ id, op, payload }).catch((error) => {
97
+ if (this.#pending.get(id) !== pending) return;
98
+ this.#pending.delete(id);
99
+ reject(error);
100
+ });
101
+ });
102
+ try {
103
+ return await result;
104
+ } finally {
105
+ if (abort) signal?.removeEventListener("abort", abort);
106
+ }
107
+ }
108
+
109
+ /** Release a late or unusable acquisition within the normal pending-request budget. */
110
+ #release(reference: unknown): void {
111
+ if (!Number.isSafeInteger(reference) || (reference as number) <= 0 || this.channel.closed)
112
+ return;
113
+ void this.request(RpcOp.Release, { reference }).catch((error) => {
114
+ try {
115
+ this.channel.options.onError?.(error);
116
+ } catch {}
117
+ });
118
+ }
119
+
120
+ /** Request remote orb metadata without service activation. */
121
+ installedOrbs(): Promise<unknown> {
122
+ return this.request(RpcOp.Describe, null);
123
+ }
124
+
125
+ /** Acquire a remote reference and its current state snapshot. */
126
+ async get(
127
+ service: string,
128
+ key: string | readonly string[],
129
+ options: { signal?: AbortSignal } = {},
130
+ ): Promise<DynamicReference> {
131
+ let released = false;
132
+ const check = () => {
133
+ if (released) throw new TembraError(Errors.Released.Reference);
134
+ if (this.channel.closed) throw new TembraError(Errors.Gone.Connection);
135
+ };
136
+ let state: RemoteState | undefined;
137
+ const acquired = await this.#request(
138
+ RpcOp.Get,
139
+ { service, key: typeof key === "string" ? [key] : key },
140
+ options.signal,
141
+ (value) => {
142
+ if (
143
+ !value ||
144
+ !Number.isSafeInteger(value.reference) ||
145
+ value.reference <= 0 ||
146
+ !Array.isArray(value.methods) ||
147
+ !value.methods.every((method: unknown) => typeof method === "string")
148
+ )
149
+ throw new TembraError(Errors.Invalid.RpcFrame);
150
+ if (Object.hasOwn(value, "state")) {
151
+ state = new RemoteState(value.state, check, (error) =>
152
+ this.channel.options.onError?.(error),
153
+ );
154
+ this.#states.set(value.reference, state);
155
+ }
156
+ },
157
+ );
158
+ const id = acquired.reference as number;
159
+ const target = {
160
+ ready: Promise.resolve(),
161
+ /** Read connection-aware status without sending a request. */
162
+ get status() {
163
+ return released ? Status.Released : peer.channel.closed ? Status.Gone : Status.Live;
164
+ },
165
+ /** Read the local mirror while the remote reference remains valid. */
166
+ get state() {
167
+ check();
168
+ if (!state) throw new TembraError(Errors.Invalid.State);
169
+ return state;
170
+ },
171
+ /** Release the remote claim once and stop retaining its state. */
172
+ release: () => {
173
+ if (released) return;
174
+ released = true;
175
+ this.#states.delete(id);
176
+ void this.request(RpcOp.Release, { reference: id }).catch((error) =>
177
+ this.channel.options.onError?.(error),
178
+ );
179
+ },
180
+ /** Reject opaque resources that cannot cross the transport. */
181
+ opaque() {
182
+ throw new TembraError(
183
+ Errors.Unsupported.RemoteOpaque,
184
+ "Opaque resources are local to their language environment",
185
+ );
186
+ },
187
+ };
188
+ const peer = this;
189
+ return new Proxy(target, {
190
+ /** Expose only methods included in the acquired remote contract. */
191
+ get: (target, property, receiver) => {
192
+ if (property === "then") return undefined;
193
+ if (Object.hasOwn(target, property)) return Reflect.get(target, property, receiver);
194
+ if (typeof property !== "string" || !acquired.methods.includes(property)) return undefined;
195
+ return async (...arguments_: unknown[]) => {
196
+ check();
197
+ const last = arguments_.at(-1) as Context | undefined;
198
+ const signal =
199
+ last && typeof last.check === "function" && "signal" in last
200
+ ? (arguments_.pop() as Context).signal
201
+ : undefined;
202
+ return this.request(
203
+ RpcOp.Call,
204
+ { reference: id, method: property, arguments: arguments_ },
205
+ signal,
206
+ );
207
+ };
208
+ },
209
+ }) as DynamicReference;
210
+ }
211
+
212
+ /** Close the connection and reject pending requests. */
213
+ close(): void {
214
+ this.channel.close();
215
+ }
216
+ }
@@ -0,0 +1,201 @@
1
+ import type { DynamicReference } from "../../authoring/types.ts";
2
+ import { RpcEvent, RpcOp } from "../../bridge/protocol.ts";
3
+ import { TembraError } from "../../error.ts";
4
+ import { Errors } from "../../errors.ts";
5
+ import type { Host } from "../../host.ts";
6
+ import type { Context } from "../../runtime/context.ts";
7
+
8
+ import { Channel, errorValue, type Limits, type Transport } from "./channel.ts";
9
+
10
+ /** Trusted infrastructure supplies the principal and authorization policy; peers cannot choose it. */
11
+ export function serve(
12
+ host: Host,
13
+ transport: Transport,
14
+ options: Limits & {
15
+ principal: string;
16
+ allow?: (service: string, key: readonly string[]) => boolean;
17
+ },
18
+ ): {
19
+ /** Stop the connection and release its remote claims. */
20
+ close(): void;
21
+ } {
22
+ type Claim = {
23
+ reference: DynamicReference;
24
+ methods: ReadonlySet<string>;
25
+ detach?: () => void;
26
+ pending?: unknown;
27
+ sending: boolean;
28
+ closed: boolean;
29
+ active: boolean;
30
+ };
31
+ const references = new Map<number, Claim>();
32
+ const calls = new Map<number, Context>();
33
+ const requests = new Map<number, { cancelled: boolean }>();
34
+ let next = 0;
35
+ let pending = 0;
36
+ const pump = (reference: number, record: Claim) => {
37
+ if (record.sending || !record.active || record.closed) return;
38
+ record.sending = true;
39
+ void (async () => {
40
+ while (Object.hasOwn(record, "pending") && !record.closed) {
41
+ const value = record.pending;
42
+ delete record.pending;
43
+ await channel.send({ event: RpcEvent.State, payload: { reference, value } });
44
+ }
45
+ })()
46
+ .catch((error) => channel.close(error))
47
+ .finally(() => {
48
+ record.sending = false;
49
+ });
50
+ };
51
+ const channel = new Channel(
52
+ transport,
53
+ options,
54
+ (message) => {
55
+ if (message.op === RpcOp.Cancel) {
56
+ const request = requests.get(message.payload?.id);
57
+ if (request) request.cancelled = true;
58
+ calls.get(message.payload?.id)?.cancel();
59
+ return;
60
+ }
61
+ const id = message.id;
62
+ if (!Number.isSafeInteger(id) || !id || id <= 0 || !message.op) {
63
+ channel.close(new TembraError(Errors.Invalid.RpcRequest));
64
+ return;
65
+ }
66
+ if (pending >= channel.maxPending || requests.has(id)) {
67
+ void channel
68
+ .send({ id, error: errorValue(new TembraError(Errors.Exhausted.PendingRequests)) })
69
+ .catch(() => channel.close());
70
+ return;
71
+ }
72
+ pending++;
73
+ const request = { cancelled: false };
74
+ requests.set(id, request);
75
+ void (async () => {
76
+ const payload = message.payload;
77
+ switch (message.op) {
78
+ case RpcOp.Describe:
79
+ return host.installedOrbs().map(({ describe, ...info }) => info);
80
+ case RpcOp.Get: {
81
+ if (
82
+ typeof payload?.service !== "string" ||
83
+ !Array.isArray(payload.key) ||
84
+ !payload.key.every((key: unknown) => typeof key === "string")
85
+ )
86
+ throw new TembraError(Errors.Invalid.Address);
87
+ if (options.allow && !options.allow(payload.service, payload.key))
88
+ throw new TembraError(Errors.Forbidden.Service);
89
+ if (references.size >= channel.maxPending)
90
+ throw new TembraError(Errors.Exhausted.RemoteReferences);
91
+ const reference = await host.get(payload.service, payload.key, {
92
+ principal: options.principal,
93
+ });
94
+ if (channel.closed || request.cancelled) {
95
+ reference.release();
96
+ throw new TembraError(Errors.Gone.Connection);
97
+ }
98
+ const referenceId = ++next;
99
+ const methods = new Set(host.session.handles.reference(reference).methods);
100
+ const record: Claim = {
101
+ reference,
102
+ methods,
103
+ sending: false,
104
+ closed: false,
105
+ active: false,
106
+ };
107
+ references.set(referenceId, record);
108
+ let snapshot: { state?: unknown } = {};
109
+ try {
110
+ snapshot = { state: reference.state.value };
111
+ let initial = true;
112
+ record.detach = reference.state.subscribe((value) => {
113
+ if (initial) {
114
+ initial = false;
115
+ return;
116
+ }
117
+ record.pending = value;
118
+ pump(referenceId, record);
119
+ });
120
+ } catch {
121
+ /* State is optional; method-only services remain portable. */
122
+ }
123
+ return { reference: referenceId, methods: [...methods], ...snapshot };
124
+ }
125
+ case RpcOp.Release: {
126
+ const record = references.get(payload?.reference);
127
+ if (record) {
128
+ record.closed = true;
129
+ record.detach?.();
130
+ record.reference.release();
131
+ references.delete(payload.reference);
132
+ }
133
+ return null;
134
+ }
135
+ case RpcOp.Call: {
136
+ const record = references.get(payload?.reference);
137
+ if (
138
+ !record ||
139
+ typeof payload.method !== "string" ||
140
+ !record.methods.has(payload.method) ||
141
+ !Array.isArray(payload.arguments) ||
142
+ typeof record.reference[payload.method] !== "function"
143
+ )
144
+ throw new TembraError(Errors.Forbidden.Method);
145
+ if (request.cancelled) throw new TembraError(Errors.Cancelled.Request);
146
+ return host.root(
147
+ async (ctx) => {
148
+ calls.set(id, ctx);
149
+ try {
150
+ return (
151
+ (await record.reference[payload.method](...payload.arguments, ctx)) ?? null
152
+ );
153
+ } finally {
154
+ calls.delete(id);
155
+ }
156
+ },
157
+ { principal: options.principal },
158
+ );
159
+ }
160
+ default:
161
+ throw new TembraError(Errors.Invalid.RpcOperation);
162
+ }
163
+ })()
164
+ .then(
165
+ async (ok) => {
166
+ await channel.send({ id, ok });
167
+ if (message.op === RpcOp.Get) {
168
+ const record = references.get(ok.reference);
169
+ if (record) {
170
+ record.active = true;
171
+ pump(ok.reference, record);
172
+ }
173
+ }
174
+ },
175
+ (error) => channel.send({ id, error: errorValue(error) }),
176
+ )
177
+ .catch((error) => channel.close(error))
178
+ .finally(() => {
179
+ pending--;
180
+ requests.delete(id);
181
+ });
182
+ },
183
+ () => {
184
+ for (const ctx of calls.values()) {
185
+ try {
186
+ ctx.cancel();
187
+ } catch {}
188
+ }
189
+ for (const record of references.values()) {
190
+ record.closed = true;
191
+ record.detach?.();
192
+ record.reference.release();
193
+ }
194
+ references.clear();
195
+ },
196
+ );
197
+ return {
198
+ /** Stop the transport and release its remote claims. */
199
+ close: () => channel.close(),
200
+ };
201
+ }
@@ -0,0 +1,70 @@
1
+ import type { Readable } from "../../state.ts";
2
+ import { protect } from "../../values.ts";
3
+
4
+ export class RemoteState implements Readable<any> {
5
+ #value: any;
6
+ #listeners = new Set<(value: any) => void>();
7
+
8
+ /** Protect the initial remote snapshot and retain its validity check. */
9
+ constructor(
10
+ value: unknown,
11
+ readonly check: () => void,
12
+ readonly report: (error: unknown) => void,
13
+ ) {
14
+ this.#value = protect(value);
15
+ }
16
+
17
+ /** Read the snapshot while the remote reference remains valid. */
18
+ get value(): any {
19
+ this.check();
20
+ return this.#value;
21
+ }
22
+
23
+ /** Publish a protected remote snapshot to local observers. */
24
+ adopt(value: unknown): void {
25
+ this.#value = protect(value);
26
+ for (const listener of this.#listeners) {
27
+ try {
28
+ listener(this.#value);
29
+ } catch (error) {
30
+ this.report(error);
31
+ }
32
+ }
33
+ }
34
+
35
+ /** Deliver the current snapshot, then subsequent updates. */
36
+ subscribe(listener: (value: any) => void): () => void {
37
+ this.check();
38
+ this.#listeners.add(listener);
39
+ listener(this.#value);
40
+ return () => {
41
+ this.#listeners.delete(listener);
42
+ };
43
+ }
44
+
45
+ /** Derive a readable value from the remote state. */
46
+ select<R>(compute: (value: any) => R): Readable<R> {
47
+ const source = this;
48
+ return {
49
+ /** Compute the selected value from the current remote snapshot. */
50
+ get value() {
51
+ return compute(source.value);
52
+ },
53
+ /** Compose another projection over the same remote source. */
54
+ select: (next) => source.select((value) => next(compute(value))),
55
+ /** Notify only when the selected value changes by identity. */
56
+ subscribe(listener) {
57
+ let initial = true;
58
+ let previous: R;
59
+ return source.subscribe((value) => {
60
+ const next = compute(value);
61
+ if (initial || !Object.is(previous, next)) {
62
+ initial = false;
63
+ previous = next;
64
+ listener(next);
65
+ }
66
+ });
67
+ },
68
+ };
69
+ }
70
+ }
package/src/kernel.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./bridge/kernel.ts";
package/src/manager.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./infrastructure/manager.ts";
package/src/msgpack.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./codecs/msgpack.ts";
package/src/node.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { orb } from "./authoring/orb.ts";
5
+ import type { HostOptions } from "./authoring/types.ts";
6
+ import type { KernelPort } from "./bridge/kernel.ts";
7
+ import { Host } from "./host.ts";
8
+
9
+ export type NodeHostOptions = Omit<HostOptions, "kernel"> & { kernel?: KernelPort };
10
+
11
+ /** Uses the existing Node runtime; it never embeds a second JavaScript engine. */
12
+ export function createHost(options: NodeHostOptions = {}): Host {
13
+ const require = createRequire(import.meta.url);
14
+ const binding = options.kernel
15
+ ? undefined
16
+ : (require("@syntropika/tembra-engine-node") as {
17
+ NodeKernel: new () => KernelPort;
18
+ });
19
+ return new Host({
20
+ ...options,
21
+ kernel: options.kernel ?? new binding!.NodeKernel(),
22
+ load:
23
+ options.load ??
24
+ (async (location) => {
25
+ const url =
26
+ location instanceof URL
27
+ ? location
28
+ : /^[a-z]+:/i.test(location)
29
+ ? new URL(location)
30
+ : pathToFileURL(path.resolve(location));
31
+ if (!/\.m?js$/.test(url.pathname)) throw new Error("Load a prebuilt JavaScript orb bundle");
32
+ return orb(
33
+ (await import(url.href)).default as import("./authoring/types.ts").OrbDefinition,
34
+ );
35
+ }),
36
+ });
37
+ }
38
+
39
+ export { orb };
40
+ export type { Host };
41
+
42
+ export {
43
+ Code,
44
+ HookCapability,
45
+ Lifetime,
46
+ Reason,
47
+ ReloadStatus,
48
+ Status,
49
+ } from "./bridge/identifiers.ts";
50
+
51
+ export { Errors, type ErrorDescriptor } from "./errors.ts";
52
+
53
+ export { ContextKey, ContextKind, opaqueFrom, type OpaqueContextValue } from "./context-key.ts";
package/src/orb.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./authoring/orb.ts";
@@ -0,0 +1 @@
1
+ export * from "./bridge/protocol.ts";
package/src/rpc.ts ADDED
@@ -0,0 +1,3 @@
1
+ export type { Limits, Transport } from "./infrastructure/rpc/channel.ts";
2
+ export { RemoteHost } from "./infrastructure/rpc/client.ts";
3
+ export { serve } from "./infrastructure/rpc/server.ts";