@syntropika/tembra-sdk 0.2.1 → 0.3.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 (241) hide show
  1. package/README.md +43 -17
  2. package/dist/authoring/types.d.ts +64 -3
  3. package/dist/authoring/wit.d.ts +6 -0
  4. package/dist/bridge/commands.d.ts +1190 -0
  5. package/dist/bridge/identifiers.d.ts +2 -0
  6. package/dist/bridge/kernel.d.ts +18 -107
  7. package/dist/bridge/protocol.d.ts +3 -138
  8. package/dist/browser.d.ts +14 -1
  9. package/dist/browser.js +141 -3298
  10. package/dist/chunks/browser-b8jamxw2.js +3399 -0
  11. package/dist/chunks/execution-nsqc6nrt.js +1419 -0
  12. package/dist/chunks/index-01zk0xqx.js +160 -0
  13. package/dist/chunks/index-3fjdfdfd.js +152 -0
  14. package/dist/chunks/index-aaymjn7v.js +787 -0
  15. package/dist/chunks/index-c1w7z9hx.js +356 -0
  16. package/dist/chunks/index-h8t0n42q.js +738 -0
  17. package/dist/chunks/index-hfds9mzp.js +308 -0
  18. package/dist/chunks/index-kr4x67wt.js +177 -0
  19. package/dist/chunks/index-kr6bnh34.js +117 -0
  20. package/dist/chunks/index-kyt9dj0a.js +1421 -0
  21. package/dist/chunks/index-n1wxzc9w.js +830 -0
  22. package/dist/chunks/index-pvac426d.js +74 -0
  23. package/dist/chunks/index-smyds5ce.js +3234 -0
  24. package/dist/chunks/index-sse8aapb.js +121 -0
  25. package/dist/chunks/index-v6heph77.js +643 -0
  26. package/dist/chunks/index-xrdvnv37.js +3448 -0
  27. package/dist/chunks/index-za4mg94e.js +26 -0
  28. package/dist/chunks/index-zkqmnjj8.js +167 -0
  29. package/dist/coordinator.js +9 -500
  30. package/dist/error.d.ts +2 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/guest.d.ts +173 -0
  33. package/dist/guest.js +26 -0
  34. package/dist/host.d.ts +36 -30
  35. package/dist/host.js +37 -3276
  36. package/dist/http/bytes.d.ts +8 -0
  37. package/dist/http/events.d.ts +7 -0
  38. package/dist/http.d.ts +45 -0
  39. package/dist/http.js +291 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +49 -862
  42. package/dist/infrastructure/rpc/client.d.ts +2 -1
  43. package/dist/infrastructure/rpc/resources.d.ts +28 -0
  44. package/dist/interpreter/abi.d.ts +54 -0
  45. package/dist/interpreter/acquire.d.ts +18 -0
  46. package/dist/interpreter/browser-network.d.ts +52 -0
  47. package/dist/interpreter/browser-port.d.ts +55 -0
  48. package/dist/interpreter/browser.d.ts +79 -0
  49. package/dist/interpreter/cli.d.ts +5 -0
  50. package/dist/interpreter/codec.d.ts +42 -0
  51. package/dist/interpreter/component/execution.d.ts +42 -0
  52. package/dist/interpreter/component/host.d.ts +69 -0
  53. package/dist/interpreter/component/instance.d.ts +40 -0
  54. package/dist/interpreter/component/kernel.d.ts +120 -0
  55. package/dist/interpreter/component/names.d.ts +5 -0
  56. package/dist/interpreter/component/port.d.ts +85 -0
  57. package/dist/interpreter/component/prepared.d.ts +97 -0
  58. package/dist/interpreter/component/resources.d.ts +45 -0
  59. package/dist/interpreter/component/revision.d.ts +87 -0
  60. package/dist/interpreter/component/scope.d.ts +116 -0
  61. package/dist/interpreter/component/streams.d.ts +28 -0
  62. package/dist/interpreter/component/values.d.ts +79 -0
  63. package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
  64. package/dist/interpreter/component/wasi-host.d.ts +64 -0
  65. package/dist/interpreter/component/wasi-http.d.ts +33 -0
  66. package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
  67. package/dist/interpreter/component/wasi.d.ts +41 -0
  68. package/dist/interpreter/core.d.ts +64 -0
  69. package/dist/interpreter/fetch-http-provider.d.ts +17 -0
  70. package/dist/interpreter/filesystem/contract.d.ts +85 -0
  71. package/dist/interpreter/filesystem/memory.d.ts +3 -0
  72. package/dist/interpreter/filesystem/opfs.d.ts +3 -0
  73. package/dist/interpreter/filesystem/scope.d.ts +35 -0
  74. package/dist/interpreter/filesystem.d.ts +8 -0
  75. package/dist/interpreter/gate.d.ts +6 -0
  76. package/dist/interpreter/host-protocol.d.ts +100 -0
  77. package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
  78. package/dist/interpreter/http-ingress.d.ts +96 -0
  79. package/dist/interpreter/http-provider.d.ts +85 -0
  80. package/dist/interpreter/io.d.ts +20 -0
  81. package/dist/interpreter/mobile.d.ts +149 -0
  82. package/dist/interpreter/native-ingress.d.ts +95 -0
  83. package/dist/interpreter/node-port.d.ts +25 -0
  84. package/dist/interpreter/node.d.ts +36 -0
  85. package/dist/interpreter/revision.d.ts +64 -0
  86. package/dist/interpreter/scope.d.ts +89 -0
  87. package/dist/interpreter/socket-addresses.d.ts +50 -0
  88. package/dist/interpreter/socket-provider.d.ts +110 -0
  89. package/dist/interpreter/standard-cli.d.ts +34 -0
  90. package/dist/interpreter/standard-codec.d.ts +96 -0
  91. package/dist/interpreter/standard-filesystem.d.ts +47 -0
  92. package/dist/interpreter/standard-host.d.ts +71 -0
  93. package/dist/interpreter/standard-http-values.d.ts +159 -0
  94. package/dist/interpreter/standard-http.d.ts +9 -0
  95. package/dist/interpreter/standard-ingress.d.ts +63 -0
  96. package/dist/interpreter/standard-sockets.d.ts +177 -0
  97. package/dist/interpreter/standard-streams.d.ts +218 -0
  98. package/dist/interpreter/standard-system.d.ts +35 -0
  99. package/dist/interpreter/standard-utf8.d.ts +4 -0
  100. package/dist/interpreter/standard.d.ts +18 -0
  101. package/dist/interpreter/types.d.ts +152 -0
  102. package/dist/interpreter/wit-shape.d.ts +92 -0
  103. package/dist/manager.js +5 -332
  104. package/dist/msgpack.js +9 -615
  105. package/dist/node.d.ts +8 -1
  106. package/dist/node.js +248 -3287
  107. package/dist/rpc.js +196 -699
  108. package/dist/runtime/adapters.d.ts +120 -0
  109. package/dist/runtime/adapters.js +38 -0
  110. package/dist/runtime/calls.d.ts +9 -3
  111. package/dist/runtime/lifecycle.d.ts +3 -1
  112. package/dist/runtime/orbs.d.ts +5 -4
  113. package/dist/runtime/references.d.ts +27 -1
  114. package/dist/runtime/reload.d.ts +5 -3
  115. package/dist/runtime/scopes.d.ts +1 -1
  116. package/dist/runtime/signals.d.ts +4 -0
  117. package/dist/runtime/wit-client.d.ts +38 -0
  118. package/dist/telemetry.js +4 -25
  119. package/dist/tooling/build.d.ts +2 -2
  120. package/dist/tooling/client-resources.d.ts +23 -0
  121. package/dist/tooling/client.d.ts +10 -0
  122. package/dist/tooling/component-glue.d.ts +17 -0
  123. package/dist/tooling/component.d.ts +11 -0
  124. package/dist/tooling/index.d.ts +3 -1
  125. package/dist/tooling/index.js +1155 -102
  126. package/dist/tooling/resolver.d.ts +4 -4
  127. package/dist/tooling/typecheck.d.ts +2 -1
  128. package/dist/tooling/types.d.ts +27 -12
  129. package/dist/tooling/wit.d.ts +9 -0
  130. package/dist/wasi/wasi-clocks-types.d.ts +2 -0
  131. package/dist/wasi/wasi-http-client.d.ts +5 -0
  132. package/dist/wasi/wasi-http-types.d.ts +285 -0
  133. package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
  134. package/dist/wasi/wasi-sockets-types.d.ts +146 -0
  135. package/package.json +62 -35
  136. package/src/authoring/declaration.ts +1 -1
  137. package/src/authoring/types.ts +53 -3
  138. package/src/authoring/wit.ts +15 -0
  139. package/src/bridge/commands.ts +1105 -0
  140. package/src/bridge/identifiers.ts +2 -0
  141. package/src/bridge/kernel.ts +56 -98
  142. package/src/bridge/protocol.ts +3 -142
  143. package/src/browser.ts +90 -6
  144. package/src/context-key.ts +4 -7
  145. package/src/error.ts +1 -1
  146. package/src/errors.ts +7 -0
  147. package/src/guest.ts +327 -0
  148. package/src/host.ts +128 -23
  149. package/src/http/bytes.ts +87 -0
  150. package/src/http/events.ts +34 -0
  151. package/src/http.ts +272 -0
  152. package/src/index.ts +3 -0
  153. package/src/infrastructure/rpc/client.ts +136 -17
  154. package/src/infrastructure/rpc/resources.ts +123 -0
  155. package/src/interpreter/abi.ts +69 -0
  156. package/src/interpreter/acquire.ts +58 -0
  157. package/src/interpreter/browser-network.ts +170 -0
  158. package/src/interpreter/browser-port.ts +425 -0
  159. package/src/interpreter/browser.ts +340 -0
  160. package/src/interpreter/cli.ts +30 -0
  161. package/src/interpreter/codec.ts +298 -0
  162. package/src/interpreter/component/execution.ts +264 -0
  163. package/src/interpreter/component/host.ts +409 -0
  164. package/src/interpreter/component/instance.ts +138 -0
  165. package/src/interpreter/component/kernel.ts +611 -0
  166. package/src/interpreter/component/names.ts +13 -0
  167. package/src/interpreter/component/port.ts +598 -0
  168. package/src/interpreter/component/prepared.ts +194 -0
  169. package/src/interpreter/component/resources.ts +345 -0
  170. package/src/interpreter/component/revision.ts +702 -0
  171. package/src/interpreter/component/scope.ts +447 -0
  172. package/src/interpreter/component/streams.ts +180 -0
  173. package/src/interpreter/component/values.ts +254 -0
  174. package/src/interpreter/component/wasi-filesystem.ts +472 -0
  175. package/src/interpreter/component/wasi-host.ts +197 -0
  176. package/src/interpreter/component/wasi-http.ts +939 -0
  177. package/src/interpreter/component/wasi-sockets.ts +958 -0
  178. package/src/interpreter/component/wasi.ts +238 -0
  179. package/src/interpreter/core.ts +386 -0
  180. package/src/interpreter/fetch-http-provider.ts +98 -0
  181. package/src/interpreter/filesystem/contract.ts +138 -0
  182. package/src/interpreter/filesystem/memory.ts +180 -0
  183. package/src/interpreter/filesystem/opfs.ts +294 -0
  184. package/src/interpreter/filesystem/scope.ts +390 -0
  185. package/src/interpreter/filesystem.ts +20 -0
  186. package/src/interpreter/gate.ts +55 -0
  187. package/src/interpreter/host-protocol.ts +242 -0
  188. package/src/interpreter/http-ingress-fetch.ts +133 -0
  189. package/src/interpreter/http-ingress.ts +203 -0
  190. package/src/interpreter/http-provider.ts +105 -0
  191. package/src/interpreter/io.ts +66 -0
  192. package/src/interpreter/mobile.ts +385 -0
  193. package/src/interpreter/native-ingress.ts +550 -0
  194. package/src/interpreter/node-port.ts +218 -0
  195. package/src/interpreter/node.ts +114 -0
  196. package/src/interpreter/revision.ts +450 -0
  197. package/src/interpreter/scope.ts +453 -0
  198. package/src/interpreter/socket-addresses.ts +246 -0
  199. package/src/interpreter/socket-provider.ts +126 -0
  200. package/src/interpreter/standard-cli.ts +184 -0
  201. package/src/interpreter/standard-codec.ts +403 -0
  202. package/src/interpreter/standard-filesystem.ts +545 -0
  203. package/src/interpreter/standard-host.ts +840 -0
  204. package/src/interpreter/standard-http-values.ts +624 -0
  205. package/src/interpreter/standard-http.ts +622 -0
  206. package/src/interpreter/standard-ingress.ts +344 -0
  207. package/src/interpreter/standard-sockets.ts +847 -0
  208. package/src/interpreter/standard-streams.ts +710 -0
  209. package/src/interpreter/standard-system.ts +182 -0
  210. package/src/interpreter/standard-utf8.ts +72 -0
  211. package/src/interpreter/standard.ts +283 -0
  212. package/src/interpreter/types.ts +163 -0
  213. package/src/interpreter/wit-shape.ts +175 -0
  214. package/src/node.ts +43 -14
  215. package/src/runtime/activities.ts +6 -6
  216. package/src/runtime/adapters.ts +314 -0
  217. package/src/runtime/calls.ts +218 -56
  218. package/src/runtime/context.ts +7 -7
  219. package/src/runtime/lifecycle.ts +36 -17
  220. package/src/runtime/orbs.ts +81 -39
  221. package/src/runtime/programs.ts +16 -8
  222. package/src/runtime/references.ts +128 -11
  223. package/src/runtime/reload.ts +71 -30
  224. package/src/runtime/resources.ts +2 -2
  225. package/src/runtime/scopes.ts +17 -17
  226. package/src/runtime/session.ts +3 -1
  227. package/src/runtime/signals.ts +31 -0
  228. package/src/runtime/wit-client.ts +228 -0
  229. package/src/tooling/build.ts +152 -54
  230. package/src/tooling/client-resources.ts +74 -0
  231. package/src/tooling/client.ts +531 -0
  232. package/src/tooling/component-glue.ts +288 -0
  233. package/src/tooling/component.ts +225 -0
  234. package/src/tooling/index.ts +3 -7
  235. package/src/tooling/resolver.ts +42 -25
  236. package/src/tooling/typecheck.ts +59 -4
  237. package/src/tooling/types.ts +27 -12
  238. package/src/tooling/wit.ts +188 -0
  239. package/dist/embedded.d.ts +0 -1
  240. package/dist/embedded.js +0 -1
  241. package/src/embedded.ts +0 -293
package/dist/node.js CHANGED
@@ -1,3336 +1,297 @@
1
+ import {
2
+ Code2,
3
+ Reason2,
4
+ Lifetime2,
5
+ Status2,
6
+ ReloadStatus2,
7
+ HookCapability2,
8
+ Errors2,
9
+ failure
10
+ } from "./chunks/index-c1w7z9hx.js";
11
+ import {
12
+ ContextKind2,
13
+ ContextKey2,
14
+ opaqueFrom2,
15
+ reply,
16
+ refusal
17
+ } from "./chunks/index-kyt9dj0a.js";
18
+ import"./chunks/index-kr4x67wt.js";
19
+ import {
20
+ cliPacket,
21
+ isolate2
22
+ } from "./chunks/index-zkqmnjj8.js";
23
+ import {
24
+ decodeHostRequest,
25
+ decodeAsyncHostRequest,
26
+ Revision,
27
+ ingressPacket,
28
+ NativeIngress,
29
+ Host2
30
+ } from "./chunks/index-xrdvnv37.js";
31
+ import {
32
+ HttpHandlerError2,
33
+ answer,
34
+ query
35
+ } from "./chunks/index-h8t0n42q.js";
36
+ import"./chunks/index-sse8aapb.js";
37
+ import"./chunks/index-za4mg94e.js";
38
+ import {
39
+ orb3
40
+ } from "./chunks/index-01zk0xqx.js";
41
+
1
42
  // src/node.ts
2
- import { createRequire } from "node:module";
43
+ import { createRequire as createRequire2 } from "node:module";
3
44
  import path from "node:path";
4
45
  import { pathToFileURL } from "node:url";
