@almadar/shell-runtime 0.1.0 → 1.0.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 (167) hide show
  1. package/dist/chunk-57SBCUSM.js +62 -0
  2. package/dist/chunk-625EP7W2.js +108 -0
  3. package/dist/{chunk-NATGCIVM.js → chunk-7WB6VWRK.js} +344 -129
  4. package/dist/{chunk-Q2H75UYT.js → chunk-A2JJT4GA.js} +1 -37
  5. package/dist/chunk-BAS26HBN.js +10 -0
  6. package/dist/{chunk-REPX5QPI.js → chunk-BOVU4TCQ.js} +11 -3
  7. package/dist/chunk-BY5G4225.js +6 -0
  8. package/dist/chunk-DFDNHVDW.js +284 -0
  9. package/dist/chunk-I3TKINSO.js +398 -0
  10. package/dist/{chunk-DYOJGLIX.js → chunk-LKWYCYX5.js} +2 -5
  11. package/dist/chunk-LYFIQPXX.js +1 -0
  12. package/dist/{chunk-VNMG7NKY.js → chunk-MU335ZA4.js} +20 -26
  13. package/dist/{chunk-ODJCZ27I.js → chunk-N7HYNKK6.js} +35 -2
  14. package/dist/{chunk-4J2QEIUV.js → chunk-NTFQ36UN.js} +4 -30
  15. package/dist/chunk-NU6LVKGS.js +15 -0
  16. package/dist/chunk-P2N6K2IV.js +20 -0
  17. package/dist/{chunk-QQRDUMB2.js → chunk-QCJWPXLH.js} +11 -11
  18. package/dist/{chunk-QELZ6TEJ.js → chunk-UD2CXYSJ.js} +39 -3
  19. package/dist/{chunk-UJHOUZAL.js → chunk-V4EMDPCO.js} +2 -5
  20. package/dist/chunk-VNGXRYFF.js +9 -0
  21. package/dist/{chunk-HNOAZWFH.js → chunk-WGCWJOT2.js} +2 -0
  22. package/dist/chunk-X6W44WHO.js +26 -0
  23. package/dist/chunk-ZUSM4VW4.js +197 -0
  24. package/dist/client/EventTransport.d.ts +23 -7
  25. package/dist/client/EventTransport.js +1 -2
  26. package/dist/client/awaiting.js +0 -1
  27. package/dist/client/channel-transport.d.ts +6 -6
  28. package/dist/client/channel-transport.js +0 -1
  29. package/dist/client/circuit-store.d.ts +16 -5
  30. package/dist/client/circuit-store.js +2 -3
  31. package/dist/client/client-kernel.d.ts +36 -15
  32. package/dist/client/declared-input-dispatch.d.ts +19 -2
  33. package/dist/client/declared-input-dispatch.js +1 -2
  34. package/dist/client/inbound-dispatch.d.ts +21 -2
  35. package/dist/client/inbound-dispatch.js +1 -2
  36. package/dist/client/local-fold.d.ts +15 -8
  37. package/dist/client/local-fold.js +1 -2
  38. package/dist/client/render-sigils.js +0 -1
  39. package/dist/client/state-book.d.ts +9 -16
  40. package/dist/client/state-book.js +1 -2
  41. package/dist/client/trait-mount-error.js +0 -1
  42. package/dist/credentials/env-vars.d.ts +5 -1
  43. package/dist/credentials/env-vars.js +1 -3
  44. package/dist/credentials/scope.d.ts +8 -7
  45. package/dist/credentials/scope.js +0 -1
  46. package/dist/credentials/vault.d.ts +142 -0
  47. package/dist/credentials/vault.js +1 -0
  48. package/dist/effects/in-flight-calls.js +0 -1
  49. package/dist/effects/on-device-model.js +0 -1
  50. package/dist/events/EventBus.d.ts +1 -4
  51. package/dist/events/EventBus.js +0 -1
  52. package/dist/events/emit-stamp.js +0 -1
  53. package/dist/index.d.ts +25 -42
  54. package/dist/index.js +27 -45
  55. package/dist/kernel/decode.d.ts +8 -10
  56. package/dist/kernel/decode.js +1 -2
  57. package/dist/kernel/engine.d.ts +132 -31
  58. package/dist/kernel/engine.js +7 -9
  59. package/dist/kernel/frame-applier.d.ts +8 -7
  60. package/dist/kernel/frame-applier.js +1 -2
  61. package/dist/kernel/host.d.ts +127 -16
  62. package/dist/kernel/host.js +4 -7
  63. package/dist/kernel/lane.d.ts +1 -22
  64. package/dist/kernel/lane.js +1 -2
  65. package/dist/kernel/os-fetch-port.d.ts +7 -0
  66. package/dist/kernel/os-fetch-port.js +3 -0
  67. package/dist/kernel/os-port.d.ts +30 -8
  68. package/dist/kernel/os-port.js +1 -2
  69. package/dist/kernel/program-effects.d.ts +11 -28
  70. package/dist/kernel/program-effects.js +1 -2
  71. package/dist/kernel/secret-ports.d.ts +139 -0
  72. package/dist/kernel/secret-ports.js +2 -0
  73. package/dist/kernel/wire.d.ts +50 -12
  74. package/dist/loader/fetch-loader.d.ts +26 -0
  75. package/dist/loader/fetch-loader.js +1 -0
  76. package/dist/loader/lazy-page.js +0 -1
  77. package/dist/loader/schema-loader.d.ts +1 -17
  78. package/dist/persistence/native-memory.js +0 -1
  79. package/dist/runtime/entities/declaredCollections.d.ts +6 -0
  80. package/dist/runtime/entities/declaredCollections.js +1 -0
  81. package/dist/runtime/evaluation/local-store-transport.d.ts +14 -23
  82. package/dist/runtime/evaluation/local-store-transport.js +9 -13
  83. package/dist/runtime/evaluation/residence-transport.d.ts +3 -3
  84. package/dist/runtime/evaluation/residence-transport.js +1 -2
  85. package/dist/runtime/evaluation/routed-persistence.js +0 -1
  86. package/dist/runtime/events/identity/routing.d.ts +2 -53
  87. package/dist/runtime/events/identity/routing.js +1 -2
  88. package/dist/runtime/types.d.ts +5 -205
  89. package/dist/runtime/types.js +1 -2
  90. package/dist/service/default-call-service.js +0 -1
  91. package/dist/service/service-provider.js +0 -1
  92. package/package.json +8 -5
  93. package/dist/chunk-2JU7Y4KU.js +0 -21
  94. package/dist/chunk-46RWK2B5.js +0 -28
  95. package/dist/chunk-4ZICQ5PM.js +0 -192
  96. package/dist/chunk-53IPZXDP.js +0 -76
  97. package/dist/chunk-5D63EMO5.js +0 -16
  98. package/dist/chunk-CPSQXEJ6.js +0 -55
  99. package/dist/chunk-CQP5XAX6.js +0 -173
  100. package/dist/chunk-CROS2GEX.js +0 -49
  101. package/dist/chunk-D4XJTBLB.js +0 -217
  102. package/dist/chunk-D5USD2EX.js +0 -232
  103. package/dist/chunk-EV56K4GB.js +0 -63
  104. package/dist/chunk-FQ6IZMIU.js +0 -10
  105. package/dist/chunk-HMK6YMQS.js +0 -135
  106. package/dist/chunk-IHQLE5M7.js +0 -62
  107. package/dist/chunk-JFWFDUTR.js +0 -35
  108. package/dist/chunk-MHYSHSRG.js +0 -54
  109. package/dist/chunk-MLKGABMK.js +0 -7
  110. package/dist/chunk-NAECVIAR.js +0 -322
  111. package/dist/chunk-Q7JK4KY7.js +0 -9
  112. package/dist/chunk-RBUMDYFS.js +0 -681
  113. package/dist/chunk-SAS5KKCR.js +0 -43
  114. package/dist/chunk-SWPDU752.js +0 -28
  115. package/dist/chunk-T775TUCD.js +0 -18
  116. package/dist/chunk-VMOBW7RK.js +0 -21
  117. package/dist/chunk-WNPNNYXY.js +0 -22
  118. package/dist/chunk-XB5GYODW.js +0 -28
  119. package/dist/chunk-YL2SO5TP.js +0 -334
  120. package/dist/chunk-YO4LWS3I.js +0 -606
  121. package/dist/chunk-ZAQSS47X.js +0 -157
  122. package/dist/chunk-ZCQUUJIF.js +0 -129
  123. package/dist/client/ServerBridge.d.ts +0 -126
  124. package/dist/client/ServerBridge.js +0 -3
  125. package/dist/credentials/seed.d.ts +0 -21
  126. package/dist/credentials/seed.js +0 -2
  127. package/dist/credentials/store.d.ts +0 -110
  128. package/dist/credentials/store.js +0 -2
  129. package/dist/index-hT1xCdTq.d.ts +0 -46
  130. package/dist/kernel/beacon.d.ts +0 -32
  131. package/dist/kernel/beacon.js +0 -2
  132. package/dist/kernel/http.d.ts +0 -302
  133. package/dist/kernel/http.js +0 -6
  134. package/dist/kernel/oauth-effects.d.ts +0 -25
  135. package/dist/kernel/oauth-effects.js +0 -7
  136. package/dist/kernel/oauth-port.d.ts +0 -31
  137. package/dist/kernel/oauth-port.js +0 -2
  138. package/dist/loader/http-loader.d.ts +0 -111
  139. package/dist/loader/http-loader.js +0 -2
  140. package/dist/runtime/effects/composition/compose-behaviors.d.ts +0 -58
  141. package/dist/runtime/effects/composition/compose-behaviors.js +0 -4
  142. package/dist/runtime/effects/composition/event-wiring.d.ts +0 -38
  143. package/dist/runtime/effects/composition/event-wiring.js +0 -2
  144. package/dist/runtime/effects/composition/index.d.ts +0 -5
  145. package/dist/runtime/effects/composition/index.js +0 -6
  146. package/dist/runtime/effects/composition/layout-strategy.d.ts +0 -35
  147. package/dist/runtime/effects/composition/layout-strategy.js +0 -2
  148. package/dist/runtime/effects/composition/pipe.d.ts +0 -25
  149. package/dist/runtime/effects/composition/pipe.js +0 -2
  150. package/dist/runtime/entities/mockStoreSeed.d.ts +0 -56
  151. package/dist/runtime/entities/mockStoreSeed.js +0 -3
  152. package/dist/runtime/entities/seedBrowserStore.d.ts +0 -28
  153. package/dist/runtime/entities/seedBrowserStore.js +0 -2
  154. package/dist/runtime/entities/std-mock-seed.d.ts +0 -87
  155. package/dist/runtime/entities/std-mock-seed.js +0 -2
  156. package/dist/runtime/time/TickScheduler.d.ts +0 -77
  157. package/dist/runtime/time/TickScheduler.js +0 -3
  158. package/dist/runtime/time/cron.d.ts +0 -25
  159. package/dist/runtime/time/cron.js +0 -2
  160. package/dist/runtime/time/duration.d.ts +0 -20
  161. package/dist/runtime/time/duration.js +0 -2
  162. package/dist/runtime/traits/OrbitalTraitParsing.d.ts +0 -34
  163. package/dist/runtime/traits/OrbitalTraitParsing.js +0 -2
  164. package/dist/runtime/traits/listen-targets.d.ts +0 -16
  165. package/dist/runtime/traits/listen-targets.js +0 -3
  166. package/dist/runtime/traits/trait-index.d.ts +0 -35
  167. package/dist/runtime/traits/trait-index.js +0 -3