5
-
6
- // src/bridge/identifiers.ts
7
- var Code = Object.freeze({
8
- Invalid: "invalid",
9
- Unavailable: "unavailable",
10
- Released: "released",
11
- Gone: "gone",
12
- Expired: "expired",
13
- Cancelled: "cancelled",
14
- Forbidden: "forbidden",
15
- Conflict: "conflict",
16
- Unsupported: "unsupported",
17
- Closed: "closed",
18
- Exhausted: "exhausted"
19
- });
20
- var Reason = Object.freeze({
21
- ActivationBusy: "activation_busy",
22
- Address: "address",
23
- AlreadyCommitted: "already_committed",
24
- AmbiguousScope: "ambiguous_scope",
25
- ApiVersion: "api_version",
26
- Arguments: "arguments",
27
- AsyncFactory: "async_factory",
28
- AsyncState: "async_state",
29
- Bigint: "bigint",
30
- ByteResult: "byte_result",
31
- Call: "call",
32
- Callback: "callback",
33
- CleanupBusy: "cleanup_busy",
34
- Clock: "clock",
35
- Codec: "codec",
36
- Connection: "connection",
37
- Context: "context",
38
- Contribution: "contribution",
39
- CoordinationLimits: "coordination_limits",
40
- Deadline: "deadline",
41
- Dependency: "dependency",
42
- DependencyCycle: "dependency_cycle",
43
- DependencyService: "dependency_service",
44
- Disposing: "disposing",
45
- Driver: "driver",
46
- Duplicate: "duplicate",
47
- DuplicateContribution: "duplicate_contribution",
48
- DuplicateListener: "duplicate_listener",
49
- DuplicateResource: "duplicate_resource",
50
- DuplicateService: "duplicate_service",
51
- EffectResults: "effect_results",
52
- EffectsRunning: "effects_running",
53
- EngineEffect: "engine_effect",
54
- EventSource: "event_source",
55
- ExclusiveDependent: "exclusive_dependent",
56
- Executor: "executor",
57
- Orb: "orb",
58
- OrbGone: "orb_gone",
59
- OrbInstalled: "orb_installed",
60
- OrbScope: "orb_scope",
61
- Factory: "factory",
62
- FactoryExpired: "factory_expired",
63
- FrameSize: "frame_size",
64
- GateBusy: "gate_busy",
65
- GateOrb: "gate_orb",
66
- GateObject: "gate_object",
67
- Hook: "hook",
68
- HookDependency: "hook_dependency",
69
- Hooks: "hooks",
70
- HooksDisabled: "hooks_disabled",
71
- Host: "host",
72
- HostAddress: "host_address",
73
- HostResource: "host_resource",
74
- HostResourceReload: "host_resource_reload",
75
- Identities: "identities",
76
- Implementation: "implementation",
77
- Invocation: "invocation",
78
- Javascript: "javascript",
79
- JsonAccessor: "json_accessor",
80
- JsonCycle: "json_cycle",
81
- JsonNumber: "json_number",
82
- JsonSymbol: "json_symbol",
83
- JsonTag: "json_tag",
84
- JsonType: "json_type",
85
- JsonValue: "json_value",
86
- Lifetime: "lifetime",
87
- Linger: "linger",
88
- ListenerCallback: "listener_callback",
89
- LiveConsumer: "live_consumer",
90
- LiveReference: "live_reference",
91
- LocalValue: "local_value",
92
- Memory: "memory",
93
- Metadata: "metadata",
94
- MetadataSize: "metadata_size",
95
- Method: "method",
96
- MigrationGate: "migration_gate",
97
- MigrationRequired: "migration_required",
98
- MigrationValue: "migration_value",
99
- MissingHook: "missing_hook",
100
- MissingMethod: "missing_method",
101
- NativeEffect: "native_effect",
102
- NativeMethod: "native_method",
103
- NativeObject: "native_object",
104
- NativeService: "native_service",
105
- Next: "next",
106
- NextUsed: "next_used",
107
- NotReady: "not_ready",
108
- Object: "object",
109
- ObjectState: "object_state",
110
- ObservationSource: "observation_source",
111
- ObservationAdmitted: "observation_admitted",
112
- Opaque: "opaque",
113
- Operation: "operation",
114
- OperationOwner: "operation_owner",
115
- Owner: "owner",
116
- Payload: "payload",
117
- PendingRequests: "pending_requests",
118
- PrepareDeadline: "prepare_deadline",
119
- Priority: "priority",
120
- Program: "program",
121
- ProgramPhase: "program_phase",
122
- ProgramRunning: "program_running",
123
- Reference: "reference",
124
- ReloadAborted: "reload_aborted",
125
- ReloadDeadline: "reload_deadline",
126
- ReloadPreparing: "reload_preparing",
127
- ReloadRunning: "reload_running",
128
- ReloadTicket: "reload_ticket",
129
- RemoteOpaque: "remote_opaque",
130
- RemoteReferences: "remote_references",
131
- Request: "request",
132
- RequestIds: "request_ids",
133
- Requires: "requires",
134
- Resource: "resource",
135
- ResourceDependencies: "resource_dependencies",
136
- ResourceDependency: "resource_dependency",
137
- ResourceHost: "resource_host",
138
- ResourceInFactory: "resource_in_factory",
139
- ResourceState: "resource_state",
140
- ResourceVersion: "resource_version",
141
- Result: "result",
142
- RetainedVersions: "retained_versions",
143
- RevisionExhausted: "revision_exhausted",
144
- Root: "root",
145
- Route: "route",
146
- RpcFrame: "rpc_frame",
147
- RpcOperation: "rpc_operation",
148
- RpcRequest: "rpc_request",
149
- RustType: "rust_type",
150
- Scope: "scope",
151
- ScopeClosed: "scope_closed",
152
- ScopeOrb: "scope_orb",
153
- ScopeOwner: "scope_owner",
154
- ScopeResource: "scope_resource",
155
- Serialization: "serialization",
156
- Service: "service",
157
- ServiceGone: "service_gone",
158
- State: "state",
159
- StateCycle: "state_cycle",
160
- StateInitialized: "state_initialized",
161
- StateOwner: "state_owner",
162
- StateRevision: "state_revision",
163
- StateValidation: "state_validation",
164
- StateValue: "state_value",
165
- StateVersion: "state_version",
166
- Subscription: "subscription",
167
- SubscriptionBusy: "subscription_busy",
168
- SubscriptionIdle: "subscription_idle",
169
- SubscriptionQueue: "subscription_queue",
170
- SubscriptionSize: "subscription_size",
171
- SubscriptionsDisabled: "subscriptions_disabled",
172
- Superseded: "superseded",
173
- Task: "task",
174
- Telemetry: "telemetry",
175
- UndeclaredDependency: "undeclared_dependency",
176
- UndeclaredService: "undeclared_service",
177
- UnknownService: "unknown_service",
178
- UpgradeConflict: "upgrade_conflict",
179
- Utf8: "utf8",
180
- Value: "value",
181
- ValueGone: "value_gone",
182
- ValuesExhausted: "values_exhausted",
183
- Views: "views"
184
- });
185
- var Lifetime = Object.freeze({
186
- Referenced: "referenced",
187
- Host: "host"
188
- });
189
- var Status = Object.freeze({
190
- Loading: "loading",
191
- Live: "live",
192
- Released: "released",
193
- Gone: "gone"
194
- });
195
- var ReloadStatus = Object.freeze({
196
- Prepared: "prepared",
197
- Committed: "committed",
198
- Aborted: "aborted"
199
- });
200
- var HookCapability = Object.freeze({
201
- Observe: "observe",
202
- Transform: "transform",
203
- Decide: "decide"
204
- });
205
-
206
- // src/errors.ts
207
- function define(code, reason, message) {
208
- return Object.freeze({ code, reason, message });
209
- }
210
- var Errors = Object.freeze({
211
- Cancelled: Object.freeze({
212
- EngineEffect: define(Code.Cancelled, Reason.EngineEffect, "The engine effect was cancelled"),
213
- Request: define(Code.Cancelled, Reason.Request, "The request was cancelled"),
214
- Resource: define(Code.Cancelled, Reason.Resource, "Resource opening was cancelled"),
215
- Root: define(Code.Cancelled, Reason.Root, "The operation was cancelled"),
216
- Task: define(Code.Cancelled, Reason.Task, "The task was cancelled")
217
- }),
218
- Closed: Object.freeze({
219
- Host: define(Code.Closed, Reason.Host, "The host is closing")
220
- }),
221
- Conflict: Object.freeze({
222
- AlreadyCommitted: define(Code.Conflict, Reason.AlreadyCommitted, "The replacement is already committed"),
223
- Codec: define(Code.Conflict, Reason.Codec, "The Rust and JS host codecs must agree"),
224
- PrepareDeadline: define(Code.Conflict, Reason.PrepareDeadline, "The preparation deadline expired"),
225
- ReloadRunning: define(Code.Conflict, Reason.ReloadRunning, "A replacement is already running"),
226
- ReloadTicket: define(Code.Conflict, Reason.ReloadTicket, "The replacement is no longer prepared")
227
- }),
228
- Exhausted: Object.freeze({
229
- FrameSize: define(Code.Exhausted, Reason.FrameSize, "The frame exceeds the configured size limit"),
230
- PendingRequests: define(Code.Exhausted, Reason.PendingRequests, "The pending request limit was reached"),
231
- RemoteReferences: define(Code.Exhausted, Reason.RemoteReferences, "The remote reference limit was reached"),
232
- RequestIds: define(Code.Exhausted, Reason.RequestIds, "Request identities are exhausted"),
233
- SubscriptionQueue: define(Code.Exhausted, Reason.SubscriptionQueue, "The subscription queue is full")
234
- }),
235
- Expired: Object.freeze({
236
- Next: define(Code.Expired, Reason.Next, "Continuation scope has ended")
237
- }),
238
- Forbidden: Object.freeze({
239
- Context: define(Code.Forbidden, Reason.Context, "An issued context from this host is required"),
240
- HostResource: define(Code.Forbidden, Reason.HostResource, "The host resource was not declared"),
241
- Method: define(Code.Forbidden, Reason.Method, "The method is not allowed by this reference"),
242
- ObservationSource: define(Code.Forbidden, Reason.ObservationSource, "Hook observation requires the original physical invocation"),
243
- Opaque: define(Code.Forbidden, Reason.Opaque, "The resource is not available as an opaque local value"),
244
- Service: define(Code.Forbidden, Reason.Service, "Access to this service is forbidden"),
245
- StateOwner: define(Code.Forbidden, Reason.StateOwner, "Only the owning orb may change this state"),
246
- UndeclaredDependency: define(Code.Forbidden, Reason.UndeclaredDependency, "The dependency was not declared"),
247
- UndeclaredService: define(Code.Forbidden, Reason.UndeclaredService, "The service was not declared as a dependency")
248
- }),
249
- Gone: Object.freeze({
250
- Connection: define(Code.Gone, Reason.Connection, "The connection is closed"),
251
- Contribution: define(Code.Gone, Reason.Contribution, "The contribution is no longer available"),
252
- Implementation: define(Code.Gone, Reason.Implementation, "The implementation is no longer available"),
253
- ListenerCallback: define(Code.Gone, Reason.ListenerCallback, "The listener callback is no longer available"),
254
- Reference: define(Code.Gone, Reason.Reference, "The reference is no longer available"),
255
- Resource: define(Code.Gone, Reason.Resource, "The resource is no longer available"),
256
- Scope: define(Code.Gone, Reason.Scope, "The declaration scope is no longer available"),
257
- State: define(Code.Gone, Reason.State, "State owner is gone")
258
- }),
259
- Invalid: Object.freeze({
260
- Address: define(Code.Invalid, Reason.Address, "Invalid address"),
261
- AsyncFactory: define(Code.Invalid, Reason.AsyncFactory, "Factories must be synchronous"),
262
- AsyncState: define(Code.Invalid, Reason.AsyncState, "State updates and migrations must be synchronous"),
263
- CoordinationLimits: define(Code.Invalid, Reason.CoordinationLimits, "Invalid coordination limits"),
264
- DependencyCycle: define(Code.Invalid, Reason.DependencyCycle, "Orb factories cannot acquire their own services"),
265
- DependencyService: define(Code.Invalid, Reason.DependencyService, "Invalid dependency service"),
266
- DuplicateListener: define(Code.Invalid, Reason.DuplicateListener, "Invalid duplicate listener"),
267
- DuplicateResource: define(Code.Invalid, Reason.DuplicateResource, "Invalid duplicate resource"),
268
- EventSource: define(Code.Invalid, Reason.EventSource, "Invalid event source"),
269
- Orb: define(Code.Invalid, Reason.Orb, "An orb needs a name and positive API version"),
270
- OrbGone: define(Code.Invalid, Reason.OrbGone, "Invalid orb gone"),
271
- OrbInstalled: define(Code.Invalid, Reason.OrbInstalled, "Use reload to replace an installed orb"),
272
- Factory: define(Code.Invalid, Reason.Factory, "Invalid factory"),
273
- FactoryExpired: define(Code.Invalid, Reason.FactoryExpired, "Declarations must be synchronous"),
274
- Hook: define(Code.Invalid, Reason.Hook, "Hooks need a run function"),
275
- HookDependency: define(Code.Invalid, Reason.HookDependency, "Invalid hook dependency"),
276
- HooksDisabled: define(Code.Invalid, Reason.HooksDisabled, "Invalid hooks disabled"),
277
- JsonAccessor: define(Code.Invalid, Reason.JsonAccessor, "Invalid json accessor"),
278
- JsonCycle: define(Code.Invalid, Reason.JsonCycle, "Invalid json cycle"),
279
- JsonNumber: define(Code.Invalid, Reason.JsonNumber, "Use BigInt for integers outside the safe Number range"),
280
- JsonSymbol: define(Code.Invalid, Reason.JsonSymbol, "Invalid json symbol"),
281
- JsonTag: define(Code.Invalid, Reason.JsonTag, "Unknown or malformed portable type tag"),
282
- JsonType: define(Code.Invalid, Reason.JsonType, "Supply a codec for custom object types"),
283
- JsonValue: define(Code.Invalid, Reason.JsonValue, "This JSON codec requires explicit portable values"),
284
- Method: define(Code.Invalid, Reason.Method, "Methods must be functions"),
285
- NextUsed: define(Code.Invalid, Reason.NextUsed, "Invalid next used"),
286
- Priority: define(Code.Invalid, Reason.Priority, "Invalid priority"),
287
- Reference: define(Code.Invalid, Reason.Reference, "An issued local reference is required"),
288
- Resource: define(Code.Invalid, Reason.Resource, "Invalid resource"),
289
- ResourceHost: define(Code.Invalid, Reason.ResourceHost, "Resource dependencies must belong to the same host"),
290
- ResourceInFactory: define(Code.Invalid, Reason.ResourceInFactory, "Resources open after declaration"),
291
- RpcFrame: define(Code.Invalid, Reason.RpcFrame, "Invalid rpc frame"),
292
- RpcOperation: define(Code.Invalid, Reason.RpcOperation, "Invalid rpc operation"),
293
- RpcRequest: define(Code.Invalid, Reason.RpcRequest, "Invalid rpc request"),
294
- Service: define(Code.Invalid, Reason.Service, "Invalid service"),
295
- ServiceGone: define(Code.Invalid, Reason.ServiceGone, "Invalid service gone"),
296
- State: define(Code.Invalid, Reason.State, "Service does not expose state"),
297
- StateCycle: define(Code.Invalid, Reason.StateCycle, "State cannot contain cycles"),
298
- StateValidation: define(Code.Invalid, Reason.StateValidation, "The orb rejected the state candidate"),
299
- StateValue: define(Code.Invalid, Reason.StateValue, "State cannot contain accessors"),
300
- StateVersion: define(Code.Invalid, Reason.StateVersion, "Invalid state version"),
301
- SubscriptionsDisabled: define(Code.Invalid, Reason.SubscriptionsDisabled, "Invalid subscriptions disabled"),
302
- SubscriptionSize: define(Code.Invalid, Reason.SubscriptionSize, "A local byte budget requires an explicit sizeOf function"),
303
- Task: define(Code.Invalid, Reason.Task, "Invalid task"),
304
- Utf8: define(Code.Invalid, Reason.Utf8, "Invalid utf8"),
305
- ValueGone: define(Code.Invalid, Reason.ValueGone, "Invalid value gone"),
306
- ValuesExhausted: define(Code.Invalid, Reason.ValuesExhausted, "Invalid values exhausted")
307
- }),
308
- Released: Object.freeze({
309
- Reference: define(Code.Released, Reason.Reference, "The reference has been released")
310
- }),
311
- Unavailable: Object.freeze({
312
- Callback: define(Code.Unavailable, Reason.Callback, "A callback failed"),
313
- OrbScope: define(Code.Unavailable, Reason.OrbScope, "The orb scope is unavailable"),
314
- NotReady: define(Code.Unavailable, Reason.NotReady, "The object is not ready"),
315
- Route: define(Code.Unavailable, Reason.Route, "The route is unavailable")
316
- }),
317
- Unsupported: Object.freeze({
318
- EngineEffect: define(Code.Unsupported, Reason.EngineEffect, "The engine effect is not supported by this adapter"),
319
- RemoteOpaque: define(Code.Unsupported, Reason.RemoteOpaque, "Opaque resources are local to their language environment"),
320
- Telemetry: define(Code.Unsupported, Reason.Telemetry, "Telemetry is disabled in this kernel"),
321
- Views: define(Code.Unsupported, Reason.Views, "Reference views are disabled in this kernel")
322
- })
323
- });
324
-
325
- // src/error.ts
326
- var codes = new Set(Object.values(Code));
327
- function isDescriptor(value) {
328
- return typeof value === "object" && value !== null && "code" in value && codes.has(value.code) && "reason" in value && typeof value.reason === "string" && "message" in value && typeof value.message === "string";
329
- }
330
-
331
- class TembraError extends Error {
332
- code;
333
- reason;
334
- constructor(error, message = error.message, options) {
335
- super(message, options);
336
- this.name = "TembraError";
337
- this.code = error.code;
338
- this.reason = error.reason;
339
- }
340
- }
341
- function failure(error) {
342
- let message = Errors.Unavailable.Callback.message;
343
- try {
344
- if (error instanceof TembraError)
345
- return error;
346
- if (isDescriptor(error))
347
- return new TembraError(error, error.message, { cause: error });
348
- message = String(error instanceof Error ? error.message : error);
349
- } catch {}
350
- return new TembraError(Errors.Unavailable.Callback, message, { cause: error });
351
- }
352
- function refuse(error, message = error.message) {
353
- throw new TembraError(error, message);
354
- }
355
-
356
- // src/authoring/service-identities.ts
357
- var identityKey = Symbol.for("@syntropika/tembra-sdk/service-identities");
358
- var existing = Object.getOwnPropertyDescriptor(globalThis, identityKey)?.value;
359
- if (existing !== undefined && !(existing instanceof WeakMap))
360
- throw new TypeError("The SDK service identity slot must contain a WeakMap");
361
- var serviceIdentities = existing instanceof WeakMap ? existing : new WeakMap;
362
- if (existing === undefined)
363
- Object.defineProperty(globalThis, identityKey, { value: serviceIdentities });
364
-
365
- // src/authoring/services.ts
366
- function associateServices(orb, apiVersion, services) {
367
- const pending = new Map;
368
- for (const [name, original, captured] of services) {
369
- const identity = { orb, name, apiVersion };
370
- for (const definition of [original, captured]) {
371
- const previous = pending.get(definition) ?? serviceIdentities.get(definition);
372
- if (previous && (previous.orb !== orb || previous.name !== name || previous.apiVersion !== apiVersion))
373
- refuse(Errors.Invalid.Service, "A service definition must have one orb, name and API version");
374
- pending.set(definition, identity);
375
- }
376
- }
377
- for (const [definition, identity] of pending)
378
- serviceIdentities.set(definition, identity);
379
- }
380
- function serviceAcquisition(service, options = {}) {
381
- if (typeof service === "string")
382
- return { name: service, options };
383
- const identity = serviceIdentities.get(service);
384
- if (!identity)
385
- refuse(Errors.Invalid.Service, "Declare this service in an orb before acquiring it");
386
- if (options.apiVersion !== undefined && options.apiVersion !== identity.apiVersion)
387
- refuse(Errors.Invalid.Service, "The acquisition API version must match the service declaration");
388
- return { name: identity.name, options: { ...options, apiVersion: identity.apiVersion } };
389
- }
390
-
391
- // src/authoring/orb.ts
392
- function orb(definition) {
393
- if (!definition.name || !Number.isInteger(definition.apiVersion) || definition.apiVersion <= 0)
394
- refuse(Errors.Invalid.Orb, "An orb needs a name and positive API version");
395
- const services = Object.fromEntries(Object.entries(definition.services ?? {}).map(([name, service]) => {
396
- if (!name || !service.methods || typeof service.methods !== "object")
397
- refuse(Errors.Invalid.Service);
398
- if (service.create && typeof service.create !== "function")
399
- refuse(Errors.Invalid.Factory);
400
- for (const handler of Object.values(service.methods)) {
401
- if (typeof handler !== "function")
402
- refuse(Errors.Invalid.Method, "Methods must be functions");
403
- }
404
- const copy = {
405
- ...service,
406
- methods: Object.freeze({ ...service.methods })
407
- };
408
- return [name, Object.freeze(copy)];
409
- }));
410
- const requires = Object.fromEntries(Object.entries(definition.requires ?? {}).map(([name, requirement]) => [
411
- name,
412
- Object.freeze({
413
- ...requirement,
414
- ...requirement.methods ? { methods: Object.freeze([...requirement.methods]) } : {},
415
- ...requirement.hooks ? { hooks: Object.freeze([...requirement.hooks]) } : {},
416
- ...requirement.services ? {
417
- services: Object.freeze(Object.fromEntries(Object.entries(requirement.services).map(([name, methods]) => [
418
- name,
419
- Object.freeze([...methods])
420
- ])))
421
- } : {}
422
- })
423
- ]));
424
- const hooks = Object.fromEntries(Object.entries(definition.hooks ?? {}).map(([name, hook]) => {
425
- if (typeof hook.run !== "function")
426
- refuse(Errors.Invalid.Hook, "Hooks need a run function");
427
- return [
428
- name,
429
- Object.freeze({ ...hook, capabilities: Object.freeze([...hook.capabilities ?? []]) })
430
- ];
431
- }));
432
- const contributes = Object.fromEntries(Object.entries(definition.contributes ?? {}).map(([alias, hooks]) => [
433
- alias,
434
- Object.freeze(Object.fromEntries(Object.entries(hooks).map(([name, contribution]) => [
435
- name,
436
- typeof contribution === "function" ? contribution : Object.freeze({ ...contribution })
437
- ])))
438
- ]));
439
- const captured = Object.freeze({
440
- ...definition,
441
- services: Object.freeze(services),
442
- requires: Object.freeze(requires),
443
- hooks: Object.freeze(hooks),
444
- contributes: Object.freeze(contributes)
445
- });
446
- associateServices(definition.name, definition.apiVersion, Object.entries(definition.services ?? {}).map(([name, original]) => [
447
- name,
448
- original,
449
- services[name]
450
- ]));
451
- return captured;
452
- }
453
-
454
- // src/bridge/protocol.ts
455
- var KernelOp = Object.freeze({
456
- ContextDerive: "context-derive",
457
- ContextValue: "context-value",
458
- ContextStats: "context-stats",
459
- Allocate: "allocate",
460
- ScopeRegister: "scope-register",
461
- ScopeExists: "scope-exists",
462
- ScopesForOwner: "scopes-for-owner",
463
- ScopesForOrb: "scopes-for-orb",
464
- ScopeAddResource: "scope-add-resource",
465
- ScopeActivate: "scope-activate",
466
- ScopesCleanup: "scopes-cleanup",
467
- ScopesReloadRegistered: "scopes-reload-registered",
468
- ScopesReload: "scopes-reload",
469
- ProgramRun: "program-run",
470
- ProgramNext: "program-next",
471
- ProgramCompleteStep: "program-complete-step",
472
- ProgramCommit: "program-commit",
473
- ProgramAbort: "program-abort",
474
- ProgramForget: "program-forget",
475
- Features: "features",
476
- Prepare: "prepare",
477
- Gate: "gate",
478
- GateOrbs: "gate-orbs",
479
- Commit: "commit",
480
- Abort: "abort",
481
- Orbs: "orbs",
482
- Orb: "orb",
483
- OrbNamed: "orb-named",
484
- NextDeadline: "next-deadline",
485
- Address: "address",
486
- Acquire: "acquire",
487
- Ready: "ready",
488
- Dependency: "dependency",
489
- Undepend: "undepend",
490
- Fail: "fail",
491
- Status: "status",
492
- Release: "release",
493
- Forget: "forget",
494
- Root: "root",
495
- CleanupRoot: "cleanup-root",
496
- RootPrincipal: "root-principal",
497
- CheckContext: "check-context",
498
- CheckRoot: "check-root",
499
- EndRoot: "end-root",
500
- CancelRoot: "cancel-root",
501
- BeginCall: "begin-call",
502
- BeginOperation: "begin-operation",
503
- BeginHookObservation: "begin-hook-observation",
504
- FinishCall: "finish-call",
505
- Invocation: "invocation",
506
- StateInit: "state-init",
507
- Snapshot: "snapshot",
508
- StateAdopt: "state-adopt",
509
- Task: "task",
510
- TaskRoot: "task-root",
511
- StopTask: "stop-task",
512
- FinishTask: "finish-task",
513
- Resource: "resource",
514
- ResourceOpened: "resource-opened",
515
- ResourceValue: "resource-value",
516
- CloseResource: "close-resource",
517
- ResourceClosed: "resource-closed",
518
- Disposed: "disposed",
519
- Tick: "tick",
520
- NextWake: "next-wake",
521
- NextIdle: "next-idle",
522
- Close: "close",
523
- FinishClose: "finish-close",
524
- Diagnostics: "diagnostics",
525
- Drain: "drain",
526
- Restrict: "restrict",
527
- Contribute: "contribute",
528
- ContributionOrdinal: "contribution-ordinal",
529
- HookPlan: "hook-plan",
530
- Listen: "listen",
531
- Subscribe: "subscribe",
532
- Enqueue: "enqueue",
533
- NextDelivery: "next-delivery",
534
- FinishDelivery: "finish-delivery",
535
- Unsubscribe: "unsubscribe"
536
- });
537
- var ActionType = Object.freeze({
538
- Execute: "execute",
539
- CancelEffects: "cancel-effects",
540
- ProgramPrepared: "program-prepared",
541
- ProgramComplete: "program-complete",
542
- Dispose: "dispose",
543
- CloseResource: "close-resource",
544
- DropValue: "drop-value",
545
- CancelRoot: "cancel-root",
546
- CancelTask: "cancel-task",
547
- RetireOrb: "retire-orb",
548
- State: "state",
549
- SubscriptionFailed: "subscription-failed",
550
- DetachSubscription: "detach-subscription",
551
- Deliver: "deliver"
552
- });
553
- var EffectType = Object.freeze({
554
- Stop: "stop",
555
- Open: "open",
556
- Close: "close",
557
- Restore: "restore",
558
- Prepare: "prepare",
559
- Validate: "validate",
560
- Initialize: "initialize",
561
- Migrate: "migrate",
562
- Adopt: "adopt",
563
- Start: "start",
564
- Drop: "drop"
565
- });
566
- var StepType = Object.freeze({
567
- Execute: "execute",
568
- Wait: "wait",
569
- Prepared: "prepared",
570
- Complete: "complete",
571
- Failed: "failed"
572
- });
573
- var NativeOp = Object.freeze({
574
- Activate: "activate",
575
- Dispose: "dispose",
576
- CancelEffect: "cancel-effect",
577
- Effect: "effect",
578
- Invoke: "invoke",
579
- Contribute: "contribute"
580
- });
581
- var RpcOp = Object.freeze({
582
- Describe: "describe",
583
- Get: "get",
584
- Release: "release",
585
- Call: "call",
586
- Cancel: "cancel"
587
- });
588
- var RpcEvent = Object.freeze({
589
- State: "state"
590
- });
591
- var OwnerKind = Object.freeze({
592
- Host: "host",
593
- Orb: "orb",
594
- Object: "object"
595
- });
596
- var EnvironmentPhase = Object.freeze({
597
- Declaring: "declaring",
598
- Prepared: "prepared",
599
- Live: "live",
600
- Closed: "closed"
601
- });
602
- var CoordinationDecision = Object.freeze({
603
- Preparing: "preparing",
604
- Commit: "commit",
605
- Abort: "abort"
606
- });
607
- var Outcome = Object.freeze({
608
- Ok: "ok",
609
- Error: "error"
610
- });
611
- var CodecTag = Object.freeze({
612
- Bigint: "bigint",
613
- Bytes: "bytes",
614
- Object: "object"
615
- });
616
- var CodecId = Object.freeze({
617
- Json: "tembra-json/1",
618
- MessagePack: "tembra-msgpack/1"
619
- });
620
-
621
- // src/values.ts
622
- class Values {
623
- allocate;
624
- #next = 1;
625
- #values = new Map;
626
- constructor(allocate) {
627
- this.allocate = allocate;
628
- }
629
- put(value) {
630
- if (this.#next > 4294967295)
631
- refuse(Errors.Invalid.ValuesExhausted);
632
- const id = this.allocate ? this.allocate() : this.#next++;
633
- this.#values.set(id, value);
634
- return id;
635
- }
636
- get(id) {
637
- if (!this.#values.has(id))
638
- refuse(Errors.Invalid.ValueGone);
639
- return this.#values.get(id);
640
- }
641
- drop(id) {
642
- this.#values.delete(id);
643
- }
644
- has(id) {
645
- return this.#values.has(id);
646
- }
647
- set(id, value) {
648
- this.#values.set(id, value);
649
- }
650
- clear() {
651
- this.#values.clear();
652
- }
653
- get size() {
654
- return this.#values.size;
655
- }
656
- }
657
- var protectedValues = new WeakSet;
658
- function protect(value) {
659
- const visiting = new WeakSet;
660
- function visit(value) {
661
- if (value === null || typeof value !== "object") {
662
- if (["function", "symbol"].includes(typeof value))
663
- refuse(Errors.Invalid.StateValue, "State must contain plain data");
664
- return;
665
- }
666
- if (protectedValues.has(value))
667
- return;
668
- if (visiting.has(value))
669
- refuse(Errors.Invalid.StateCycle, "State cannot contain cycles");
670
- const proto = Object.getPrototypeOf(value);
671
- if (!Array.isArray(value) && proto !== Object.prototype && proto !== null)
672
- refuse(Errors.Invalid.StateValue, "State requires plain objects and arrays");
673
- visiting.add(value);
674
- for (const key of Reflect.ownKeys(value)) {
675
- if (typeof key !== "string")
676
- refuse(Errors.Invalid.StateValue, "State cannot contain symbol properties");
677
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
678
- if (!Object.hasOwn(descriptor, "value"))
679
- refuse(Errors.Invalid.StateValue, "State cannot contain accessors");
680
- visit(descriptor.value);
681
- }
682
- visiting.delete(value);
683
- Object.freeze(value);
684
- protectedValues.add(value);
685
- }
686
- visit(value);
687
- return value;
688
- }
689
-
690
- // src/state/selection.ts
691
- class Selection {
692
- compute;
693
- report;
694
- check;
695
- #value;
696
- #listeners = new Set;
697
- #children = new Set;
698
- #active = true;
699
- #cleanups;
700
- #cleanup;
701
- #remove;
702
- constructor(compute, value, report, check) {
703
- this.compute = compute;
704
- this.report = report;
705
- this.check = check;
706
- this.#value = protect(compute(value));
707
- }
708
- get value() {
709
- this.check();
710
- return this.#value;
711
- }
712
- track(cleanups, remove) {
713
- this.#cleanups = cleanups;
714
- this.#remove = remove;
715
- const weak = new WeakRef(this);
716
- this.#cleanup = () => weak.deref()?.detach();
717
- cleanups?.add(this.#cleanup);
718
- }
719
- detach() {
720
- if (!this.#active)
721
- return;
722
- this.#active = false;
723
- if (this.#cleanup)
724
- this.#cleanups?.delete(this.#cleanup);
725
- this.#remove?.();
726
- this.#listeners.clear();
727
- for (const weak of this.#children)
728
- weak.deref()?.detach();
729
- this.#children.clear();
730
- }
731
- prepare(value) {
732
- if (!this.#active)
733
- return;
734
- try {
735
- this.check();
736
- } catch {
737
- this.detach();
738
- return;
739
- }
740
- let next;
741
- try {
742
- next = protect(this.compute(value));
743
- } catch (error) {
744
- this.detach();
745
- this.report(error);
746
- return;
747
- }
748
- if (!this.#active)
749
- return;
750
- const children = [];
751
- if (!Object.is(next, this.#value)) {
752
- for (const weak of this.#children) {
753
- const child = weak.deref();
754
- const prepared = child?.prepare(next);
755
- if (prepared)
756
- children.push(prepared);
757
- else
758
- this.#children.delete(weak);
759
- }
760
- }
761
- return {
762
- adopt: () => {
763
- if (!this.#active || Object.is(next, this.#value))
764
- return () => {};
765
- this.#value = next;
766
- const notifyChildren = children.map((child) => child.adopt());
767
- const listeners = [...this.#listeners];
768
- return () => {
769
- if (!this.#active)
770
- return;
771
- for (const notify of notifyChildren)
772
- notify();
773
- for (const listener of listeners) {
774
- try {
775
- listener(next);
776
- } catch (error) {
777
- this.report(error);
778
- }
779
- }
780
- };
781
- }
782
- };
783
- }
784
- select(compute) {
785
- this.check();
786
- const child = new Selection(compute, this.#value, this.report, this.check);
787
- this.check();
788
- const weak = new WeakRef(child);
789
- this.#children.add(weak);
790
- child.track(this.#cleanups, () => this.#children.delete(weak));
791
- return child;
792
- }
793
- subscribe(listener) {
794
- this.check();
795
- this.#listeners.add(listener);
796
- try {
797
- listener(this.#value);
798
- } catch (error) {
799
- this.report(error);
800
- }
801
- return () => {
802
- this.#listeners.delete(listener);
803
- };
804
- }
805
- }
806
-
807
- // src/state/binding.ts
808
- class StateBinding {
809
- backend;
810
- object;
811
- closed = false;
812
- #value;
813
- #listeners = new Set;
814
- #selections = new Set;
815
- constructor(backend, object, initial) {
816
- this.backend = backend;
817
- this.object = object;
818
- this.#value = arguments.length >= 3 ? initial : backend.value(backend.snapshot(object).value);
819
- }
820
- check() {
821
- if (this.closed)
822
- throw new TembraError(Errors.Gone.State, "State owner is gone");
823
- }
824
- get value() {
825
- this.check();
826
- return this.#value;
827
- }
828
- view(options, check = () => this.check()) {
829
- const binding = this;
830
- return {
831
- get value() {
832
- check();
833
- return binding.value;
834
- },
835
- update(context, change) {
836
- check();
837
- binding.backend.check(context, binding.object);
838
- const previous = binding.backend.snapshot(binding.object);
839
- const current = binding.backend.value(previous.value);
840
- const candidate = change(current);
841
- validate(candidate, options);
842
- binding.backend.check(context, binding.object);
843
- if (Object.is(candidate, current))
844
- return current;
845
- const selected = binding.prepare(candidate);
846
- binding.backend.adopt(binding.object, context, previous.revision, candidate);
847
- const publish = binding.adopt(selected, candidate);
848
- binding.backend.publish(publish);
849
- return candidate;
850
- },
851
- select: (compute) => {
852
- check();
853
- return binding.select(compute, check);
854
- },
855
- subscribe: (listener) => {
856
- check();
857
- return binding.subscribe(listener);
858
- }
859
- };
860
- }
861
- select(compute, check = () => this.check(), cleanups) {
862
- check();
863
- const selection = new Selection(compute, this.value, (error) => this.backend.report(error), check);
864
- check();
865
- const weak = new WeakRef(selection);
866
- this.#selections.add(weak);
867
- selection.track(cleanups, () => this.#selections.delete(weak));
868
- return selection;
869
- }
870
- subscribe(listener) {
871
- this.check();
872
- this.#listeners.add(listener);
873
- try {
874
- listener(this.value);
875
- } catch (error) {
876
- this.backend.report(error);
877
- }
878
- return () => {
879
- this.#listeners.delete(listener);
880
- };
881
- }
882
- prepare(candidate) {
883
- const prepared = [];
884
- for (const weak of this.#selections) {
885
- const selection = weak.deref();
886
- const next = selection?.prepare(candidate);
887
- if (next)
888
- prepared.push(next);
889
- else
890
- this.#selections.delete(weak);
891
- }
892
- return prepared;
893
- }
894
- adopt(prepared, candidate) {
895
- this.#value = candidate;
896
- const selections = prepared.map((p) => p.adopt());
897
- const listeners = [...this.#listeners];
898
- return () => {
899
- for (const notify of selections)
900
- notify();
901
- for (const listener of listeners) {
46
+ import { readFile } from "node:fs/promises";
47
+
48
+ // src/interpreter/node-port.ts
49
+ import { Buffer } from "node:buffer";
50
+ class NodePort {
51
+ transport;
52
+ constructor(transport) {
53
+ this.transport = transport;
54
+ }
55
+ description() {
56
+ return this.transport.description();
57
+ }
58
+ release(environment) {
59
+ this.transport.release(environment);
60
+ }
61
+ declare(packet, scope) {
62
+ return answer(this.transport.declare(packet, (request) => respond(() => scope.sync(decodeHostRequest(request)))));
63
+ }
64
+ execute(packet, scope) {
65
+ return new Promise((resolve, reject) => {
66
+ let failure2;
67
+ const pending = new Set;
68
+ const signal = scope.signal;
69
+ const cancel = () => this.transport.cancel();
70
+ this.transport.dispatch(packet, (raw) => {
902
71
  try {
903
- listener(candidate);
72
+ const event = JSON.parse(raw);
73
+ if (event.event === "complete") {
74
+ signal?.removeEventListener("abort", cancel);
75
+ scope.cancel();
76
+ Promise.allSettled([...pending]).then(() => {
77
+ try {
78
+ this.transport.finish();
79
+ if (failure2 !== undefined)
80
+ throw failure2;
81
+ if (!Object.hasOwn(event.result, "ok"))
82
+ throw failure(event.result.error);
83
+ if (typeof event.result.ok !== "string")
84
+ throw new Error("Invalid guest result packet");
85
+ resolve(event.result.ok);
86
+ } catch (error) {
87
+ reject(error);
88
+ }
89
+ }).catch(reject);
90
+ } else if (event.event === "host") {
91
+ if (!event.asynchronous)
92
+ this.transport.reply(event.id, respond(() => scope.sync(decodeHostRequest(event.packet))));
93
+ else {
94
+ let request;
95
+ const operation = Promise.resolve().then(() => {
96
+ request = decodeAsyncHostRequest(event.packet);
97
+ return scope.async(request);
98
+ }).then((value) => scope.deliver(request, value, (value) => this.transport.reply(event.id, respond(() => value))), (error) => this.transport.reply(event.id, respond(() => {
99
+ throw error;
100
+ }))).catch((error) => {
101
+ failure2 = error;
102
+ });
103
+ pending.add(operation);
104
+ operation.finally(() => pending.delete(operation));
105
+ }
106
+ } else
107
+ throw new Error("Unknown interpreter event");
904
108
  } catch (error) {
905
- this.backend.report(error);
109
+ failure2 = error;
906
110
  }
907
- }
908
- };
909
- }
910
- close() {
911
- this.closed = true;
912
- this.#value = undefined;
913
- this.#listeners.clear();
914
- for (const weak of this.#selections)
915
- weak.deref()?.detach();
916
- this.#selections.clear();
917
- }
918
- }
919
- function validate(candidate, options) {
920
- if (candidate && typeof candidate.then === "function")
921
- refuse(Errors.Invalid.AsyncState, "State updates and migrations must be synchronous");
922
- const protectedValue = protect(candidate);
923
- const result = options.validate?.(protectedValue);
924
- if (result !== undefined && result !== true)
925
- refuse(Errors.Invalid.StateValidation, "Orb rejected the candidate state");
926
- return protectedValue;
927
- }
928
- // src/authoring/declaration.ts
929
- class Declaration {
930
- session;
931
- environment;
932
- constructor(session, environment) {
933
- this.session = session;
934
- this.environment = environment;
935
- }
936
- check() {
937
- if (this.environment.phase !== EnvironmentPhase.Declaring)
938
- refuse(Errors.Invalid.FactoryExpired, "Declarations must be synchronous");
939
- }
940
- get principal() {
941
- return this.session.principalFor(this.environment.object?.id ?? 0);
942
- }
943
- get orb() {
944
- return this.environment.orb.scope?.value;
945
- }
946
- get key() {
947
- return this.environment.object?.address.key ?? ["main"];
948
- }
949
- state(initial, options = {}) {
950
- this.check();
951
- const environment = this.environment;
952
- const object = environment.object;
953
- if (!object || environment.state)
954
- refuse(Errors.Invalid.State, "An object declares exactly one state");
955
- const version = options.version ?? 1;
956
- if (!Number.isInteger(version) || version <= 0)
957
- refuse(Errors.Invalid.StateVersion);
958
- let binding = object.binding;
959
- if (!binding && object.live)
960
- binding = new StateBinding(this.session, object.id, validate(initial, options));
961
- if (!binding) {
962
- const value = validate(initial, options);
963
- const id = this.session.values.put(value);
964
- try {
965
- this.session.kernel.command(KernelOp.StateInit, { object: object.id, value: id, version });
966
- } catch (error) {
967
- this.session.values.drop(id);
968
- throw error;
969
- }
970
- object.binding = binding = new StateBinding(this.session, object.id);
971
- }
972
- const handle = binding.view(options);
973
- environment.state = { initial, options, binding };
974
- return handle;
975
- }
976
- get(service, key, options = {}) {
977
- this.check();
978
- const acquisition = serviceAcquisition(service, options);
979
- const requirement = this.session.scopes.requirement(this.environment, acquisition.name);
980
- const resolved = requirement.service;
981
- if (typeof service !== "string" && resolved !== acquisition.name)
982
- refuse(Errors.Invalid.Service, "A typed dependency must resolve its declared service name");
983
- if (!this.environment.object && this.environment.orb.definition.services?.[resolved])
984
- refuse(Errors.Invalid.DependencyCycle);
985
- const admitted = serviceAcquisition(service, {
986
- ...options,
987
- ...requirement.apiVersion ? { apiVersion: requirement.apiVersion } : {},
988
- ...requirement.methods ? { methods: requirement.methods } : {},
989
- principal: options.principal ?? this.principal
990
- });
991
- const identity = JSON.stringify([resolved, key, options.principal ?? this.principal]);
992
- const existing = this.environment.dependencies.get(identity);
993
- if (existing)
994
- return existing;
995
- const reference = this.session.handles.hold(resolved, key, admitted.options);
996
- if (this.environment.object) {
997
- try {
998
- this.session.kernel.command(KernelOp.Dependency, {
999
- object: this.environment.object.id,
1000
- reference: this.session.handles.reference(reference).id
1001
- });
1002
- } catch (error) {
1003
- reference.release();
1004
- throw error;
1005
- }
1006
- }
1007
- this.environment.dependencies.set(identity, reference);
1008
- return reference;
1009
- }
1010
- resource(name, options) {
1011
- this.check();
1012
- if (!options)
1013
- return this.session.scopes.hostResource(name);
1014
- if (this.environment.resources.has(name))
1015
- refuse(Errors.Invalid.DuplicateResource, name);
1016
- const resource = this.session.resources.declare(this.environment, name, options);
1017
- this.environment.resources.set(name, resource);
1018
- return resource.handle;
1019
- }
1020
- task(start) {
1021
- this.check();
1022
- if (typeof start !== "function")
1023
- refuse(Errors.Invalid.Task);
1024
- this.environment.tasks.push({ start });
1025
- }
1026
- on(name, source, handle, options = {}) {
1027
- this.check();
1028
- if (!this.session.kernel.features.subscriptions)
1029
- refuse(Errors.Invalid.SubscriptionsDisabled);
1030
- if (options.maxBytes !== undefined && !options.sizeOf)
1031
- refuse(Errors.Invalid.SubscriptionSize, "A local byte budget requires an explicit sizeOf function");
1032
- if (!name || this.environment.listeners.some((listener) => listener.name === name))
1033
- refuse(Errors.Invalid.DuplicateListener, name);
1034
- this.environment.listeners.push({ name, source, handle, options });
1035
- }
1036
- hook(name) {
1037
- this.check();
1038
- if (!this.session.kernel.features.hooks)
1039
- refuse(Errors.Invalid.HooksDisabled);
1040
- if (!this.environment.orb.definition.hooks?.[name])
1041
- refuse(Errors.Invalid.Hook, name);
1042
- const operation = this.session.kernel.command(KernelOp.Allocate);
1043
- return {
1044
- run: (context, input) => this.session.orbs.runHook(this.environment, name, context, input),
1045
- observe: (source, input) => this.session.orbs.observe(this.environment, name, operation, source, input)
1046
- };
1047
- }
1048
- }
1049
- function consumerState(binding, check, cleanups) {
1050
- return {
1051
- get value() {
1052
- check();
1053
- return binding.value;
1054
- },
1055
- select(compute) {
1056
- check();
1057
- return binding.select(compute, check, cleanups);
1058
- },
1059
- subscribe(listener) {
1060
- check();
1061
- const detach = binding.subscribe((value) => {
1062
- try {
1063
- check();
1064
- } catch {
1065
- return;
1066
- }
1067
- listener(value);
1068
- });
1069
- let active = true;
1070
- const cleanup = () => {
1071
- if (!active)
1072
- return;
1073
- active = false;
1074
- cleanups.delete(cleanup);
1075
- detach();
1076
- };
1077
- cleanups.add(cleanup);
1078
- try {
1079
- check();
1080
- } catch {
1081
- cleanup();
1082
- }
1083
- return cleanup;
1084
- }
1085
- };
1086
- }
1087
-
1088
- // src/bridge/kernel.ts
1089
- class Kernel {
1090
- port;
1091
- features;
1092
- constructor(port) {
1093
- this.port = port;
1094
- this.features = this.command(KernelOp.Features);
1095
- }
1096
- command(op, fields = {}) {
1097
- const envelope = JSON.parse(this.port.request(JSON.stringify({ ...fields, op })));
1098
- if (envelope.error)
1099
- throw new TembraError(envelope.error);
1100
- return envelope.ok;
1101
- }
1102
- }
1103
-
1104
- // src/codecs/json.ts
1105
- var marker = "$tembra";
1106
- function pack(value, visiting) {
1107
- if (typeof value === "bigint")
1108
- return { [marker]: [CodecTag.Bigint, value.toString()] };
1109
- if (value instanceof Uint8Array)
1110
- return { [marker]: [CodecTag.Bytes, [...value]] };
1111
- if (value === null || typeof value === "string" || typeof value === "boolean")
1112
- return value;
1113
- if (typeof value === "number") {
1114
- if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value))
1115
- refuse(Errors.Invalid.JsonNumber, "Use BigInt for integers outside the safe Number range");
1116
- return value;
1117
- }
1118
- if (typeof value !== "object")
1119
- refuse(Errors.Invalid.JsonValue, "This JSON codec requires explicit portable values");
1120
- if (visiting.has(value))
1121
- refuse(Errors.Invalid.JsonCycle);
1122
- const prototype = Object.getPrototypeOf(value);
1123
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
1124
- refuse(Errors.Invalid.JsonType, "Supply a codec for custom object types");
1125
- visiting.add(value);
1126
- try {
1127
- if (Array.isArray(value))
1128
- return Array.from(value, (child) => pack(child, visiting));
1129
- const entries = Reflect.ownKeys(value).map((key) => {
1130
- if (typeof key !== "string")
1131
- refuse(Errors.Invalid.JsonSymbol);
1132
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
1133
- if (!Object.hasOwn(descriptor, "value"))
1134
- refuse(Errors.Invalid.JsonAccessor);
1135
- return [key, pack(descriptor.value, visiting)];
1136
- });
1137
- return Object.hasOwn(value, marker) ? { [marker]: [CodecTag.Object, entries] } : Object.fromEntries(entries);
1138
- } finally {
1139
- visiting.delete(value);
1140
- }
1141
- }
1142
- function unpack(value) {
1143
- if (value === null || typeof value !== "object") {
1144
- if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value))
1145
- refuse(Errors.Invalid.JsonNumber);
1146
- return value;
1147
- }
1148
- if (Array.isArray(value))
1149
- return value.map(unpack);
1150
- if (Object.hasOwn(value, marker)) {
1151
- const tag = value[marker];
1152
- if (Object.keys(value).length !== 1 || !Array.isArray(tag) || tag.length !== 2)
1153
- refuse(Errors.Invalid.JsonTag);
1154
- const [type, data] = tag;
1155
- if (type === CodecTag.Bigint && typeof data === "string" && /^-?(0|[1-9]\d*)$/.test(data))
1156
- return BigInt(data);
1157
- if (type === CodecTag.Bytes && Array.isArray(data) && data.every((v) => Number.isInteger(v) && v >= 0 && v <= 255))
1158
- return Uint8Array.from(data);
1159
- if (type === CodecTag.Object && Array.isArray(data)) {
1160
- if (!data.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string"))
1161
- refuse(Errors.Invalid.JsonTag);
1162
- return Object.fromEntries(data.map(([key, child]) => [key, unpack(child)]));
1163
- }
1164
- refuse(Errors.Invalid.JsonTag, "Unknown or malformed portable type tag");
1165
- }
1166
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, unpack(child)]));
1167
- }
1168
- function utf8(text) {
1169
- const output = [];
1170
- for (const character of text) {
1171
- let point = character.codePointAt(0);
1172
- if (point >= 55296 && point <= 57343)
1173
- point = 65533;
1174
- if (point < 128)
1175
- output.push(point);
1176
- else if (point < 2048)
1177
- output.push(192 | point >> 6, 128 | point & 63);
1178
- else if (point < 65536)
1179
- output.push(224 | point >> 12, 128 | point >> 6 & 63, 128 | point & 63);
1180
- else
1181
- output.push(240 | point >> 18, 128 | point >> 12 & 63, 128 | point >> 6 & 63, 128 | point & 63);
1182
- }
1183
- return Uint8Array.from(output);
1184
- }
1185
- function text(bytes) {
1186
- const output = [];
1187
- for (let index = 0;index < bytes.length; ) {
1188
- const first = bytes[index++];
1189
- if (first < 128) {
1190
- output.push(String.fromCharCode(first));
1191
- continue;
1192
- }
1193
- const count = first >= 194 && first <= 223 ? 1 : first >= 224 && first <= 239 ? 2 : first >= 240 && first <= 244 ? 3 : -1;
1194
- if (count < 0 || index + count > bytes.length)
1195
- refuse(Errors.Invalid.Utf8);
1196
- let point = first & 127 >> count + 1;
1197
- for (let offset = 0;offset < count; offset++) {
1198
- const next = bytes[index++];
1199
- if ((next & 192) !== 128)
1200
- refuse(Errors.Invalid.Utf8);
1201
- point = point << 6 | next & 63;
1202
- }
1203
- if (point < [0, 128, 2048, 65536][count] || point > 1114111 || point >= 55296 && point <= 57343)
1204
- refuse(Errors.Invalid.Utf8);
1205
- output.push(String.fromCodePoint(point));
1206
- }
1207
- return output.join("");
1208
- }
1209
- var jsonCodec = Object.freeze({
1210
- id: CodecId.Json,
1211
- serialize: (value) => utf8(JSON.stringify(pack(value, new WeakSet))),
1212
- deserialize: (bytes) => unpack(JSON.parse(text(bytes)))
1213
- });
1214
-
1215
- // src/telemetry.ts
1216
- class Telemetry {
1217
- capacity;
1218
- sampleEvery;
1219
- #events = [];
1220
- #next = 0;
1221
- constructor(capacity = 256, sampleEvery = 1) {
1222
- this.capacity = capacity;
1223
- this.sampleEvery = sampleEvery;
1224
- if (!Number.isInteger(capacity) || capacity <= 0 || !Number.isInteger(sampleEvery) || sampleEvery <= 0)
1225
- throw new RangeError("Invalid telemetry limits");
1226
- }
1227
- sample() {
1228
- return this.#next++ % this.sampleEvery === 0;
1229
- }
1230
- record(trace) {
1231
- if (this.#events.length === this.capacity)
1232
- this.#events.shift();
1233
- this.#events.push(trace);
1234
- }
1235
- drain() {
1236
- return this.#events.splice(0);
1237
- }
1238
- }
1239
-
1240
- // src/runtime/activities.ts
1241
- class Activities {
1242
- session;
1243
- tasks = new Map;
1244
- listeners = new Map;
1245
- #identities = new WeakMap;
1246
- constructor(session) {
1247
- this.session = session;
1248
- }
1249
- prepare(environment, previous) {
1250
- for (const definition of environment.listeners) {
1251
- const source = typeof definition.source === "function" ? definition.source() : definition.source;
1252
- if (!source || typeof source.subscribe !== "function")
1253
- refuse(Errors.Invalid.EventSource);
1254
- const id = this.session.kernel.command(KernelOp.Listen, {
1255
- scope: environment.id,
1256
- previous: previous?.id,
1257
- name: definition.name,
1258
- source: this.identity(source),
1259
- sizing: definition.options.sizeOf ? this.identity(definition.options.sizeOf) : 0,
1260
- operation: this.session.kernel.command(KernelOp.Allocate),
1261
- maxPending: definition.options.maxPending ?? 64,
1262
- ...definition.options.maxBytes ? { maxBytes: definition.options.maxBytes } : {},
1263
- coalesce: "select" in source
1264
- });
1265
- const existing = this.listeners.get(id);
1266
- if (existing) {
1267
- definition.running = existing;
1268
- continue;
1269
- }
1270
- const record = {
1271
- id,
1272
- definition,
1273
- environment,
1274
- stopped: false,
1275
- detach() {}
1276
- };
1277
- definition.running = record;
1278
- this.listeners.set(id, record);
1279
- try {
1280
- record.detach = source.subscribe((value) => {
1281
- if (record.stopped)
1282
- return;
1283
- const payload = this.session.values.put(value);
1284
- try {
1285
- const bytes = definition.options.sizeOf?.(value) ?? 0;
1286
- if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > 4294967295)
1287
- throw new TembraError(Errors.Invalid.SubscriptionSize);
1288
- this.session.kernel.command(KernelOp.Enqueue, { subscription: id, payload, bytes });
1289
- } catch (error) {
1290
- this.session.values.drop(payload);
1291
- this.session.report(error);
1292
- this.failed(id);
1293
- }
1294
- this.session.lifecycle.flush();
1295
- });
1296
- if (record.stopped)
1297
- record.detach();
1298
- } catch (error) {
1299
- this.stopListener(record);
1300
- throw error;
1301
- }
1302
- }
1303
- }
1304
- start(environment) {
1305
- environment.phase = EnvironmentPhase.Live;
1306
- for (const definition of environment.listeners) {
1307
- const record = definition.running;
1308
- record.environment = environment;
1309
- record.definition = definition;
1310
- }
1311
- for (const task of environment.tasks)
1312
- this.startTask(environment, task);
1313
- }
1314
- startTask(environment, definition) {
1315
- if (definition.running || environment.phase !== EnvironmentPhase.Live || this.session.closing)
1316
- return;
1317
- const id = this.session.kernel.command(KernelOp.Task, { owner: environment.owner });
1318
- const controller = new AbortController;
1319
- const operation = this.session.kernel.command(KernelOp.Allocate);
1320
- const record = { id, controller, done: Promise.resolve() };
1321
- definition.running = record;
1322
- this.tasks.set(id, record);
1323
- record.done = this.session.track(Promise.resolve().then(async () => {
1324
- try {
1325
- await definition.start({
1326
- signal: controller.signal,
1327
- root: (callback) => {
1328
- const root = this.session.kernel.command(KernelOp.TaskRoot, {
1329
- task: id,
1330
- principal: this.session.principalFor(environment.object?.id ?? 0)
1331
- });
1332
- return this.session.calls.root(() => this.session.calls.owned(environment, operation, callback, root), false, root);
1333
- }
1334
- });
1335
- } catch (error) {
1336
- if (!controller.signal.aborted)
1337
- this.session.report(error);
1338
- } finally {
1339
- this.session.kernel.command(KernelOp.Tick, { now: this.session.now() });
1340
- this.session.kernel.command(KernelOp.FinishTask, { task: id });
1341
- this.tasks.delete(id);
1342
- delete definition.running;
1343
- this.session.lifecycle.flush();
1344
- }
1345
- }));
1346
- }
1347
- identity(value) {
1348
- let id = this.#identities.get(value);
1349
- if (id === undefined) {
1350
- id = this.session.kernel.command(KernelOp.Allocate);
1351
- this.#identities.set(value, id);
1352
- }
1353
- return id;
1354
- }
1355
- deliver(subscription, payload, operation) {
1356
- const record = this.listeners.get(subscription);
1357
- const job = Promise.resolve().then(async () => {
1358
- try {
1359
- if (!record)
1360
- throw new TembraError(Errors.Gone.ListenerCallback);
1361
- await this.session.calls.owned(record.environment, operation, (ctx) => record.definition.handle(ctx, this.session.values.get(payload)));
1362
- } catch (error) {
1363
- this.session.report(error);
1364
- } finally {
1365
- this.session.kernel.command(KernelOp.FinishDelivery, { subscription });
1366
- this.session.lifecycle.flush();
1367
- }
1368
- });
1369
- if (record)
1370
- record.done = job;
1371
- this.session.track(job);
1372
- }
1373
- detach(id) {
1374
- const record = this.listeners.get(id);
1375
- if (record)
1376
- this.stopListener(record);
1377
- }
1378
- cancel(id) {
1379
- this.tasks.get(id)?.controller.abort(new TembraError(Errors.Cancelled.Task));
1380
- }
1381
- failed(id) {
1382
- const record = this.listeners.get(id);
1383
- if (!record)
1384
- return;
1385
- this.session.report(new TembraError(Errors.Exhausted.SubscriptionQueue));
1386
- this.stopListener(record);
1387
- }
1388
- stopListener(record) {
1389
- if (record.stopped)
1390
- return;
1391
- record.stopped = true;
1392
- try {
1393
- record.detach();
1394
- } catch (error) {
1395
- this.session.report(error);
1396
- }
1397
- this.session.kernel.command(KernelOp.Unsubscribe, { subscription: record.id });
1398
- this.listeners.delete(record.id);
1399
- this.session.lifecycle.flush();
1400
- }
1401
- async stop(environment) {
1402
- for (const definition of environment.tasks) {
1403
- if (definition.running)
1404
- this.session.kernel.command(KernelOp.StopTask, { task: definition.running.id });
1405
- }
1406
- this.session.lifecycle.flush();
1407
- await Promise.all(environment.tasks.map((task) => task.running?.done));
1408
- await Promise.all(environment.listeners.map((listener) => listener.running?.done));
1409
- }
1410
- }
1411
-
1412
- // src/context-key.ts
1413
- var ContextKind = Object.freeze({
1414
- Text: "text",
1415
- Integer: "integer",
1416
- Boolean: "boolean",
1417
- Opaque: "opaque"
1418
- });
1419
-
1420
- class ContextKey {
1421
- name;
1422
- version;
1423
- kind;
1424
- constructor(name, version, kind) {
1425
- this.name = name;
1426
- this.version = version;
1427
- this.kind = kind;
1428
- Object.freeze(this);
1429
- }
1430
- static text(name, version = 1) {
1431
- return new ContextKey(name, version, ContextKind.Text);
1432
- }
1433
- static integer(name, version = 1) {
1434
- return new ContextKey(name, version, ContextKind.Integer);
1435
- }
1436
- static boolean(name, version = 1) {
1437
- return new ContextKey(name, version, ContextKind.Boolean);
1438
- }
1439
- static opaque(name, version = 1) {
1440
- return new ContextKey(name, version, ContextKind.Opaque);
1441
- }
1442
- source(value, ctx) {
1443
- if (this.kind !== ContextKind.Opaque)
1444
- return;
1445
- const token = typeof value === "object" && value !== null ? ctx.session.contextTokens.get(value) : undefined;
1446
- if (!token || token.root !== ctx.root)
1447
- throw new TypeError("An owner-issued opaque reference from this host and root is required");
1448
- return token.source;
1449
- }
1450
- }
1451
- function readContextValue(ctx, key, frame) {
1452
- const entry = ctx.session.kernel.command(KernelOp.ContextValue, {
1453
- root: ctx.root,
1454
- context: frame,
1455
- call: ctx.invocation?.id,
1456
- key
1457
- });
1458
- if (!entry)
1459
- return;
1460
- if (entry.kind !== ContextKind.Opaque)
1461
- return entry.value;
1462
- const token = Object.freeze({ opaque: true });
1463
- ctx.session.contextTokens.set(token, { root: ctx.root, source: entry.source });
1464
- return token;
1465
- }
1466
- function opaqueFrom(ctx, key, issuedFrame) {
1467
- const token = readContextValue(ctx, key, issuedFrame);
1468
- if (!token)
1469
- throw new TypeError("The owner did not issue a reference");
1470
- return token;
1471
- }
1472
-
1473
- // src/runtime/context.ts
1474
- var issued = new WeakMap;
1475
-
1476
- class Context {
1477
- session;
1478
- root;
1479
- invocation;
1480
- frame;
1481
- constructor(session, root, invocation, frame = 0) {
1482
- this.session = session;
1483
- this.root = root;
1484
- this.invocation = invocation;
1485
- this.frame = frame;
1486
- issued.set(this, this);
1487
- }
1488
- with(key, value) {
1489
- const source = key.source(value, this);
1490
- const frame = this.session.kernel.command(KernelOp.ContextDerive, {
1491
- root: this.root,
1492
- context: this.frame,
1493
- call: this.invocation?.id,
1494
- key,
1495
- ...key.kind === ContextKind.Opaque ? { source } : { value }
1496
- });
1497
- return new Context(this.session, this.root, this.invocation, frame);
1498
- }
1499
- value(key) {
1500
- return readContextValue(this, key, this.frame);
1501
- }
1502
- exportValues(keys) {
1503
- const result = {};
1504
- for (const key of keys) {
1505
- if (key.kind === ContextKind.Opaque)
1506
- throw new TypeError("Local opaque references cannot be exported");
1507
- const value = this.value(key);
1508
- if (value !== undefined)
1509
- result[`${key.name}@${key.version}`] = value;
1510
- }
1511
- return result;
1512
- }
1513
- get principal() {
1514
- return this.session.kernel.command(KernelOp.RootPrincipal, { root: this.root });
1515
- }
1516
- get signal() {
1517
- return this.session.calls.signal(this.root);
1518
- }
1519
- check() {
1520
- this.session.kernel.command(KernelOp.CheckContext, {
1521
- root: this.root,
1522
- call: this.invocation?.id
1523
- });
1524
- }
1525
- cancel() {
1526
- this.session.kernel.command(KernelOp.CancelRoot, { root: this.root });
1527
- this.session.lifecycle.flush();
1528
- }
1529
- get(service, key, options = {}) {
1530
- this.check();
1531
- return this.session.handles.get(service, key, options, this);
1532
- }
1533
- resource(name) {
1534
- this.check();
1535
- return this.session.scopes.hostResource(name);
1536
- }
1537
- }
1538
- function issuedContext(value, session) {
1539
- if (typeof value !== "object" || value === null || issued.get(value)?.session !== session) {
1540
- throw new TembraError(Errors.Forbidden.Context, "An issued context from this host is required");
1541
- }
1542
- return issued.get(value);
1543
- }
1544
- function context(value, session) {
1545
- const result = issuedContext(value, session);
1546
- result.check();
1547
- return result;
1548
- }
1549
- function isContext(value) {
1550
- return typeof value === "object" && value !== null && issued.has(value);
1551
- }
1552
-
1553
- // src/runtime/calls.ts
1554
- class Calls {
1555
- session;
1556
- constructor(session) {
1557
- this.session = session;
1558
- }
1559
- signal(root) {
1560
- const session = this.session;
1561
- let controller = session.controllers.get(root);
1562
- if (!controller) {
1563
- controller = new AbortController;
1564
- try {
1565
- session.kernel.command(KernelOp.CheckRoot, { root });
1566
- } catch (error) {
1567
- if (!(error instanceof TembraError) || error.code !== Code.Cancelled)
1568
- throw error;
1569
- controller.abort(error);
1570
- }
1571
- session.controllers.set(root, controller);
1572
- }
1573
- return controller.signal;
1574
- }
1575
- releaseRoot(root) {
1576
- for (const reference of this.session.rootReferences.get(root) ?? [])
1577
- this.session.handles.release(reference);
1578
- this.session.rootReferences.delete(root);
1579
- this.session.controllers.delete(root);
1580
- }
1581
- async root(operation, cleanup = false, issuedRoot, principal = this.session.principal) {
1582
- const session = this.session;
1583
- const root = issuedRoot ?? session.kernel.command(cleanup ? KernelOp.CleanupRoot : KernelOp.Root, { principal });
1584
- const ctx = new Context(session, root);
1585
- try {
1586
- return await operation(ctx);
1587
- } finally {
1588
- this.releaseRoot(root);
1589
- session.options.native?.rootEnded?.(root);
1590
- if (!session.lifecycle.closedDiagnostics)
1591
- session.kernel.command(KernelOp.EndRoot, { root });
1592
- session.controllers.delete(root);
1593
- session.lifecycle.flush();
1594
- }
1595
- }
1596
- async invoke(reference, method, arguments_, ctx) {
1597
- const session = this.session;
1598
- context(ctx, session);
1599
- if (reference.released)
1600
- throw new TembraError(Errors.Released.Reference);
1601
- await reference.ready;
1602
- const admission = session.options.native?.admit?.(reference.id, method, ctx);
1603
- let invocation;
1604
- if (admission)
1605
- invocation = admission.call;
1606
- else {
1607
- ctx.check();
1608
- invocation = session.kernel.command(KernelOp.BeginCall, {
1609
- reference: reference.id,
1610
- root: ctx.root,
1611
- context: ctx.frame || undefined,
1612
- method
1613
111
  });
1614
- }
1615
- const entered = new Context(session, ctx.root, invocation, ctx.frame);
1616
- const physical = session.track((async () => {
1617
- const sampled = session.telemetry?.sample();
1618
- const started = sampled ? session.now() : 0;
1619
- let outcome = Outcome.Ok;
1620
- try {
1621
- const native = session.options.native;
1622
- if (native && (admission?.native ?? native.hasOrb(invocation.orb)))
1623
- return await native.invoke(invocation, arguments_, entered);
1624
- const object = session.objects.get(invocation.object);
1625
- const environment = object?.versions.get(invocation.orb);
1626
- const handle = environment?.orb.definition.services?.[reference.address.service]?.methods[method];
1627
- if (!environment || !handle)
1628
- throw new TembraError(Errors.Gone.Implementation);
1629
- return await handle(environment.value, entered, ...arguments_);
1630
- } catch (error) {
1631
- outcome = Outcome.Error;
1632
- throw error;
1633
- } finally {
1634
- if (sampled)
1635
- session.telemetry.record({
1636
- service: reference.address.service,
1637
- method,
1638
- root: invocation.root,
1639
- codeVersion: invocation.codeVersion,
1640
- duration: session.now() - started,
1641
- outcome
1642
- });
1643
- session.lifecycle.finishCall(invocation.id);
1644
- }
1645
- })());
1646
- return this.observe(physical, ctx.signal);
1647
- }
1648
- async owned(environment, operation, handle, root) {
1649
- const session = this.session;
1650
- const execute = async (ctx) => {
1651
- const invocation = session.kernel.command(KernelOp.BeginOperation, {
1652
- orb: environment.orb.info.id,
1653
- root: ctx.root,
1654
- context: ctx.frame || undefined,
1655
- operation,
1656
- ...environment.object ? { object: environment.object.id } : {}
1657
- });
1658
- try {
1659
- return await handle(new Context(session, ctx.root, invocation, ctx.frame));
1660
- } finally {
1661
- session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
1662
- session.lifecycle.flush();
1663
- }
1664
- };
1665
- return root === undefined ? this.root(execute, false, undefined, session.principalFor(environment.object?.id ?? 0)) : execute(typeof root === "number" ? new Context(session, root) : root);
1666
- }
1667
- async observe(physical, signal) {
1668
- if (signal.aborted)
1669
- throw signal.reason;
1670
- let abort;
1671
- const cancelled = new Promise((_, reject) => {
1672
- abort = () => reject(signal.reason ?? new TembraError(Errors.Cancelled.Root));
1673
- signal.addEventListener("abort", abort, { once: true });
1674
- });
1675
- try {
1676
- return await Promise.race([physical, cancelled]);
1677
- } finally {
1678
- signal.removeEventListener("abort", abort);
1679
- }
1680
- }
1681
- }
1682
-
1683
- // src/runtime/orbs.ts
1684
- class Orbs {
1685
- session;
1686
- records = new Map;
1687
- operations = new Map;
1688
- #ready = new Map;
1689
- #ordinals = new Map;
1690
- constructor(session) {
1691
- this.session = session;
1692
- }
1693
- declarations(definitions) {
1694
- const captured = definitions.map((definition) => orb(definition));
1695
- const current = this.session.kernel.command(KernelOp.Orbs);
1696
- const lookup = (name) => captured.find((f) => f.name === name);
1697
- const metadata = captured.map((definition) => {
1698
- if (!this.session.kernel.features.views && Object.values(definition.services ?? {}).some((service) => service.access))
1699
- throw new TembraError(Errors.Unsupported.Views);
1700
- const requires = Object.entries(definition.requires ?? {}).map(([alias, requirement]) => {
1701
- const name = requirement.orb ?? alias;
1702
- const provider = lookup(name);
1703
- const info = current.find((f) => f.name === name);
1704
- const names = provider ? Object.keys(provider.services ?? {}) : info?.services.map((s) => s.name) ?? [];
1705
- const service = names.includes(alias) ? alias : names.length === 1 ? names[0] : undefined;
1706
- if (requirement.methods && !service)
1707
- refuse(Errors.Invalid.DependencyService, `Use explicit services for ${name}`);
1708
- return {
1709
- orb: name,
1710
- apiVersion: requirement.apiVersion,
1711
- services: requirement.services ?? (requirement.methods ? { [service]: requirement.methods } : {}),
1712
- hooks: requirement.hooks ?? []
1713
- };
1714
- });
1715
- for (const [alias, hooks] of Object.entries(definition.contributes ?? {})) {
1716
- const requirement = definition.requires?.[alias];
1717
- if (!requirement)
1718
- refuse(Errors.Invalid.HookDependency, alias);
1719
- for (const [hook, contribution] of Object.entries(hooks)) {
1720
- if (!requirement.hooks?.includes(hook))
1721
- refuse(Errors.Invalid.HookDependency, hook);
1722
- const priority = typeof contribution === "function" ? 0 : contribution.priority ?? 0;
1723
- if (!Number.isInteger(priority) || priority < -2147483648 || priority > 2147483647)
1724
- refuse(Errors.Invalid.Priority);
1725
- }
1726
- }
1727
- return {
1728
- name: definition.name,
1729
- apiVersion: definition.apiVersion,
1730
- requires,
1731
- hooks: Object.keys(definition.hooks ?? {}),
1732
- services: Object.entries(definition.services ?? {}).map(([name, service]) => ({
1733
- name,
1734
- methods: Object.keys(service.methods),
1735
- lifetime: service.lifetime ?? Lifetime.Referenced,
1736
- linger: service.linger ?? 0
1737
- }))
1738
- };
112
+ if (signal?.aborted)
113
+ cancel();
114
+ else
115
+ signal?.addEventListener("abort", cancel, { once: true });
1739
116
  });
1740
- return { definitions: captured, metadata };
1741
117
  }
1742
- async install(definitions) {
1743
- const current = this.session.kernel.command(KernelOp.Orbs);
1744
- if (definitions.some((f) => current.some((installed) => installed.name === f.name)))
1745
- refuse(Errors.Invalid.OrbInstalled, "Use reload to replace an installed orb");
1746
- const prepared = this.declarations(definitions);
1747
- const reload = this.session.kernel.command(KernelOp.Prepare, {
1748
- orbs: prepared.metadata
1749
- });
1750
- this.session.kernel.command(KernelOp.Commit, { ticket: reload.id });
1751
- const records = reload.orbs.map((info) => ({
1752
- info,
1753
- definition: prepared.definitions.find((f) => f.name === info.name)
1754
- }));
1755
- for (const record of records)
1756
- this.records.set(record.info.id, record);
1757
- for (const record of records)
1758
- this.registerContributions(record);
1759
- await Promise.all(records.map((record) => this.ready(record)));
1760
- for (const record of records) {
1761
- for (const service of record.info.services.filter((s) => s.lifetime === Lifetime.Host)) {
1762
- const reference = await this.session.handles.get(service.name, "main", {
1763
- principal: "host"
1764
- });
1765
- reference.release();
1766
- }
1767
- }
1768
- this.session.lifecycle.flush();
1769
- }
1770
- scope(record) {
1771
- if (record.scope)
1772
- return record.scope;
1773
- const environment = this.session.scopes.environment({ kind: OwnerKind.Orb, id: record.info.owner }, record);
1774
- record.scope = environment;
118
+ ingress(dispatch, exchange, scope) {
119
+ const transport = this.transport;
120
+ const carrier = new NativeIngress({
121
+ supply: (answer) => answer.kind === "data" ? transport.supplyRequest(answer.data, null, null) : answer.kind === "end" ? transport.supplyRequest(null, answer.trailers.map(nodeField), null) : transport.supplyRequest(null, null, answer.message),
122
+ pull: () => transport.pullResponse(),
123
+ disconnect: () => transport.disconnect(),
124
+ cancel: () => transport.cancel(),
125
+ reply: (id, packet) => transport.reply(id, packet),
126
+ finish: () => transport.finish()
127
+ }, exchange, scope);
128
+ const { method, scheme, authority, pathWithQuery, fields } = exchange.request;
1775
129
  try {
1776
- const value = record.definition.create?.(new Declaration(this.session, environment)) ?? {};
1777
- if (value && typeof value.then === "function")
1778
- refuse(Errors.Invalid.AsyncFactory);
1779
- environment.value = value;
1780
- } finally {
1781
- environment.phase = EnvironmentPhase.Prepared;
1782
- this.session.programs.register(environment);
1783
- }
1784
- return environment;
1785
- }
1786
- ready(record) {
1787
- if (record.scope?.phase === EnvironmentPhase.Live)
1788
- return Promise.resolve();
1789
- let ready = this.#ready.get(record.info.id);
1790
- if (!ready) {
1791
- ready = (async () => {
130
+ transport.ingress(ingressPacket(dispatch), {
131
+ method,
132
+ ...scheme === undefined ? {} : { scheme },
133
+ ...authority === undefined ? {} : { authority },
134
+ ...pathWithQuery === undefined ? {} : { pathWithQuery },
135
+ fields: fields.map(nodeField)
136
+ }, (event) => {
1792
137
  try {
1793
- await this.session.scopes.readyHostScope();
1794
- if (record.scope?.phase === EnvironmentPhase.Closed)
1795
- delete record.scope;
1796
- const scope = this.scope(record);
1797
- await this.session.programs.activate(scope.id);
138
+ carrier.event(carrierEvent(event));
1798
139
  } catch (error) {
1799
- if (record.scope) {
1800
- await this.session.programs.cleanup([record.scope]);
1801
- delete record.scope;
1802
- }
1803
- throw error;
1804
- }
1805
- })();
1806
- this.#ready.set(record.info.id, ready);
1807
- const clear = () => {
1808
- if (this.#ready.get(record.info.id) === ready)
1809
- this.#ready.delete(record.info.id);
1810
- };
1811
- ready.then(clear, clear);
1812
- }
1813
- return ready;
1814
- }
1815
- registerContributions(record) {
1816
- for (const [alias, hooks] of Object.entries(record.definition.contributes ?? {})) {
1817
- const requirement = record.definition.requires[alias];
1818
- const target = requirement.orb ?? alias;
1819
- for (const [hook, contribution] of Object.entries(hooks)) {
1820
- const operation = this.session.kernel.command(KernelOp.Allocate);
1821
- const key = JSON.stringify([record.info.name, target, hook]);
1822
- if (!this.#ordinals.has(key))
1823
- this.#ordinals.set(key, this.session.kernel.command(KernelOp.ContributionOrdinal));
1824
- this.operations.set(operation, {
1825
- orb: record,
1826
- handler: typeof contribution === "function" ? contribution : contribution.handle
1827
- });
1828
- this.session.kernel.command(KernelOp.Contribute, {
1829
- orb: record.info.id,
1830
- target,
1831
- hook,
1832
- operation,
1833
- priority: typeof contribution === "function" ? 0 : contribution.priority ?? 0,
1834
- ordinal: this.#ordinals.get(key)
1835
- });
1836
- }
1837
- }
1838
- }
1839
- async runHook(environment, name, context2, input) {
1840
- context2 = context(context2, this.session);
1841
- const definition = environment.orb.definition.hooks?.[name];
1842
- if (!definition)
1843
- refuse(Errors.Invalid.Hook, name);
1844
- const plan = this.session.kernel.command(KernelOp.HookPlan, {
1845
- root: context2.root,
1846
- target: environment.orb.info.name,
1847
- hook: name
1848
- });
1849
- const participants = plan.map((operation) => async (ctx, input, next) => {
1850
- return this.runContribution(operation, ctx, input, next);
1851
- });
1852
- return definition.run(context2, input, participants);
1853
- }
1854
- async observe(environment, name, operation, source, input) {
1855
- source = issuedContext(source, this.session);
1856
- const definition = environment.orb.definition.hooks?.[name];
1857
- if (!definition)
1858
- refuse(Errors.Invalid.Hook, name);
1859
- if (!source.invocation)
1860
- throw new TembraError(Errors.Forbidden.ObservationSource);
1861
- const admitted = this.session.kernel.command(KernelOp.BeginHookObservation, {
1862
- source: source.invocation.id,
1863
- orb: environment.orb.info.id,
1864
- operation,
1865
- ...environment.object ? { object: environment.object.id } : {},
1866
- hook: name
1867
- });
1868
- await this.session.track(this.session.calls.root(async () => {
1869
- try {
1870
- const context = new Context(this.session, admitted.invocation.root, admitted.invocation);
1871
- const participants = admitted.plan.map((operation) => async (ctx, input, next) => this.runContribution(operation, ctx, input, next));
1872
- await definition.run(context, input, participants);
1873
- } finally {
1874
- this.session.lifecycle.finishCall(admitted.invocation.id);
1875
- }
1876
- }, false, admitted.invocation.root));
1877
- }
1878
- async runContribution(operation, ctx, input, next) {
1879
- ctx = context(ctx, this.session);
1880
- const contributor = this.operations.get(operation);
1881
- if (!contributor) {
1882
- const native = this.session.options.native;
1883
- if (native?.hasContribution?.(operation) && native.contribute)
1884
- return native.contribute(operation, ctx, input);
1885
- throw new TembraError(Errors.Gone.Contribution);
1886
- }
1887
- const scope = contributor.orb.scope;
1888
- if (!scope)
1889
- throw new TembraError(Errors.Unavailable.OrbScope);
1890
- return this.session.calls.owned(scope, operation, (entered) => contributor.handler(entered, input, next), ctx);
1891
- }
1892
- retire(id) {
1893
- const scopes = this.session.kernel.command(KernelOp.ScopesForOrb, { orb: id });
1894
- const cleanup = this.session.programs.cleanupScopes(scopes);
1895
- this.session.track(cleanup.then(() => {
1896
- for (const [operation, contribution] of this.operations)
1897
- if (contribution.orb.info.id === id)
1898
- this.operations.delete(operation);
1899
- this.records.delete(id);
1900
- this.#ready.delete(id);
1901
- }), true);
1902
- }
1903
- }
1904
-
1905
- // src/runtime/lifecycle.ts
1906
- class Lifecycle {
1907
- session;
1908
- constructor(session) {
1909
- this.session = session;
1910
- }
1911
- get closedDiagnostics() {
1912
- return this.#finalDiagnostics;
1913
- }
1914
- #closed;
1915
- #flushing = false;
1916
- #linger;
1917
- #lingerDeadline;
1918
- #finalDiagnostics;
1919
- flush(initial) {
1920
- if (this.#flushing)
1921
- return;
1922
- this.#flushing = true;
1923
- try {
1924
- for (;; ) {
1925
- const actions = initial ?? this.session.kernel.command(KernelOp.Drain);
1926
- initial = undefined;
1927
- if (!actions.length)
1928
- break;
1929
- for (const action of actions) {
1930
- try {
1931
- this.action(action);
1932
- } catch (error) {
1933
- this.session.report(error);
1934
- }
140
+ carrier.fail(error);
1935
141
  }
1936
- }
1937
- } finally {
1938
- this.#flushing = false;
1939
- this.scheduleLinger();
1940
- }
1941
- }
1942
- finishCall(call) {
1943
- const session = this.session;
1944
- if (!this.#flushing && session.options.native?.finish) {
1945
- const batch = session.options.native.finish(call, session.now());
1946
- if (!batch.actions.length) {
1947
- this.scheduleLinger(batch.deadline);
1948
- return;
1949
- }
1950
- this.flush(batch.actions);
1951
- return;
1952
- }
1953
- session.kernel.command(KernelOp.Tick, { now: session.now() });
1954
- session.kernel.command(KernelOp.FinishCall, { call });
1955
- this.flush();
1956
- }
1957
- action(action) {
1958
- const session = this.session;
1959
- const nativeHandled = session.options.native?.notify?.(action);
1960
- if (nativeHandled && !(action.type === ActionType.ProgramComplete && session.programs.pending(action.id)))
1961
- return;
1962
- switch (action.type) {
1963
- case ActionType.Execute:
1964
- case ActionType.CancelEffects:
1965
- case ActionType.ProgramPrepared:
1966
- case ActionType.ProgramComplete:
1967
- session.programs.dispatch(action);
1968
- break;
1969
- case ActionType.DropValue:
1970
- session.values.drop(action.id);
1971
- session.options.native?.dropValue?.(action.id);
1972
- break;
1973
- case ActionType.CancelRoot:
1974
- session.controllers.get(action.id)?.abort(new TembraError(Errors.Cancelled.Root));
1975
- break;
1976
- case ActionType.CancelTask:
1977
- session.activities.cancel(action.id);
1978
- break;
1979
- case ActionType.Deliver:
1980
- session.activities.deliver(action.id, action.payload, action.operation);
1981
- break;
1982
- case ActionType.DetachSubscription:
1983
- session.activities.detach(action.id);
1984
- break;
1985
- case ActionType.SubscriptionFailed:
1986
- session.activities.failed(action.id);
1987
- break;
1988
- case ActionType.Dispose:
1989
- session.track(this.dispose(action.id), true);
1990
- break;
1991
- case ActionType.CloseResource: {
1992
- break;
1993
- }
1994
- case ActionType.RetireOrb:
1995
- session.handles.retire(action.id);
1996
- session.orbs.retire(action.id);
1997
- break;
1998
- case ActionType.State: {
1999
- const object = session.objects.get(action.id);
2000
- if (!object?.binding)
2001
- break;
2002
- const snapshot = session.snapshot(action.id);
2003
- if (!session.values.has(snapshot.value)) {
2004
- const candidate = session.value(snapshot.value);
2005
- session.publish(object.binding.adopt(object.binding.prepare(candidate), candidate));
2006
- }
2007
- break;
2008
- }
2009
- }
2010
- }
2011
- async dispose(id) {
2012
- const session = this.session;
2013
- const object = session.objects.get(id);
2014
- if (!object) {
2015
- await session.options.native?.dispose(id);
2016
- session.kernel.command(KernelOp.Disposed, { object: id });
2017
- this.flush();
2018
- return;
2019
- }
2020
- object.disposing ??= (async () => {
2021
- const errors = [];
2022
- await object.activation.catch(() => {});
2023
- const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
2024
- owner: { kind: OwnerKind.Object, id }
2025
142
  });
2026
- try {
2027
- await session.programs.cleanupScopes(scopes);
2028
- } catch (error) {
2029
- errors.push(error);
2030
- }
2031
- try {
2032
- if (session.options.native?.hasOrb(object.orb))
2033
- await session.options.native.dispose(id);
2034
- } catch (error) {
2035
- errors.push(error);
2036
- }
2037
- object.binding?.close();
2038
- session.kernel.command(KernelOp.Disposed, { object: id });
2039
- session.objects.delete(id);
2040
- this.flush();
2041
- if (errors.length)
2042
- throw new AggregateError(errors, "Object cleanup failed");
2043
- })();
2044
- return object.disposing;
2045
- }
2046
- scheduleLinger(known) {
2047
- const session = this.session;
2048
- if (session.closing)
2049
- return;
2050
- const deadline = (known === undefined ? session.kernel.command(KernelOp.NextDeadline) : known) ?? undefined;
2051
- if (deadline === this.#lingerDeadline)
2052
- return;
2053
- if (this.#linger !== undefined)
2054
- clearTimeout(this.#linger);
2055
- this.#linger = undefined;
2056
- this.#lingerDeadline = deadline;
2057
- if (deadline === undefined)
2058
- return;
2059
- this.#linger = setTimeout(() => {
2060
- if (this.#lingerDeadline !== deadline)
2061
- return;
2062
- this.#linger = undefined;
2063
- this.#lingerDeadline = undefined;
2064
- session.kernel.command(KernelOp.Tick, { now: session.now() });
2065
- this.flush();
2066
- }, Math.max(0, deadline - session.now()));
2067
- this.#linger.unref?.();
2068
- }
2069
- diagnostics() {
2070
- const session = this.session;
2071
- if (this.#finalDiagnostics)
2072
- return this.#finalDiagnostics;
2073
- return {
2074
- ...session.kernel.command(KernelOp.Diagnostics),
2075
- values: session.values.size,
2076
- pendingJobs: session.jobs.size
2077
- };
2078
- }
2079
- close() {
2080
- const session = this.session;
2081
- this.#closed ??= (async () => {
2082
- session.closing = true;
2083
- clearTimeout(this.#linger);
2084
- this.#linger = undefined;
2085
- this.#lingerDeadline = undefined;
2086
- session.kernel.command(KernelOp.Close);
2087
- await session.replacements.cancel();
2088
- this.flush();
2089
- for (;; ) {
2090
- await session.options.native?.settled?.();
2091
- this.flush();
2092
- const pending = [...session.jobs];
2093
- if (!pending.length)
2094
- break;
2095
- await Promise.allSettled(pending);
2096
- this.flush();
2097
- }
2098
- session.kernel.command(KernelOp.FinishClose);
2099
- session.values.clear();
2100
- session.handles.clear();
2101
- session.orbs.records.clear();
2102
- session.scopes.clear();
2103
- this.#finalDiagnostics = this.diagnostics();
2104
- session.kernel.port.free?.();
2105
- if (session.cleanupErrors.length)
2106
- throw new AggregateError(session.cleanupErrors, "Host cleanup failed");
2107
- })();
2108
- return this.#closed;
2109
- }
2110
- }
2111
-
2112
- // src/runtime/records.ts
2113
- function deferred() {
2114
- let resolve;
2115
- let reject;
2116
- const promise = new Promise((accept, refuse) => {
2117
- resolve = accept;
2118
- reject = refuse;
2119
- });
2120
- promise.catch(() => {});
2121
- return { promise, resolve, reject };
2122
- }
2123
-
2124
- // src/runtime/programs.ts
2125
- function errorText(value, limit) {
2126
- return value.slice(0, limit).replace(/[\uD800-\uDFFF]/gu, "�");
2127
- }
2128
-
2129
- class Programs {
2130
- session;
2131
- scopes = new Map;
2132
- #pending = new Map;
2133
- constructor(session) {
2134
- this.session = session;
2135
- }
2136
- register(environment) {
2137
- const parent = environment.owner.kind === OwnerKind.Host ? undefined : environment.object ? environment.orb.scope : this.session.hostScope;
2138
- this.session.kernel.command(KernelOp.ScopeRegister, {
2139
- scope: environment.id,
2140
- owner: environment.owner,
2141
- orb: environment.orb.info.id,
2142
- parents: parent ? [parent.id] : [],
2143
- dependencies: [...environment.dependencies.values()].map((reference) => this.session.handles.reference(reference).id),
2144
- resources: [...environment.resources.values()].map((resource) => resource.id),
2145
- stateVersion: environment.state?.options.version ?? (environment.state ? 1 : undefined),
2146
- migrate: Boolean(environment.state?.options.migrate)
2147
- });
2148
- }
2149
- activate(scope) {
2150
- return this.run(this.session.kernel.command(KernelOp.ScopeActivate, { scope }));
2151
- }
2152
- cleanup(environments) {
2153
- const scopes = environments.map((environment) => environment.id).filter((scope) => this.session.kernel.command(KernelOp.ScopeExists, { scope }));
2154
- return this.cleanupScopes(scopes);
2155
- }
2156
- cleanupScopes(scopes) {
2157
- return scopes.length ? this.run(this.session.kernel.command(KernelOp.ScopesCleanup, { scopes })) : Promise.resolve();
2158
- }
2159
- pending(program) {
2160
- return this.#pending.has(program);
2161
- }
2162
- run(program) {
2163
- const pending = this.#pending.get(program);
2164
- if (pending)
2165
- return pending.promise;
2166
- const completion = deferred();
2167
- this.#pending.set(program, completion);
2168
- try {
2169
- this.session.kernel.command(KernelOp.ProgramRun, { program });
2170
- this.session.lifecycle.flush();
2171
143
  } catch (error) {
2172
- this.#pending.delete(program);
2173
- completion.reject(error);
2174
- }
2175
- return completion.promise;
2176
- }
2177
- dispatch(action) {
2178
- if (action.type === ActionType.Execute) {
2179
- this.session.track(Promise.allSettled(action.effects.map((effect) => this.execute(effect))).then((settled) => {
2180
- const limit = Math.max(0, Math.min(2048, Math.floor((1024 * 1024 - 128 - settled.length * 96) / (12 * settled.length))));
2181
- const results = settled.map((result) => {
2182
- if (result.status === "fulfilled")
2183
- return { value: result.value ?? null };
2184
- try {
2185
- const { code, reason, message } = failure(result.reason);
2186
- if (!Object.values(Code).includes(code) || typeof reason !== "string" || typeof message !== "string")
2187
- return { error: Errors.Unavailable.Callback };
2188
- return {
2189
- error: {
2190
- code,
2191
- reason: errorText(reason, limit),
2192
- message: errorText(message, limit)
2193
- }
2194
- };
2195
- } catch {
2196
- return { error: Errors.Unavailable.Callback };
2197
- }
2198
- });
2199
- this.session.kernel.command(KernelOp.ProgramCompleteStep, {
2200
- program: action.id,
2201
- results
2202
- });
2203
- this.session.lifecycle.flush();
2204
- }));
2205
- } else if (action.type === ActionType.CancelEffects) {
2206
- for (const effect of action.effects) {
2207
- if (effect.type !== EffectType.Open && effect.type !== EffectType.Restore)
2208
- continue;
2209
- const resource = this.session.resources.find(effect.resource);
2210
- if (resource)
2211
- resource.controller.abort(new TembraError(Errors.Cancelled.EngineEffect));
2212
- else if (this.session.options.native?.cancelEffect) {
2213
- const cancel = this.session.options.native.cancelEffect.bind(this.session.options.native);
2214
- this.session.track(Promise.resolve().then(() => cancel(effect))).catch((error) => this.session.report(error));
2215
- }
2216
- }
2217
- } else {
2218
- const completion = this.#pending.get(action.id);
2219
- this.#pending.delete(action.id);
2220
- if (action.error) {
2221
- const error = new TembraError(action.error);
2222
- if (completion)
2223
- completion.reject(error);
2224
- else {
2225
- this.session.cleanupErrors.push(error);
2226
- this.session.report(error);
2227
- }
2228
- } else
2229
- completion?.resolve();
2230
- }
2231
- }
2232
- resource(id) {
2233
- const direct = this.session.resources.find(id);
2234
- if (direct)
2235
- return direct;
2236
- throw new TembraError(Errors.Gone.Resource);
2237
- }
2238
- async execute(effect) {
2239
- const environment = effect.scope === undefined ? undefined : this.scopes.get(effect.scope);
2240
- if (effect.scope !== undefined && !environment && this.session.options.native)
2241
- return this.session.options.native.effect(effect);
2242
- if ((effect.type === EffectType.Close || effect.type === EffectType.Open) && !this.session.resources.find(effect.resource) && this.session.options.native)
2243
- return this.session.options.native.effect(effect);
2244
- switch (effect.type) {
2245
- case EffectType.Open:
2246
- await this.resource(effect.resource).start();
2247
- break;
2248
- case EffectType.Close:
2249
- await this.session.resources.close(this.resource(effect.resource));
2250
- break;
2251
- case EffectType.Restore:
2252
- await this.session.resources.reopen(this.resource(effect.previous), effect.resource);
2253
- break;
2254
- case EffectType.Stop:
2255
- if (environment)
2256
- await this.session.activities.stop(environment);
2257
- break;
2258
- case EffectType.Prepare: {
2259
- if (!environment)
2260
- throw new TembraError(Errors.Gone.Scope);
2261
- this.session.activities.prepare(environment, effect.previous ? this.scopes.get(effect.previous) : undefined);
2262
- break;
2263
- }
2264
- case EffectType.Validate:
2265
- validate(this.session.value(effect.value), environment.state.options);
2266
- break;
2267
- case EffectType.Initialize:
2268
- return this.candidate(environment, environment.state.initial);
2269
- case EffectType.Migrate: {
2270
- const state = environment.state;
2271
- return this.candidate(environment, state.options.migrate(this.session.value(effect.value), effect.version));
2272
- }
2273
- case EffectType.Adopt: {
2274
- const orbs = new Map;
2275
- for (const pair of effect.replacements) {
2276
- if (!pair.next)
2277
- continue;
2278
- const next = this.scopes.get(pair.next);
2279
- for (const [resource, declaration] of next.resourceDeclarations ?? [])
2280
- resource.options = declaration;
2281
- delete next.resourceDeclarations;
2282
- orbs.set(next.orb.info.id, next.orb);
2283
- if (next.object) {
2284
- if (next.state)
2285
- next.object.binding = next.state.binding;
2286
- next.object.orb = next.orb.info.id;
2287
- next.object.versions.set(next.orb.info.id, next);
2288
- }
2289
- }
2290
- for (const record of orbs.values()) {
2291
- this.session.orbs.records.set(record.info.id, record);
2292
- this.session.orbs.registerContributions(record);
2293
- }
2294
- for (const pair of effect.replacements) {
2295
- const next = pair.next ? this.scopes.get(pair.next) : undefined;
2296
- if (next?.object)
2297
- this.session.handles.refreshReferences(next.object, next.orb);
2298
- }
2299
- for (const pair of effect.replacements)
2300
- if (pair.next)
2301
- this.scopes.get(pair.next)?.state?.publish?.();
2302
- break;
2303
- }
2304
- case EffectType.Start:
2305
- if (environment) {
2306
- this.session.activities.start(environment);
2307
- if (environment.object)
2308
- environment.object.live = true;
2309
- }
2310
- break;
2311
- case EffectType.Drop: {
2312
- if (!environment)
2313
- break;
2314
- for (const reference of environment.dependencies.values())
2315
- this.session.handles.revoke(this.session.handles.reference(reference).id);
2316
- environment.dependencies.clear();
2317
- for (const resource of environment.resources.values())
2318
- this.session.resources.closedRecords.delete(resource.id);
2319
- environment.phase = EnvironmentPhase.Closed;
2320
- if (environment.object)
2321
- environment.object.versions.delete(environment.orb.info.id);
2322
- this.scopes.delete(environment.id);
2323
- break;
2324
- }
2325
- default:
2326
- throw new TembraError(Errors.Unsupported.EngineEffect, effect.type);
144
+ carrier.abandon(error);
145
+ return carrier.settled;
2327
146
  }
147
+ carrier.begun();
148
+ return carrier.settled;
2328
149
  }
2329
- candidate(environment, candidate) {
2330
- const state = environment.state;
2331
- const value = validate(candidate, state.options);
2332
- const id = this.session.values.put(value);
2333
- state.publish = () => this.session.publish(state.binding.adopt(state.binding.prepare(value), value));
2334
- return id;
150
+ close() {
151
+ this.transport.close();
2335
152
  }
2336
153
  }
2337
-
2338
- // src/runtime/references.ts
2339
- var references = new WeakMap;
2340
- var finalizer = typeof FinalizationRegistry === "undefined" ? undefined : new FinalizationRegistry((held) => held.session.deref()?.handles.release(held.id));
2341
-
2342
- class References {
2343
- session;
2344
- constructor(session) {
2345
- this.session = session;
2346
- }
2347
- #metadata = new Map;
2348
- #byObject = new Map;
2349
- activateAcquired(acquired, address, requiredMethods = []) {
2350
- const session = this.session;
2351
- let object = session.objects.get(acquired.object);
2352
- if (!object) {
2353
- const activation = deferred();
2354
- object = {
2355
- id: acquired.object,
2356
- address,
2357
- orb: acquired.orb,
2358
- versions: new Map,
2359
- activation: activation.promise
2360
- };
2361
- session.objects.set(object.id, object);
2362
- const record = object;
2363
- session.track(session.scopes.activate(record, acquired).then(activation.resolve, (error) => {
2364
- record.error = error;
2365
- try {
2366
- session.kernel.command(KernelOp.Fail, { object: record.id });
2367
- } catch {}
2368
- activation.reject(error);
2369
- session.lifecycle.flush();
2370
- }));
2371
- }
2372
- if (!this.claimExists(acquired.reference))
2373
- return object.activation;
2374
- const provider = this.orbMetadata(object.orb);
2375
- const methods = provider.services.find((service) => service.name === address.service)?.methods ?? [];
2376
- const record = {
2377
- id: acquired.reference,
2378
- object: acquired.object,
2379
- address,
2380
- methods: new Set(methods),
2381
- requiredMethods: new Set(requiredMethods),
2382
- stateCleanups: new Set,
2383
- ready: object.activation,
2384
- released: false,
2385
- nativeOwned: true
2386
- };
2387
- const access = session.orbs.records.get(object.orb)?.definition.services?.[address.service]?.access;
2388
- try {
2389
- this.referenceMethods(record, methods, access);
2390
- } catch (error) {
2391
- if (session.kernel.features.views && this.claimExists(record.id))
2392
- session.kernel.command(KernelOp.Restrict, { reference: record.id, methods: [] });
2393
- throw error;
2394
- }
2395
- session.references.set(record.id, record);
2396
- let owned = this.#byObject.get(record.object);
2397
- if (!owned)
2398
- this.#byObject.set(record.object, owned = new Set);
2399
- owned.add(record);
2400
- return object.activation;
2401
- }
2402
- hold(definition, key, options = {}, ctx) {
2403
- let service;
2404
- if (typeof definition === "string")
2405
- service = definition;
2406
- else {
2407
- const acquisition = serviceAcquisition(definition, options);
2408
- service = acquisition.name;
2409
- options = acquisition.options;
2410
- }
2411
- const session = this.session;
2412
- if (ctx)
2413
- context(ctx, session);
2414
- session.kernel.command(KernelOp.Tick, { now: session.now() });
2415
- const address = {
2416
- service,
2417
- key: typeof key === "string" ? [key] : [...key],
2418
- principal: options.principal ?? ctx?.principal ?? session.principal
2419
- };
2420
- const acquired = session.kernel.command(KernelOp.Acquire, {
2421
- ...address,
2422
- apiVersion: options.apiVersion ?? 0,
2423
- methods: options.methods ?? []
2424
- });
2425
- let object = session.objects.get(acquired.object);
2426
- if (!object) {
2427
- const activation = deferred();
2428
- object = {
2429
- id: acquired.object,
2430
- address,
2431
- orb: acquired.orb,
2432
- versions: new Map,
2433
- activation: activation.promise
2434
- };
2435
- session.objects.set(object.id, object);
2436
- const record = object;
2437
- queueMicrotask(() => {
2438
- session.track(session.scopes.activate(record, acquired).then(activation.resolve, (error) => {
2439
- record.error = error;
2440
- try {
2441
- session.kernel.command(KernelOp.Fail, { object: record.id });
2442
- } catch {}
2443
- activation.reject(error);
2444
- session.lifecycle.flush();
2445
- }));
2446
- });
2447
- }
2448
- const provider = this.orbMetadata(acquired.orb);
2449
- const methods = new Set(provider.services.find((s) => s.name === service)?.methods ?? []);
2450
- const record = {
2451
- id: acquired.reference,
2452
- object: acquired.object,
2453
- address,
2454
- methods,
2455
- requiredMethods: new Set(options.methods ?? []),
2456
- stateCleanups: new Set,
2457
- ready: object.activation,
2458
- released: false,
2459
- ...ctx ? { context: ctx } : {}
2460
- };
2461
- const nativeAccess = session.options.native?.access?.(acquired.orb, service, address.principal);
2462
- const access = nativeAccess ? () => ({ methods: nativeAccess }) : session.orbs.records.get(acquired.orb)?.definition.services?.[service]?.access;
2463
- try {
2464
- this.referenceMethods(record, methods, access);
2465
- } catch (error) {
2466
- session.kernel.command(KernelOp.Release, { reference: record.id });
2467
- session.kernel.command(KernelOp.Forget, { reference: record.id });
2468
- session.lifecycle.flush();
2469
- throw error;
2470
- }
2471
- session.references.set(record.id, record);
2472
- let owned = this.#byObject.get(record.object);
2473
- if (!owned) {
2474
- owned = new Set;
2475
- this.#byObject.set(record.object, owned);
2476
- }
2477
- owned.add(record);
2478
- if (ctx) {
2479
- let owned = session.rootReferences.get(ctx.root);
2480
- if (!owned) {
2481
- owned = new Set;
2482
- session.rootReferences.set(ctx.root, owned);
2483
- }
2484
- owned.add(record.id);
2485
- }
2486
- const check = () => {
2487
- if (record.released)
2488
- throw new TembraError(Errors.Released.Reference);
2489
- if (session.closing)
2490
- throw new TembraError(Errors.Gone.Reference);
2491
- const object = session.objects.get(record.object);
2492
- if (!object || object.disposing || object.error)
2493
- throw new TembraError(Errors.Gone.Reference);
2494
- if (!object.live)
2495
- throw new TembraError(Errors.Unavailable.NotReady);
2496
- };
2497
- const target = {
2498
- get ready() {
2499
- return record.ready;
2500
- },
2501
- get status() {
2502
- return record.released ? Status.Released : recordSession.closing ? Status.Gone : recordSession.kernel.command(KernelOp.Status, { reference: record.id });
2503
- },
2504
- get state() {
2505
- check();
2506
- const binding = recordSession.objects.get(record.object)?.binding;
2507
- if (!binding)
2508
- refuse(Errors.Invalid.State, "Service does not expose state");
2509
- return consumerState(binding, check, record.stateCleanups);
2510
- },
2511
- release: () => this.release(record.id),
2512
- opaque: (name) => {
2513
- check();
2514
- const object = session.objects.get(record.object);
2515
- const resource = object.versions.get(object.orb)?.resources.get(name);
2516
- if (!resource?.options.opaque)
2517
- throw new TembraError(Errors.Forbidden.Opaque, name);
2518
- return resource.handle.value;
2519
- }
2520
- };
2521
- const recordSession = session;
2522
- const proxy = new Proxy(target, {
2523
- get: (target, property, receiver) => {
2524
- if (property === "then")
2525
- return;
2526
- if (Object.hasOwn(target, property))
2527
- return Reflect.get(target, property, receiver);
2528
- if (typeof property !== "string")
2529
- return;
2530
- if (!record.methods.has(property))
2531
- return;
2532
- return (...arguments_) => {
2533
- let callContext = record.context;
2534
- if (isContext(arguments_.at(-1)))
2535
- callContext = arguments_.pop();
2536
- return callContext ? session.calls.invoke(record, property, arguments_, context(callContext, session)) : session.calls.root((ctx) => session.calls.invoke(record, property, arguments_, ctx), false, undefined, record.address.principal);
2537
- };
2538
- }
2539
- });
2540
- references.set(proxy, { session, record });
2541
- finalizer?.register(proxy, { session: new WeakRef(session), id: record.id }, record);
2542
- return proxy;
2543
- }
2544
- async get(service, key, options = {}, ctx) {
2545
- const reference = this.hold(service, key, options, ctx);
2546
- try {
2547
- await reference.ready;
2548
- return reference;
2549
- } catch (error) {
2550
- reference.release();
2551
- throw error;
2552
- }
2553
- }
2554
- reference(value) {
2555
- const issued = typeof value === "object" && value !== null ? references.get(value) : undefined;
2556
- if (!issued || issued.session !== this.session)
2557
- refuse(Errors.Invalid.Reference, "An issued local reference is required");
2558
- return issued.record;
2559
- }
2560
- orbMetadata(id) {
2561
- const definition = this.session.orbs.records.get(id)?.info;
2562
- if (definition)
2563
- return definition;
2564
- let metadata = this.#metadata.get(id);
2565
- if (!metadata) {
2566
- metadata = this.session.kernel.command(KernelOp.Orb, { id });
2567
- this.#metadata.set(id, metadata);
2568
- }
2569
- return metadata;
2570
- }
2571
- referenceMethods(record, methods, access, resetAccess = false) {
2572
- const session = this.session;
2573
- if (access && !session.kernel.features.views)
2574
- throw new TembraError(Errors.Unsupported.Views);
2575
- const allowed = access ? new Set(access(record.address.principal).methods) : undefined;
2576
- const visible = new Set([...methods].filter((method) => (!record.requiredMethods.size || record.requiredMethods.has(method)) && (!allowed || allowed.has(method))));
2577
- if (access || resetAccess && session.kernel.features.views)
2578
- session.kernel.command(KernelOp.Restrict, {
2579
- reference: record.id,
2580
- methods: [...visible]
2581
- });
2582
- record.methods = visible;
2583
- }
2584
- refreshReferences(object, orb) {
2585
- const session = this.session;
2586
- const service = orb.definition.services?.[object.address.service];
2587
- if (!service)
2588
- return;
2589
- const methods = Object.keys(service.methods);
2590
- for (const reference of this.#byObject.get(object.id) ?? []) {
2591
- if (reference.released)
2592
- continue;
2593
- if (reference.nativeOwned && !this.claimExists(reference.id)) {
2594
- this.revoke(reference.id);
2595
- continue;
2596
- }
2597
- try {
2598
- this.referenceMethods(reference, methods, service.access, true);
2599
- } catch (error) {
2600
- reference.methods.clear();
2601
- if (!reference.released && session.kernel.features.views)
2602
- session.kernel.command(KernelOp.Restrict, { reference: reference.id, methods: [] });
2603
- session.report(error);
2604
- }
2605
- }
2606
- }
2607
- claimExists(reference) {
2608
- try {
2609
- const status = this.session.kernel.command(KernelOp.Status, { reference });
2610
- return status !== Status.Released && status !== Status.Gone;
2611
- } catch (error) {
2612
- if (error instanceof TembraError && (error.code === Code.Gone || error.code === Code.Released))
2613
- return false;
2614
- throw error;
2615
- }
2616
- }
2617
- forget(record) {
2618
- for (const cleanup of record.stateCleanups)
2619
- cleanup();
2620
- record.stateCleanups.clear();
2621
- this.session.references.delete(record.id);
2622
- const owned = this.#byObject.get(record.object);
2623
- owned?.delete(record);
2624
- if (!owned?.size)
2625
- this.#byObject.delete(record.object);
2626
- }
2627
- release(id) {
2628
- const session = this.session;
2629
- const record = session.references.get(id);
2630
- if (!record || record.released)
2631
- return;
2632
- record.released = true;
2633
- finalizer?.unregister(record);
2634
- if (session.lifecycle.closedDiagnostics) {
2635
- this.forget(record);
2636
- return;
2637
- }
2638
- session.kernel.command(KernelOp.Tick, { now: session.now() });
2639
- session.kernel.command(KernelOp.Release, { reference: id });
2640
- session.kernel.command(KernelOp.Forget, { reference: id });
2641
- this.forget(record);
2642
- session.lifecycle.flush();
2643
- }
2644
- revoke(id) {
2645
- const record = this.session.references.get(id);
2646
- if (!record)
2647
- return;
2648
- record.released = true;
2649
- finalizer?.unregister(record);
2650
- this.forget(record);
2651
- }
2652
- retire(orb) {
2653
- this.#metadata.delete(orb);
2654
- }
2655
- clear() {
2656
- for (const reference of this.session.references.values())
2657
- this.forget(reference);
2658
- this.session.references.clear();
2659
- this.#byObject.clear();
2660
- this.#metadata.clear();
154
+ function respond(operation) {
155
+ try {
156
+ return `{ "ok":${reply(operation())}}`;
157
+ } catch (error) {
158
+ return refusal(error);
2661
159
  }
2662
160
  }
2663
-
2664
- // src/runtime/reload.ts
2665
- class Replacements {
2666
- session;
2667
- #pending;
2668
- #program;
2669
- #prepared;
2670
- constructor(session) {
2671
- this.session = session;
2672
- }
2673
- async replace(definitions, options = {}, remove = []) {
2674
- return (await this.prepare(definitions, options, remove)).commit();
2675
- }
2676
- prepare(definitions, options = {}, remove = []) {
2677
- if (this.session.closing)
2678
- return Promise.reject(new TembraError(Errors.Closed.Host));
2679
- if (this.#pending)
2680
- return Promise.reject(new TembraError(Errors.Conflict.ReloadRunning));
2681
- const pending = this.capture(definitions, options, remove);
2682
- this.#pending = pending;
2683
- pending.catch(() => {
2684
- if (this.#pending === pending)
2685
- this.#pending = undefined;
2686
- });
2687
- return pending;
2688
- }
2689
- async cancel() {
2690
- if (this.#prepared?.status === ReloadStatus.Prepared)
2691
- return this.#prepared.abort();
2692
- if (this.#program !== undefined) {
2693
- this.session.kernel.command(KernelOp.ProgramAbort, { program: this.#program });
2694
- const settled = this.session.programs.run(this.#program);
2695
- this.session.lifecycle.flush();
2696
- await settled.catch(() => {});
2697
- }
2698
- await this.#pending?.catch(() => {
2699
- return;
2700
- });
2701
- }
2702
- async capture(definitions, options, remove) {
2703
- const session = this.session;
2704
- const declarations = session.orbs.declarations(definitions);
2705
- const reload = session.kernel.command(KernelOp.Prepare, {
2706
- orbs: declarations.metadata,
2707
- remove
2708
- });
2709
- const definitionsByName = new Map(declarations.definitions.map((definition) => [definition.name, definition]));
2710
- const records = reload.orbs.map((info) => ({
2711
- info,
2712
- definition: definitionsByName.get(info.name),
2713
- ticket: reload.id
2714
- }));
2715
- const recordsById = new Map(records.map((record) => [record.info.id, record]));
2716
- let program;
2717
- try {
2718
- for (const record of records)
2719
- session.orbs.scope(record);
2720
- for (const id of reload.objects) {
2721
- const object = session.objects.get(id);
2722
- if (!object)
2723
- continue;
2724
- const orb = reload.providers[object.address.service];
2725
- const record = orb === undefined ? undefined : recordsById.get(orb);
2726
- if (record)
2727
- session.scopes.createEnvironment(object, record);
2728
- }
2729
- for (const record of records)
2730
- record.ticket = undefined;
2731
- program = session.kernel.command(KernelOp.ScopesReloadRegistered, {
2732
- ticket: reload.id,
2733
- deadline: options.deadline ?? 5000,
2734
- now: session.now()
2735
- });
2736
- this.#program = program;
2737
- await session.programs.run(program);
2738
- if (session.closing)
2739
- await session.programs.run(program);
2740
- } catch (error) {
2741
- this.#program = undefined;
2742
- if (program === undefined) {
2743
- session.kernel.command(KernelOp.Abort, { ticket: reload.id });
2744
- const scopes = reload.orbs.flatMap((orb) => session.kernel.command(KernelOp.ScopesForOrb, { orb: orb.id }));
2745
- await session.programs.cleanupScopes(scopes);
2746
- }
2747
- throw error;
2748
- }
2749
- this.#program = undefined;
2750
- const id = program;
2751
- const report = {
2752
- codeVersion: reload.codeVersion,
2753
- orbs: records.map((record) => record.info.name)
2754
- };
2755
- let status = ReloadStatus.Prepared;
2756
- return this.#prepared = {
2757
- report,
2758
- get status() {
2759
- return status;
2760
- },
2761
- commit: async () => {
2762
- if (status !== ReloadStatus.Prepared)
2763
- throw new TembraError(Errors.Conflict.ReloadTicket);
2764
- this.#prepared = undefined;
2765
- try {
2766
- session.kernel.command(KernelOp.ProgramCommit, { program: id });
2767
- } catch (error) {
2768
- session.kernel.command(KernelOp.ProgramAbort, { program: id });
2769
- await session.programs.run(id).catch(() => {});
2770
- status = ReloadStatus.Aborted;
2771
- this.#pending = undefined;
2772
- throw error;
2773
- }
2774
- status = ReloadStatus.Committed;
2775
- this.#pending = undefined;
2776
- await session.programs.run(id);
2777
- return report;
2778
- },
2779
- abort: async () => {
2780
- if (status === ReloadStatus.Aborted)
2781
- return;
2782
- if (status !== ReloadStatus.Prepared)
2783
- throw new TembraError(Errors.Conflict.AlreadyCommitted);
2784
- status = ReloadStatus.Aborted;
2785
- this.#prepared = undefined;
2786
- this.#pending = undefined;
2787
- session.kernel.command(KernelOp.ProgramAbort, { program: id });
2788
- try {
2789
- await session.programs.run(id);
2790
- } catch (error) {
2791
- if (!(error instanceof TembraError) || error.reason !== Reason.ReloadAborted)
2792
- throw error;
2793
- }
2794
- }
2795
- };
2796
- }
161
+ function nodeField([name, value]) {
162
+ return { name, value: Buffer.from(value.buffer, value.byteOffset, value.byteLength) };
2797
163
  }
2798
-
2799
- // src/runtime/resources.ts
2800
- var issued2 = new WeakMap;
2801
-
2802
- class Resources {
2803
- session;
2804
- records = new Map;
2805
- closedRecords = new Map;
2806
- constructor(session) {
2807
- this.session = session;
2808
- }
2809
- find(id) {
2810
- return this.records.get(id) ?? this.closedRecords.get(id);
2811
- }
2812
- dependencyIds(options) {
2813
- const dependencies = [];
2814
- for (const dependency of options.deps ?? []) {
2815
- const resource = typeof dependency === "object" && dependency !== null ? issued2.get(dependency) : undefined;
2816
- if (resource) {
2817
- if (resource.session !== this.session)
2818
- refuse(Errors.Invalid.ResourceHost, "Resource dependencies must belong to the same host");
2819
- dependencies.push(resource.id);
2820
- } else {
2821
- this.session.handles.reference(dependency);
2822
- }
2823
- }
2824
- return dependencies;
2825
- }
2826
- register(environment, name, options) {
2827
- return this.session.kernel.command(KernelOp.Resource, {
2828
- owner: environment.owner,
2829
- name,
2830
- version: options.version ?? 1,
2831
- exclusive: options.exclusive ?? false,
2832
- dependencies: this.dependencyIds(options)
2833
- }).id;
2834
- }
2835
- redeclare(environment, previous) {
2836
- for (const resource of previous.resources.values()) {
2837
- this.records.delete(resource.id);
2838
- this.closedRecords.delete(resource.id);
2839
- resource.reset(this.register(environment, resource.name, resource.options));
2840
- resource.dependencies = this.dependencyIds(resource.options);
2841
- this.records.set(resource.id, resource);
2842
- environment.resources.set(resource.name, resource);
2843
- }
2844
- }
2845
- declare(environment, name, options) {
2846
- if (!name || typeof options.open !== "function")
2847
- refuse(Errors.Invalid.Resource);
2848
- const id = this.register(environment, name, options);
2849
- const reused = this.records.get(id);
2850
- if (reused) {
2851
- (environment.resourceDeclarations ??= new Map).set(reused, options);
2852
- return reused;
2853
- }
2854
- const controller = new AbortController;
2855
- const handle = Object.freeze({
2856
- get value() {
2857
- if (environment.phase === EnvironmentPhase.Declaring)
2858
- refuse(Errors.Invalid.ResourceInFactory, "Resources open after declaration");
2859
- const value = record.session.kernel.command(KernelOp.ResourceValue, {
2860
- resource: record.id
2861
- });
2862
- return record.session.value(value);
2863
- },
2864
- version: options.version ?? 1
2865
- });
2866
- const record = {
2867
- id,
2868
- name,
2869
- options,
2870
- handle,
2871
- dependencies: this.dependencyIds(options),
2872
- controller,
2873
- session: this.session,
2874
- reset: (id) => {
2875
- record.id = id;
2876
- record.controller = new AbortController;
2877
- delete record.value;
2878
- delete record.closed;
2879
- delete record.started;
2880
- },
2881
- start: () => {
2882
- record.started ??= (async () => {
2883
- const declaration = record.options;
2884
- const value = await declaration.open(record.controller.signal);
2885
- const id = this.session.values.put(value);
2886
- try {
2887
- this.session.kernel.command(KernelOp.ResourceOpened, {
2888
- resource: record.id,
2889
- value: id
2890
- });
2891
- } catch (error) {
2892
- this.session.values.drop(id);
2893
- if (declaration.close)
2894
- await this.session.calls.root((ctx) => declaration.close(value, ctx), true);
2895
- throw error;
2896
- }
2897
- record.value = id;
2898
- })();
2899
- record.started.catch(() => {});
2900
- return record.started;
2901
- }
2902
- };
2903
- issued2.set(handle, record);
2904
- this.records.set(id, record);
2905
- return record;
2906
- }
2907
- async close(record) {
2908
- record.closed ??= (async () => {
2909
- record.controller.abort(new TembraError(Errors.Cancelled.Resource));
2910
- await record.started?.catch(() => {});
2911
- try {
2912
- if (record.value !== undefined && record.options.close) {
2913
- const value = this.session.value(record.value);
2914
- await this.session.calls.root((ctx) => record.options.close(value, ctx), true);
2915
- }
2916
- } finally {
2917
- this.session.kernel.command(KernelOp.ResourceClosed, { resource: record.id });
2918
- this.records.delete(record.id);
2919
- this.closedRecords.set(record.id, record);
2920
- this.session.lifecycle.flush();
2921
- }
2922
- })();
2923
- return record.closed;
2924
- }
2925
- async reopen(record, id) {
2926
- this.closedRecords.delete(record.id);
2927
- record.reset(id);
2928
- this.records.set(id, record);
2929
- await record.start();
164
+ function bytes(value) {
165
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
166
+ }
167
+ function fields(value) {
168
+ return value.map((field) => [field.name, bytes(field.value)]);
169
+ }
170
+ function carrierEvent(event) {
171
+ switch (event.kind) {
172
+ case "refused":
173
+ return { kind: "refused", code: bytes(event.code) };
174
+ case "data":
175
+ return { kind: "data", data: bytes(event.data) };
176
+ case "head":
177
+ return { kind: "head", status: event.status, fields: fields(event.fields) };
178
+ case "trailers":
179
+ return { kind: "trailers", fields: fields(event.fields) };
180
+ default:
181
+ return event;
2930
182
  }
2931
183
  }
2932
184
 
2933
- // src/runtime/scopes.ts
2934
- class Scopes {
2935
- session;
2936
- constructor(session) {
2937
- this.session = session;
2938
- }
2939
- #hostResources = new Map;
2940
- #pendingHostScopes = new Set;
2941
- #hostActivation;
2942
- environment(owner, orb, object) {
2943
- const environment = {
2944
- id: this.session.kernel.command(KernelOp.Allocate),
2945
- owner,
2946
- orb,
2947
- ...object ? { object } : {},
2948
- phase: EnvironmentPhase.Declaring,
2949
- value: {},
2950
- dependencies: new Map,
2951
- resources: new Map,
2952
- tasks: [],
2953
- listeners: []
2954
- };
2955
- this.session.programs.scopes.set(environment.id, environment);
2956
- return environment;
2957
- }
2958
- async activate(object, acquired) {
2959
- const session = this.session;
2960
- if (session.options.native?.hasOrb(acquired.orb)) {
2961
- await session.options.native.activate(object.id, acquired.orb, object.address.service, object.address.key, object.address.principal);
2962
- const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
2963
- owner: { kind: OwnerKind.Object, id: object.id }
2964
- });
2965
- await Promise.all(scopes.map((scope) => session.programs.activate(scope)));
2966
- try {
2967
- session.snapshot(object.id);
2968
- object.binding = new StateBinding(session, object.id);
2969
- } catch {}
2970
- } else {
2971
- const orb = session.orbs.records.get(acquired.orb);
2972
- if (!orb)
2973
- refuse(Errors.Invalid.OrbGone);
2974
- await session.orbs.ready(orb);
2975
- const environment = this.createEnvironment(object, orb);
2976
- object.versions.set(orb.info.id, environment);
2977
- await this.session.programs.activate(environment.id);
2978
- }
2979
- if (session.kernel.command(KernelOp.Status, { reference: acquired.reference }) === Status.Loading)
2980
- session.kernel.command(KernelOp.Ready, { object: object.id });
2981
- object.live = true;
2982
- session.lifecycle.flush();
2983
- }
2984
- createEnvironment(object, orb) {
2985
- const definition = orb.definition.services?.[object.address.service];
2986
- if (!definition)
2987
- refuse(Errors.Invalid.ServiceGone);
2988
- const environment = this.environment({ kind: OwnerKind.Object, id: object.id }, orb, object);
2989
- try {
2990
- const value = definition.create?.(new Declaration(this.session, environment)) ?? {};
2991
- if (value && typeof value.then === "function")
2992
- refuse(Errors.Invalid.AsyncFactory, "Factories must be synchronous");
2993
- environment.value = value;
2994
- return environment;
2995
- } finally {
2996
- environment.phase = EnvironmentPhase.Prepared;
2997
- this.session.programs.register(environment);
2998
- }
2999
- }
3000
- readyHostScope() {
3001
- const session = this.session;
3002
- if (session.closing)
3003
- return Promise.reject(new TembraError(Errors.Closed.Host));
3004
- if (this.#hostActivation)
3005
- return this.#hostActivation;
3006
- const activation = (async () => {
3007
- if (session.hostScope.phase === EnvironmentPhase.Closed)
3008
- session.hostScope = await this.redeclareHostScope(session.hostScope);
3009
- await this.session.programs.activate(session.hostScope.id);
3010
- while (this.#pendingHostScopes.size) {
3011
- let environment = this.#pendingHostScopes.values().next().value;
3012
- if (environment.phase === EnvironmentPhase.Closed || [...environment.resources.values()].some((resource) => session.resources.dependencyIds(resource.options).some((id, index) => id !== resource.dependencies[index]))) {
3013
- const previous = environment;
3014
- environment = await this.redeclareHostScope(previous);
3015
- this.#pendingHostScopes.delete(previous);
3016
- this.#pendingHostScopes.add(environment);
3017
- }
3018
- await this.session.programs.activate(environment.id);
3019
- this.#pendingHostScopes.delete(environment);
3020
- }
3021
- })();
3022
- this.#hostActivation = activation;
3023
- const clear = () => {
3024
- if (this.#hostActivation === activation)
3025
- this.#hostActivation = undefined;
3026
- };
3027
- activation.then(clear, clear);
3028
- return activation;
3029
- }
3030
- async redeclareHostScope(previous) {
3031
- const session = this.session;
3032
- await session.programs.cleanup([previous]);
3033
- const environment = this.environment({ kind: OwnerKind.Host }, previous.orb);
3034
- session.resources.redeclare(environment, previous);
3035
- environment.phase = EnvironmentPhase.Prepared;
3036
- session.programs.register(environment);
3037
- return environment;
3038
- }
3039
- requirement(environment, service) {
3040
- const own = environment.orb.definition.services?.[service];
3041
- if (own)
3042
- return { service, apiVersion: environment.orb.info.apiVersion };
3043
- for (const [alias, requirement] of Object.entries(environment.orb.definition.requires ?? {})) {
3044
- let provider;
3045
- try {
3046
- provider = this.session.kernel.command(KernelOp.OrbNamed, {
3047
- name: requirement.orb ?? alias,
3048
- ticket: environment.orb.ticket
3049
- });
3050
- } catch (error) {
3051
- if (error instanceof TembraError && error.code === Code.Gone && error.reason === Reason.Orb)
3052
- continue;
3053
- throw error;
3054
- }
3055
- const selected = alias === service ? provider.services.find((s) => s.name === alias) ?? (provider.services.length === 1 ? provider.services[0] : undefined) : provider.services.find((s) => s.name === service);
3056
- if (!selected)
3057
- continue;
3058
- const methods = requirement.services?.[selected.name] ?? requirement.methods;
3059
- if (!methods)
3060
- throw new TembraError(Errors.Forbidden.UndeclaredService, service);
3061
- return { service: selected.name, apiVersion: requirement.apiVersion, methods };
3062
- }
3063
- throw new TembraError(Errors.Forbidden.UndeclaredDependency, service);
3064
- }
3065
- hostResource(name) {
3066
- const resource = this.#hostResources.get(name);
3067
- if (!resource)
3068
- throw new TembraError(Errors.Forbidden.HostResource, name);
3069
- return resource.handle;
3070
- }
3071
- resource(name, options) {
3072
- const session = this.session;
3073
- if (session.closing)
3074
- throw new TembraError(Errors.Closed.Host);
3075
- if (this.#hostResources.has(name))
3076
- refuse(Errors.Invalid.DuplicateResource);
3077
- const environment = this.environment({ kind: OwnerKind.Host }, session.hostScope.orb);
3078
- try {
3079
- const resource = new Declaration(session, environment).resource(name, options);
3080
- this.#hostResources.set(name, environment.resources.get(name));
3081
- environment.phase = EnvironmentPhase.Prepared;
3082
- session.programs.register(environment);
3083
- this.#pendingHostScopes.add(environment);
3084
- session.track(this.readyHostScope()).catch((error) => session.report(error));
3085
- return resource;
3086
- } catch (error) {
3087
- session.programs.scopes.delete(environment.id);
3088
- throw error;
3089
- }
3090
- }
3091
- registerHost(environment) {
3092
- for (const [name, resource] of environment.resources)
3093
- this.#hostResources.set(name, resource);
3094
- }
3095
- clear() {
3096
- this.#hostResources.clear();
3097
- this.#pendingHostScopes.clear();
3098
- }
185
+ // src/interpreter/node.ts
186
+ import { createRequire } from "node:module";
187
+ function directoryFilesystem(path) {
188
+ return Object.freeze({ kind: "directory", path });
3099
189
  }
3100
190
 
3101
- // src/runtime/session.ts
3102
- class Session {
191
+ class NodeExecution {
3103
192
  options;
3104
- contextTokens = new WeakMap;
3105
- calls = new Calls(this);
3106
- handles = new References(this);
3107
- scopes = new Scopes(this);
3108
- lifecycle = new Lifecycle(this);
3109
- kernel;
3110
- values;
3111
- resources = new Resources(this);
3112
- activities = new Activities(this);
3113
- orbs = new Orbs(this);
3114
- replacements = new Replacements(this);
3115
- programs = new Programs(this);
3116
- objects = new Map;
3117
- references = new Map;
3118
- rootReferences = new Map;
3119
- controllers = new Map;
3120
- jobs = new Set;
3121
- cleanupErrors = [];
3122
- hostScope;
3123
- codec;
3124
- name;
3125
- principal;
3126
- errors = [];
3127
- now;
3128
- telemetry;
3129
- closing = false;
3130
- #publishing = false;
3131
- #publications = [];
193
+ #backend;
194
+ #interpreter = false;
195
+ #binding = createRequire(import.meta.url)("@syntropika/tembra-engine-node");
3132
196
  constructor(options) {
3133
197
  this.options = options;
3134
- this.kernel = new Kernel(options.kernel);
3135
- if (options.telemetry && !this.kernel.features.telemetry)
3136
- throw new TembraError(Errors.Unsupported.Telemetry);
3137
- this.telemetry = options.telemetry ? new Telemetry(options.telemetry.capacity, options.telemetry.sampleEvery) : undefined;
3138
- this.values = new Values(() => this.kernel.command(KernelOp.Allocate));
3139
- this.codec = options.serialization ?? jsonCodec;
3140
- this.name = options.name ?? "host";
3141
- this.principal = options.principal ?? "host";
3142
- const clock = options.now ?? (() => performance.now());
3143
- const origin = options.clockOrigin ?? clock();
3144
- this.now = () => Math.floor(clock() - origin);
3145
- const hostOrb = {
3146
- info: {
3147
- id: 0,
3148
- owner: 0,
3149
- name: "$host",
3150
- apiVersion: 1,
3151
- codeVersion: 1,
3152
- services: [],
3153
- hooks: [],
3154
- requires: []
3155
- },
3156
- definition: { name: "$host", apiVersion: 1 }
3157
- };
3158
- this.hostScope = this.scopes.environment({ kind: OwnerKind.Host }, hostOrb);
3159
- for (const [name, declaration] of Object.entries(options.resources ?? {})) {
3160
- new Declaration(this, this.hostScope).resource(name, declaration);
3161
- }
3162
- this.scopes.registerHost(this.hostScope);
3163
- this.hostScope.phase = EnvironmentPhase.Prepared;
3164
- this.programs.register(this.hostScope);
3165
- }
3166
- principalFor(object) {
3167
- return this.objects.get(object)?.address.principal ?? this.principal;
3168
- }
3169
- snapshot(object) {
3170
- return this.kernel.command(KernelOp.Snapshot, { object });
3171
- }
3172
- value(id) {
3173
- if (this.values.has(id))
3174
- return this.values.get(id);
3175
- if (!this.options.native)
3176
- refuse(Errors.Invalid.ValueGone);
3177
- const value = this.options.native.value(id);
3178
- this.values.set(id, value);
3179
- return value;
3180
198
  }
3181
- check(value, object) {
3182
- const ctx = context(value, this);
3183
- if (!ctx.invocation || ctx.invocation.object !== object)
3184
- throw new TembraError(Errors.Forbidden.StateOwner);
3185
- return ctx.invocation;
3186
- }
3187
- adopt(object, value, revision, candidate) {
3188
- const invocation = this.check(value, object);
3189
- const id = this.values.put(candidate);
199
+ async materialize(definition) {
200
+ return this.open(new this.#binding.NodeArtifact(definition.artifact), definition);
201
+ }
202
+ backend() {
203
+ if (this.#backend)
204
+ return this.#backend;
205
+ this.#backend = new this.#binding.NodeInterpreter(JSON.stringify({
206
+ limits: this.options.limits ?? {},
207
+ network: this.options.providers?.network ?? [],
208
+ filesystem: Object.fromEntries(Object.entries(this.options.providers?.filesystem ?? {}).map(([name, provider]) => [
209
+ name,
210
+ provider.path
211
+ ]))
212
+ }), (packet) => {
213
+ try {
214
+ this.options.onLog?.(JSON.parse(packet));
215
+ } catch {}
216
+ });
217
+ return this.#backend;
218
+ }
219
+ async open(artifact, options) {
220
+ const identity = JSON.parse(artifact.description());
221
+ const prepared = query(artifact, {
222
+ kind: "install",
223
+ name: identity.name,
224
+ apiVersion: identity.apiVersion,
225
+ requires: options.requires ?? {},
226
+ grants: options.grants ?? {},
227
+ filesystem: Object.keys(this.options.providers?.filesystem ?? {}),
228
+ network: this.options.providers?.network ?? [],
229
+ http: this.options.providers?.network ?? []
230
+ });
231
+ const backend = this.backend();
232
+ if (identity.kind === "source" && !this.#interpreter) {
233
+ backend.interpreter(this.options.engine ?? requireEngine());
234
+ this.#interpreter = true;
235
+ }
236
+ const port = backend.open(artifact, JSON.stringify(prepared.bindings), JSON.stringify(options.grants ?? {}), cliPacket(options.cli));
3190
237
  try {
3191
- return this.kernel.command(KernelOp.StateAdopt, {
3192
- call: invocation.id,
3193
- object,
3194
- revision,
3195
- value: id
3196
- });
238
+ const transport = new NodePort(port);
239
+ return new Revision(transport, artifact, this.options.limits?.timeoutMs ?? 1e4).definition(identity, prepared);
3197
240
  } catch (error) {
3198
- this.values.drop(id);
241
+ port.close();
3199
242
  throw error;
3200
- } finally {
3201
- this.lifecycle.flush();
3202
243
  }
3203
244
  }
3204
- publish(operation) {
3205
- this.#publications.push(operation);
3206
- if (this.#publishing)
3207
- return;
3208
- this.#publishing = true;
3209
- try {
3210
- while (this.#publications.length)
3211
- this.#publications.shift()();
3212
- } finally {
3213
- this.#publishing = false;
3214
- }
3215
- }
3216
- report(error) {
3217
- const reported = failure(error);
3218
- if (this.errors.length === 64)
3219
- this.errors.shift();
3220
- this.errors.push(reported);
3221
- try {
3222
- this.options.onError?.(reported);
3223
- } catch {}
3224
- }
3225
- track(job, cleanup = false) {
3226
- this.jobs.add(job);
3227
- job.then(() => {
3228
- this.jobs.delete(job);
3229
- }, (error) => {
3230
- this.jobs.delete(job);
3231
- if (cleanup) {
3232
- this.cleanupErrors.push(error);
3233
- this.report(error);
3234
- }
3235
- });
3236
- return job;
3237
- }
3238
245
  }
3239
-
3240
- // src/host.ts
3241
- class Host {
3242
- session;
3243
- constructor(options) {
3244
- this.session = new Session(options);
3245
- }
3246
- get name() {
3247
- return this.session.name;
3248
- }
3249
- get features() {
3250
- return this.session.kernel.features;
3251
- }
3252
- install(definition) {
3253
- return this.session.orbs.install(Array.isArray(definition) ? definition : [definition]);
3254
- }
3255
- async load(location) {
3256
- if (!this.session.options.load)
3257
- throw new Error("This host has no module loader");
3258
- await this.install(await this.session.options.load(location));
3259
- }
3260
- reload(definitions, options) {
3261
- return this.session.replacements.replace(definitions, options);
3262
- }
3263
- prepare(definitions, options) {
3264
- return this.session.replacements.prepare(definitions, options);
3265
- }
3266
- remove(names, options) {
3267
- return this.session.replacements.replace([], options, names);
3268
- }
3269
- hold(service, key, options) {
3270
- return this.session.handles.hold(service, key, options);
3271
- }
3272
- get(service, key, options) {
3273
- return this.session.handles.get(service, key, options);
3274
- }
3275
- root(operation, options = {}) {
3276
- return this.session.calls.root(operation, false, undefined, options.principal);
3277
- }
3278
- resource(name, options) {
3279
- return this.session.scopes.resource(name, options);
3280
- }
3281
- diagnostics() {
3282
- return this.session.lifecycle.diagnostics();
3283
- }
3284
- errors() {
3285
- return this.session.errors.splice(0);
3286
- }
3287
- traces() {
3288
- return this.session.telemetry?.drain() ?? [];
3289
- }
3290
- installedOrbs() {
3291
- return this.session.kernel.command(KernelOp.Orbs).map((info) => {
3292
- const definition = this.session.orbs.records.get(info.id)?.definition;
3293
- const description = Object.freeze({
3294
- ...info,
3295
- hookCapabilities: Object.fromEntries(info.hooks.map((name) => [name, definition?.hooks?.[name]?.capabilities ?? []]))
3296
- });
3297
- return Object.freeze({
3298
- ...info,
3299
- describe: () => description
3300
- });
3301
- });
3302
- }
3303
- close() {
3304
- return this.session.lifecycle.close();
3305
- }
246
+ function requireEngine() {
247
+ const require2 = createRequire(import.meta.url);
248
+ return require2("node:fs").readFileSync(require2.resolve("@syntropika/tembra-engine-node/interpreter.wasm"));
3306
249
  }
3307
250
 
3308
251
  // src/node.ts
3309
252
  function createHost(options = {}) {
3310
- const require2 = createRequire(import.meta.url);
3311
- const binding = options.kernel ? undefined : require2("@syntropika/tembra-engine-node");
3312
- return new Host({
253
+ const require2 = createRequire2(import.meta.url);
254
+ let kernel = options.kernel;
255
+ if (!kernel) {
256
+ const { NodeKernel } = require2("@syntropika/tembra-engine-node");
257
+ kernel = new NodeKernel;
258
+ }
259
+ let execution;
260
+ const backend = () => execution ??= new NodeExecution(options.isolated ?? {});
261
+ return new Host2({
262
+ [isolate2]: (definition) => backend().materialize(definition),
3313
263
  ...options,
3314
- kernel: options.kernel ?? new binding.NodeKernel,
3315
- load: options.load ?? (async (location) => {
264
+ kernel,
265
+ load: options.load ?? (async (location, registration) => {
3316
266
  const url = location instanceof URL ? location : /^[a-z]+:/i.test(location) ? new URL(location) : pathToFileURL(path.resolve(location));
3317
- if (!/\.m?js$/.test(url.pathname))
3318
- throw new Error("Load a prebuilt JavaScript orb bundle");
3319
- return orb((await import(url.href)).default);
267
+ if (!url.pathname.endsWith(".wasm"))
268
+ throw new Error("Orb loading requires a built .wasm artifact");
269
+ let source;
270
+ if (url.protocol === "file:")
271
+ source = new Uint8Array(await readFile(url));
272
+ else {
273
+ const response = await fetch(url);
274
+ if (!response.ok)
275
+ throw new Error(`Orb request failed: ${response.status}`);
276
+ source = new Uint8Array(await response.arrayBuffer());
277
+ }
278
+ return { ...registration, artifact: source };
3320
279
  })
3321
280
  });
3322
281
  }
3323
282
  export {
3324
- Code,
3325
- ContextKey,
3326
- ContextKind,
3327
- Errors,
3328
- HookCapability,
3329
- Lifetime,
3330
- Reason,
3331
- ReloadStatus,
3332
- Status,
283
+ Code2 as Code,
284
+ ContextKey2 as ContextKey,
285
+ ContextKind2 as ContextKind,
286
+ Errors2 as Errors,
287
+ HookCapability2 as HookCapability,
288
+ HttpHandlerError2 as HttpHandlerError,
289
+ Lifetime2 as Lifetime,
290
+ Reason2 as Reason,
291
+ ReloadStatus2 as ReloadStatus,
292
+ Status2 as Status,
3333
293
  createHost,
3334
- opaqueFrom,
3335
- orb
294
+ directoryFilesystem,
295
+ opaqueFrom2 as opaqueFrom,
296
+ orb3 as orb
3336
297
  };