@@ -1,55 +0,0 @@
1
- import { parseOrbitalTraits } from './chunk-SAS5KKCR.js';
2
- import { findEntityAmongOrbitals, orbitalInlineEntities } from '@almadar/core';
3
- import { createLogger } from '@almadar/logger';
4
-
5
- var traitIndexLog = createLogger("almadar:runtime:trait-index");
6
- var parseCache = /* @__PURE__ */ new WeakMap();
7
- function parseOrbitalCached(orbital) {
8
- let cached = parseCache.get(orbital);
9
- if (cached === void 0) {
10
- cached = { traits: parseOrbitalTraits(orbital), entities: orbitalInlineEntities(orbital) };
11
- parseCache.set(orbital, cached);
12
- }
13
- return cached;
14
- }
15
- function buildTraitIndex(orbitals) {
16
- const parsed = orbitals.map((orbital) => ({ orbital, parsed: parseOrbitalCached(orbital).traits }));
17
- const allEntities = orbitals.map((orbital) => parseOrbitalCached(orbital).entities).flat();
18
- const orbitalsView = parsed.map(({ orbital, parsed: p }) => ({ schema: orbital, entity: p.entity }));
19
- const byName = /* @__PURE__ */ new Map();
20
- for (const { orbital, parsed: p } of parsed) {
21
- const { traits, inlineTraits, entity } = p;
22
- for (let i = 0; i < traits.length; i++) {
23
- const traitDef = traits[i];
24
- const irTrait = inlineTraits[i];
25
- const linkedEntityName = irTrait?.linkedEntity;
26
- let traitEntity = entity;
27
- if (linkedEntityName && linkedEntityName !== traitEntity.name) {
28
- const resolved = findEntityAmongOrbitals(allEntities, linkedEntityName);
29
- if (resolved) {
30
- traitEntity = resolved;
31
- } else {
32
- traitIndexLog.warn("linkedEntity:unresolved", {
33
- orbital: orbital.name,
34
- trait: traitDef.name,
35
- linkedEntityName
36
- });
37
- traitEntity = { name: linkedEntityName, fields: [] };
38
- }
39
- }
40
- const isShared = traitEntity.shared === true;
41
- byName.set(traitDef.name, {
42
- traitDef,
43
- irTrait,
44
- entity: traitEntity,
45
- orbitalName: orbital.name,
46
- ...orbital.id !== void 0 ? { orbitalId: orbital.id } : {},
47
- frameKey: isShared ? `$shared::${traitEntity.name}` : traitDef.name,
48
- isSharedEntity: isShared
49
- });
50
- }
51
- }
52
- return { byName, allEntities, orbitals: orbitalsView };
53
- }
54
-
55
- export { buildTraitIndex };
@@ -1,173 +0,0 @@
1
- import { parseCron, cronMinuteKey, cronMatches } from './chunk-CROS2GEX.js';
2
-
3
- // src/runtime/time/TickScheduler.ts
4
- var EVERY_PASS = 0;
5
- var CRON_CHECK_INTERVAL_MS = 1e3;
6
- var TickScheduler = class {
7
- ticks = /* @__PURE__ */ new Map();
8
- nextId = 1;
9
- running = false;
10
- paused = false;
11
- frameHandle = null;
12
- hasRaf;
13
- constructor() {
14
- this.hasRaf = typeof requestAnimationFrame === "function" && typeof cancelAnimationFrame === "function";
15
- }
16
- /**
17
- * Register a tick. `intervalMs <= 0` means "every pass" (a frame-interval
18
- * tick, matching LOLO's `interval: "frame"`). Returns a handle to stop
19
- * just this tick.
20
- */
21
- add(intervalMs, onDue) {
22
- const id = this.nextId++;
23
- this.ticks.set(id, {
24
- kind: "interval",
25
- intervalMs: intervalMs > 0 ? intervalMs : EVERY_PASS,
26
- accumulatedMs: 0,
27
- lastTimestamp: null,
28
- onDue
29
- });
30
- this.ensureRunning();
31
- return {
32
- stop: () => {
33
- this.ticks.delete(id);
34
- this.maybeStop();
35
- }
36
- };
37
- }
38
- /**
39
- * Register a cron-scheduled tick (`ticks { ... every "0 9 * * *" }`).
40
- * Fires at most once per matching calendar minute. Throws if `expression` isn't a valid 5-field cron
41
- * string; callers on a path the compiler has already validated (e.g.
42
- * generated code) won't hit this, but a raw runtime value might.
43
- */
44
- addCron(expression, onDue) {
45
- const fields = parseCron(expression);
46
- const id = this.nextId++;
47
- this.ticks.set(id, {
48
- kind: "cron",
49
- fields,
50
- accumulatedMs: CRON_CHECK_INTERVAL_MS,
51
- // check on the first pass, not after a full second
52
- lastTimestamp: null,
53
- lastFiredMinuteKey: -1,
54
- onDue
55
- });
56
- this.ensureRunning();
57
- return {
58
- stop: () => {
59
- this.ticks.delete(id);
60
- this.maybeStop();
61
- }
62
- };
63
- }
64
- /** Stop every tick and the shared loop. */
65
- stopAll() {
66
- this.ticks.clear();
67
- this.maybeStop();
68
- }
69
- /** True while the scheduler is paused (no tick callback fires and no backlog accumulates). */
70
- get isPaused() {
71
- return this.paused;
72
- }
73
- /**
74
- * Halt the shared loop without dropping registered ticks. No `onDue`
75
- * fires again until `resume()`. A no-op if already paused.
76
- */
77
- pause() {
78
- if (this.paused) return;
79
- this.paused = true;
80
- this.stopLoop();
81
- }
82
- /**
83
- * Restart the shared loop after `pause()`. Every registered tick's phase
84
- * is reset (`lastTimestamp = null`) so the paused duration is never
85
- * counted as elapsed time — the same "first pass just captures the
86
- * timestamp" behavior a freshly `add()`-ed tick gets, which is what keeps
87
- * resume from bursting a backlog of missed beats. A no-op if not paused.
88
- */
89
- resume() {
90
- if (!this.paused) return;
91
- this.paused = false;
92
- for (const tick of this.ticks.values()) {
93
- tick.lastTimestamp = null;
94
- }
95
- if (this.ticks.size > 0) {
96
- this.ensureRunning();
97
- }
98
- }
99
- ensureRunning() {
100
- if (this.running || this.paused) return;
101
- this.running = true;
102
- if (this.hasRaf) {
103
- const loop = (timestamp) => {
104
- if (!this.running) return;
105
- this.advance(timestamp);
106
- this.frameHandle = requestAnimationFrame(loop);
107
- };
108
- this.frameHandle = requestAnimationFrame(loop);
109
- } else {
110
- this.frameHandle = setInterval(() => this.advance(Date.now()), 16);
111
- }
112
- }
113
- maybeStop() {
114
- if (this.ticks.size > 0 || !this.running) return;
115
- this.stopLoop();
116
- }
117
- /** Cancel the active rAF/interval loop, if any, and clear the running flag. */
118
- stopLoop() {
119
- this.running = false;
120
- if (this.frameHandle !== null) {
121
- if (this.hasRaf) {
122
- cancelAnimationFrame(this.frameHandle);
123
- } else {
124
- clearInterval(this.frameHandle);
125
- }
126
- this.frameHandle = null;
127
- }
128
- }
129
- advance(timestamp) {
130
- for (const tick of this.ticks.values()) {
131
- if (tick.kind === "cron") {
132
- this.advanceCron(tick, timestamp);
133
- continue;
134
- }
135
- if (tick.intervalMs <= EVERY_PASS) {
136
- tick.onDue();
137
- continue;
138
- }
139
- if (tick.lastTimestamp === null) {
140
- tick.lastTimestamp = timestamp;
141
- continue;
142
- }
143
- tick.accumulatedMs += timestamp - tick.lastTimestamp;
144
- tick.lastTimestamp = timestamp;
145
- if (tick.accumulatedMs >= tick.intervalMs) {
146
- tick.onDue();
147
- tick.accumulatedMs = tick.accumulatedMs % tick.intervalMs;
148
- }
149
- }
150
- }
151
- /** Cron ticks check calendar-match at most once a second, deduped per matching minute. */
152
- advanceCron(tick, timestamp) {
153
- if (tick.lastTimestamp === null) {
154
- tick.lastTimestamp = timestamp;
155
- return;
156
- }
157
- tick.accumulatedMs += timestamp - tick.lastTimestamp;
158
- tick.lastTimestamp = timestamp;
159
- if (tick.accumulatedMs < CRON_CHECK_INTERVAL_MS) return;
160
- tick.accumulatedMs = 0;
161
- const now = /* @__PURE__ */ new Date();
162
- const minuteKey = cronMinuteKey(now);
163
- if (minuteKey !== tick.lastFiredMinuteKey && cronMatches(tick.fields, now)) {
164
- tick.lastFiredMinuteKey = minuteKey;
165
- tick.onDue();
166
- }
167
- }
168
- };
169
- function createTickScheduler() {
170
- return new TickScheduler();
171
- }
172
-
173
- export { TickScheduler, createTickScheduler };
@@ -1,49 +0,0 @@
1
- // src/runtime/time/cron.ts
2
- function parseCronField(field, min, max) {
3
- const values = /* @__PURE__ */ new Set();
4
- for (const part of field.split(",")) {
5
- if (part === "*") {
6
- for (let i = min; i <= max; i++) values.add(i);
7
- } else if (part.includes("/")) {
8
- const [range, stepStr] = part.split("/");
9
- const step = parseInt(stepStr, 10);
10
- const start = range === "*" ? min : parseInt(range, 10);
11
- for (let i = start; i <= max; i += step) values.add(i);
12
- } else if (part.includes("-")) {
13
- const [lo, hi] = part.split("-").map(Number);
14
- for (let i = lo; i <= hi; i++) values.add(i);
15
- } else {
16
- values.add(parseInt(part, 10));
17
- }
18
- }
19
- return values;
20
- }
21
- function parseCron(expression) {
22
- const parts = expression.trim().split(/\s+/);
23
- if (parts.length !== 5) {
24
- throw new Error(`Invalid cron expression (expected 5 fields): ${expression}`);
25
- }
26
- return {
27
- minute: parseCronField(parts[0], 0, 59),
28
- hour: parseCronField(parts[1], 0, 23),
29
- day: parseCronField(parts[2], 1, 31),
30
- month: parseCronField(parts[3], 1, 12),
31
- weekday: parseCronField(parts[4], 0, 6)
32
- };
33
- }
34
- function isValidCronExpression(expression) {
35
- try {
36
- parseCron(expression);
37
- return true;
38
- } catch {
39
- return false;
40
- }
41
- }
42
- function cronMatches(fields, date) {
43
- return fields.minute.has(date.getMinutes()) && fields.hour.has(date.getHours()) && fields.day.has(date.getDate()) && fields.month.has(date.getMonth() + 1) && fields.weekday.has(date.getDay());
44
- }
45
- function cronMinuteKey(date) {
46
- return date.getFullYear() * 1e8 + date.getMonth() * 1e6 + date.getDate() * 1e4 + date.getHours() * 100 + date.getMinutes();
47
- }
48
-
49
- export { cronMatches, cronMinuteKey, isValidCronExpression, parseCron, parseCronField };
@@ -1,217 +0,0 @@
1
- import { declareCapabilities, answerRequest } from './chunk-NATGCIVM.js';
2
- import { DispatchLane } from './chunk-53IPZXDP.js';
3
- import { decodeResolveProgress, decodeProgress } from './chunk-RBUMDYFS.js';
4
- import { installKernelEvaluator, MountSeedSchema, EventStreamItemSchema, isEntityReferenceAny } from '@almadar/core';
5
-
6
- function declaredEntityTypes(schema) {
7
- return schema.orbitals.flatMap((orbital) => [orbital.entity, ...orbital.auxiliaryEntities ?? []].flatMap((entity) => isEntityReferenceAny(entity) ? [] : [entity.name]));
8
- }
9
- var KernelEngine = class _KernelEngine {
10
- constructor(kernel, schemaJson, ports, entityTypes = [], forkedFrom, providedHandle, preserveProgramContext = false) {
11
- this.kernel = kernel;
12
- this.schemaJson = schemaJson;
13
- this.ports = ports;
14
- this.entityTypes = entityTypes;
15
- this.preserveProgramContext = preserveProgramContext;
16
- installKernelEvaluator(kernel);
17
- this.ports = {
18
- ...ports,
19
- substrateMessage: (site, key, value) => JSON.parse(kernel.osCompletionEvent(JSON.stringify({ ...site, emit: { success: site.emit.onMessage } }), key, JSON.stringify({ ok: value }))),
20
- substrateCompletion: (site, key, op, args, outcome) => JSON.parse(kernel.substrateCompletionEvent(JSON.stringify(site), key, op, JSON.stringify(args), JSON.stringify(outcome)))
21
- };
22
- this.handle = providedHandle ?? forkedFrom?.fork() ?? this.openServer();
23
- this.declare();
24
- }
25
- kernel;
26
- schemaJson;
27
- ports;
28
- entityTypes;
29
- preserveProgramContext;
30
- handle;
31
- lane = new DispatchLane();
32
- tickMount = [];
33
- messages = { locales: [], catalogs: {} };
34
- /**
35
- * A kernel on the same program, registered once, holding none of this one's session: every trait at its initial
36
- * state, no rows the kernel held, its locales and mounted ticks kept. A stateless host serves each request a
37
- * fork (EXEC-DIST-5), `ports` answering it.
38
- */
39
- fork(ports = this.ports) {
40
- const forked = new _KernelEngine(this.kernel, this.schemaJson, ports, this.entityTypes, this.handle, void 0, this.preserveProgramContext);
41
- forked.tickMount = this.tickMount;
42
- forked.messages = this.messages;
43
- return forked;
44
- }
45
- forkProgram(program, ports = this.ports) {
46
- const schemaJson = JSON.stringify(program);
47
- const entityTypes = [.../* @__PURE__ */ new Set([
48
- ...this.entityTypes,
49
- ...declaredEntityTypes(program)
50
- ])];
51
- return new _KernelEngine(this.kernel, schemaJson, ports, entityTypes, void 0, this.handle.forkProgram(schemaJson), true);
52
- }
53
- /** A server over the host's ports. */
54
- openServer() {
55
- return new this.kernel.Server(this.schemaJson);
56
- }
57
- declare() {
58
- const handle = this.handle;
59
- declareCapabilities(this.ports.persistence, (entityType, queryJson, writeJson) => handle.setCapabilities(entityType, queryJson, writeJson), this.entityTypes);
60
- }
61
- static open(kernel, schema, ports) {
62
- return new _KernelEngine(kernel, JSON.stringify(schema), ports, declaredEntityTypes(schema));
63
- }
64
- /** A fresh kernel on the same program: every trait back at its initial state. */
65
- reset() {
66
- const contextualHandle = this.preserveProgramContext ? this.handle.fork() : void 0;
67
- this.handle.free();
68
- this.handle = contextualHandle ?? this.openServer();
69
- this.declare();
70
- this.handle.setTickMount(JSON.stringify(this.tickMount));
71
- this.handle.setMessages(JSON.stringify(this.messages.locales), JSON.stringify(this.messages.catalogs));
72
- if (this.managedProgram !== void 0) this.handle.setManagedProgram(this.managedProgram);
73
- }
74
- managedProgram;
75
- /** The program whose declared credentials this kernel's credential effects manage beside its own (a console's app). */
76
- setManagedProgram(program) {
77
- this.managedProgram = JSON.stringify(program);
78
- this.handle.setManagedProgram(this.managedProgram);
79
- }
80
- /** The program's declared locales and merged catalogs (a lazy page's behavior contributes its namespaced keys). */
81
- setMessages(locales, catalogs) {
82
- this.messages = { locales, catalogs };
83
- this.handle.setMessages(JSON.stringify(locales), JSON.stringify(catalogs));
84
- }
85
- /** The traits some client has mounted: a tick that is not `[background]` fires only for these. */
86
- setTickMount(traits) {
87
- this.tickMount = traits;
88
- this.handle.setTickMount(JSON.stringify(traits));
89
- }
90
- /** What this host mounts when it starts: the kernel's boot mounts for the side it serves (EXEC-ENDPOINT-3). */
91
- bootMounts(side) {
92
- return MountSeedSchema.array().parse(JSON.parse(this.handle.bootMounts(side)));
93
- }
94
- /** What mounts when a client opens `routePath` (EXEC-ENDPOINT-3). */
95
- routeMounts(routePath) {
96
- return MountSeedSchema.array().parse(JSON.parse(this.handle.routeMounts(routePath)));
97
- }
98
- /** Mock-seed the `[runtime]` entities the kernel holds itself, owner columns stamped with `viewerId`. */
99
- seedRuntimeMock(viewerId) {
100
- this.handle.seedRuntimeMock(viewerId);
101
- }
102
- dispose() {
103
- this.handle.free();
104
- }
105
- liveItemDelivered(item, viewer, clientId) {
106
- return this.handle.liveItemDelivered(JSON.stringify(item), JSON.stringify(viewer), clientId);
107
- }
108
- /** `OsGrants::allows` over the grants of the program this kernel runs. */
109
- osAllows(requirementJson) {
110
- return this.handle.osAllows(requirementJson);
111
- }
112
- /** Place the program's anchored grants and arguments under the host's anchors. */
113
- setOsAnchors(anchorsJson) {
114
- return this.handle.setOsAnchors(anchorsJson);
115
- }
116
- /** An `os/` call's arguments with its anchored parts resolved under the host's anchors. */
117
- osResolveArgs(op, argsJson) {
118
- return this.handle.osResolveArgs(op, argsJson);
119
- }
120
- /** The current state of a trait instance, `''` when it has none. */
121
- stateOf(traitName, entityId) {
122
- return this.handle.getState(traitName, entityId);
123
- }
124
- /**
125
- * `reference` resolved for `scope.user` against the host-answered store (EXEC-RENDER-3): the rows that still
126
- * match its query and the viewer's `@read` in the reference's order, a missing or hidden row omitted, and `total`
127
- * re-counted (a `total: none` reference is not re-counted: the total is the resolved window). Each read the
128
- * kernel makes is answered here, as in `evaluate`.
129
- */
130
- async resolveRows(reference, scope) {
131
- const handle = this.handle;
132
- let progress = decodeResolveProgress(handle.resolveRows(JSON.stringify(reference), JSON.stringify(scope.user ?? null)));
133
- while (progress.status === "await") {
134
- const { flight, requests } = progress;
135
- let replies;
136
- try {
137
- replies = await Promise.all(
138
- requests.map(async (pending) => ({ id: pending.id, answer: await answerRequest(this.ports, pending.request, scope) }))
139
- );
140
- } catch (error) {
141
- handle.abandon(flight);
142
- throw error;
143
- }
144
- progress = decodeResolveProgress(handle.resumeResolve(flight, JSON.stringify(replies)));
145
- }
146
- return { rows: progress.rows, total: progress.total };
147
- }
148
- /** Run `request` against `orbital`: start it, answer every request the kernel asks for, resume until done. */
149
- async evaluate(orbital, request, scope) {
150
- const guard = await this.lane.enter();
151
- try {
152
- const handle = this.handle;
153
- let progress = decodeProgress(handle.start(orbital, JSON.stringify(request)));
154
- while (progress.status === "await") {
155
- const { flight, requests } = progress;
156
- let replies;
157
- guard.park(request.event);
158
- try {
159
- replies = await Promise.all(
160
- requests.map(async (pending) => ({ id: pending.id, answer: await answerRequest(this.ports, pending.request, { ...scope, assertReentry: () => this.lane.assertCanReenter(guard.turn) }) }))
161
- );
162
- } catch (error) {
163
- handle.abandon(flight);
164
- throw error;
165
- }
166
- guard.resume();
167
- progress = decodeProgress(handle.resume(flight, JSON.stringify(replies)));
168
- }
169
- if (scope.onStream !== void 0) {
170
- const items = EventStreamItemSchema.array().parse(JSON.parse(handle.dispatchStream()));
171
- for (const item of items) scope.onStream(item);
172
- }
173
- return progress.response;
174
- } finally {
175
- guard.release();
176
- }
177
- }
178
- };
179
- function kernelRequest(request, user, locale) {
180
- const { _activeTraits: _dropped, _targetTrait: sidecarTarget, ...rest } = request.payload ?? {};
181
- const payload = rest;
182
- const target = request.targetTrait ?? (typeof sidecarTarget === "string" ? sidecarTarget : void 0);
183
- const { payload: _payload, ...others } = request;
184
- return {
185
- ...others,
186
- ...request.payload !== void 0 ? { payload } : {},
187
- ...target !== void 0 ? { targetTrait: target } : {},
188
- ...user !== void 0 ? { user } : {},
189
- ...locale !== void 0 ? { locale } : {}
190
- };
191
- }
192
- function withOriginClient(response, clientId) {
193
- if (clientId === void 0) return response;
194
- return {
195
- ...response,
196
- emittedEvents: response.emittedEvents.map((emitted) => emitted.source === void 0 ? emitted : { ...emitted, source: { ...emitted.source, originClientId: emitted.source.originClientId ?? clientId } })
197
- };
198
- }
199
- async function evaluateOnKernel(kernel, request, user, locale) {
200
- return withOriginClient(await kernel.engine.evaluate(kernel.orbital, kernelRequest(request, user, locale), {
201
- orbital: kernel.orbital,
202
- ...user !== void 0 ? { user } : {},
203
- ...request.clientId !== void 0 ? { originClientId: request.clientId } : {},
204
- ...locale !== void 0 ? { locale } : {},
205
- ...request.entityId !== void 0 ? { entityId: request.entityId } : {},
206
- ...kernel.onStream !== void 0 ? { onStream: (item) => {
207
- if (item.type === "event" && item.data.source !== void 0 && request.clientId !== void 0) {
208
- kernel.onStream?.({ ...item, data: { ...item.data, source: { ...item.data.source, originClientId: item.data.source.originClientId ?? request.clientId } } });
209
- } else if (item.type === "complete") {
210
- kernel.onStream?.({ ...item, data: withOriginClient(item.data, request.clientId) });
211
- } else kernel.onStream?.(item);
212
- } } : {},
213
- ...kernel.outsideEventQueue !== void 0 ? { outsideEventQueue: kernel.outsideEventQueue } : {}
214
- }), request.clientId);
215
- }
216
-
217
- export { KernelEngine, evaluateOnKernel, kernelRequest };