@opencode/codemode 2.2.7 → 2.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 (197) hide show
  1. package/README.md +11 -13
  2. package/dist/{vm/async.d.ts → async.d.ts} +1 -1
  3. package/dist/codemode.d.ts +8 -22
  4. package/dist/codemode.js +17 -38
  5. package/dist/data.d.ts +4 -19
  6. package/dist/data.js +1 -82
  7. package/dist/extension.d.ts +8 -2
  8. package/dist/extension.js +9 -0
  9. package/dist/{vm/host.d.ts → host.d.ts} +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/{vm/opcodes.d.ts → opcodes.d.ts} +1 -1
  12. package/dist/{vm/prelude → prelude}/helpers.js +1 -1
  13. package/dist/{vm/runtime → runtime}/driver.d.ts +1 -1
  14. package/dist/{vm/runtime → runtime}/driver.js +1 -1
  15. package/dist/{vm/runtime → runtime}/errors.js +2 -2
  16. package/dist/{vm/runtime → runtime}/execute.d.ts +17 -8
  17. package/dist/{vm/runtime → runtime}/execute.js +11 -9
  18. package/dist/{vm/runtime → runtime}/extensions.d.ts +1 -1
  19. package/dist/{vm/runtime → runtime}/extensions.js +39 -4
  20. package/dist/{vm/runtime → runtime}/globals.js +1 -1
  21. package/dist/{vm/runtime → runtime}/interpreter.d.ts +1 -1
  22. package/dist/{vm/runtime → runtime}/model.d.ts +1 -1
  23. package/dist/{vm/runtime → runtime}/objects.d.ts +1 -1
  24. package/dist/{vm/runtime → runtime}/objects.js +1 -1
  25. package/dist/{vm/runtime → runtime}/operations.d.ts +1 -1
  26. package/dist/{vm/runtime → runtime}/operations.js +1 -1
  27. package/dist/scan.js +2 -2
  28. package/dist/{vm/scheduler.d.ts → scheduler.d.ts} +1 -1
  29. package/dist/{vm/snapshot → snapshot}/codec.d.ts +6 -5
  30. package/dist/{vm/snapshot → snapshot}/codec.js +12 -5
  31. package/dist/{vm/snapshot → snapshot}/snapshot.d.ts +8 -5
  32. package/dist/{vm/snapshot → snapshot}/snapshot.js +14 -3
  33. package/dist/{vm/snapshot.js → snapshot.js} +1 -1
  34. package/dist/stdlib/array.d.ts +14 -9
  35. package/dist/stdlib/array.js +89 -276
  36. package/dist/stdlib/bytes.d.ts +11 -7
  37. package/dist/stdlib/bytes.js +112 -79
  38. package/dist/stdlib/collections.d.ts +7 -7
  39. package/dist/stdlib/collections.js +30 -339
  40. package/dist/stdlib/console.d.ts +2 -2
  41. package/dist/stdlib/console.js +3 -3
  42. package/dist/stdlib/date.d.ts +2 -2
  43. package/dist/stdlib/date.js +21 -30
  44. package/dist/stdlib/headers.d.ts +2 -2
  45. package/dist/stdlib/headers.js +15 -33
  46. package/dist/stdlib/iterator.d.ts +2 -2
  47. package/dist/stdlib/iterator.js +10 -302
  48. package/dist/stdlib/json.d.ts +2 -2
  49. package/dist/stdlib/json.js +15 -31
  50. package/dist/stdlib/math.d.ts +2 -7
  51. package/dist/stdlib/math.js +6 -30
  52. package/dist/stdlib/number.d.ts +3 -3
  53. package/dist/stdlib/number.js +8 -8
  54. package/dist/stdlib/object.d.ts +4 -4
  55. package/dist/stdlib/object.js +12 -30
  56. package/dist/stdlib/regexp.d.ts +6 -5
  57. package/dist/stdlib/regexp.js +18 -13
  58. package/dist/stdlib/string.d.ts +2 -2
  59. package/dist/stdlib/string.js +53 -53
  60. package/dist/stdlib/url.d.ts +21 -9
  61. package/dist/stdlib/url.js +55 -55
  62. package/dist/stdlib/value.d.ts +3 -4
  63. package/dist/stdlib/value.js +5 -6
  64. package/dist/stdlib/web.d.ts +4 -4
  65. package/dist/stdlib/web.js +7 -7
  66. package/dist/tool-runtime.d.ts +14 -13
  67. package/dist/tool-runtime.js +245 -53
  68. package/dist/tool-schema.d.ts +5 -0
  69. package/dist/tool-schema.js +36 -16
  70. package/dist/tool.d.ts +24 -9
  71. package/dist/tool.js +15 -22
  72. package/dist/{vm/vm.d.ts → vm.d.ts} +3 -3
  73. package/dist/{vm/vm.js → vm.js} +1 -1
  74. package/package.json +3 -5
  75. package/dist/interpreter/callback.d.ts +0 -35
  76. package/dist/interpreter/callback.js +0 -98
  77. package/dist/interpreter/errors.js +0 -173
  78. package/dist/interpreter/execute.d.ts +0 -14
  79. package/dist/interpreter/execute.js +0 -207
  80. package/dist/interpreter/extensions.d.ts +0 -9
  81. package/dist/interpreter/extensions.js +0 -248
  82. package/dist/interpreter/generators.d.ts +0 -3
  83. package/dist/interpreter/generators.js +0 -168
  84. package/dist/interpreter/globals.js +0 -144
  85. package/dist/interpreter/interpreter.d.ts +0 -48
  86. package/dist/interpreter/interpreter.js +0 -2253
  87. package/dist/interpreter/intrinsics.d.ts +0 -15
  88. package/dist/interpreter/intrinsics.js +0 -105
  89. package/dist/interpreter/model.d.ts +0 -68
  90. package/dist/interpreter/model.js +0 -54
  91. package/dist/interpreter/native.d.ts +0 -17
  92. package/dist/interpreter/native.js +0 -35
  93. package/dist/interpreter/objects.d.ts +0 -301
  94. package/dist/interpreter/objects.js +0 -592
  95. package/dist/interpreter/promises.d.ts +0 -18
  96. package/dist/interpreter/promises.js +0 -292
  97. package/dist/interpreter/runner.d.ts +0 -178
  98. package/dist/interpreter/runner.js +0 -480
  99. package/dist/interpreter/scope.d.ts +0 -16
  100. package/dist/interpreter/scope.js +0 -79
  101. package/dist/suspend-error.d.ts +0 -24
  102. package/dist/suspend-error.js +0 -25
  103. package/dist/vm/data.d.ts +0 -7
  104. package/dist/vm/data.js +0 -13
  105. package/dist/vm/index.d.ts +0 -6
  106. package/dist/vm/index.js +0 -6
  107. package/dist/vm/runtime/errors.d.ts +0 -23
  108. package/dist/vm/runtime/globals.d.ts +0 -6
  109. package/dist/vm/runtime/limits.d.ts +0 -10
  110. package/dist/vm/runtime/limits.js +0 -19
  111. package/dist/vm/runtime/modules.d.ts +0 -4
  112. package/dist/vm/runtime/modules.js +0 -33
  113. package/dist/vm/runtime/references.d.ts +0 -8
  114. package/dist/vm/runtime/references.js +0 -51
  115. package/dist/vm/stdlib/array.d.ts +0 -16
  116. package/dist/vm/stdlib/array.js +0 -311
  117. package/dist/vm/stdlib/bytes.d.ts +0 -11
  118. package/dist/vm/stdlib/bytes.js +0 -222
  119. package/dist/vm/stdlib/collections.d.ts +0 -7
  120. package/dist/vm/stdlib/collections.js +0 -188
  121. package/dist/vm/stdlib/console.d.ts +0 -6
  122. package/dist/vm/stdlib/console.js +0 -93
  123. package/dist/vm/stdlib/date.d.ts +0 -2
  124. package/dist/vm/stdlib/date.js +0 -123
  125. package/dist/vm/stdlib/headers.d.ts +0 -2
  126. package/dist/vm/stdlib/headers.js +0 -92
  127. package/dist/vm/stdlib/iterator.d.ts +0 -2
  128. package/dist/vm/stdlib/iterator.js +0 -30
  129. package/dist/vm/stdlib/json.d.ts +0 -3
  130. package/dist/vm/stdlib/json.js +0 -42
  131. package/dist/vm/stdlib/math.d.ts +0 -3
  132. package/dist/vm/stdlib/math.js +0 -73
  133. package/dist/vm/stdlib/number.d.ts +0 -3
  134. package/dist/vm/stdlib/number.js +0 -72
  135. package/dist/vm/stdlib/object.d.ts +0 -6
  136. package/dist/vm/stdlib/object.js +0 -201
  137. package/dist/vm/stdlib/regexp.d.ts +0 -8
  138. package/dist/vm/stdlib/regexp.js +0 -119
  139. package/dist/vm/stdlib/string.d.ts +0 -2
  140. package/dist/vm/stdlib/string.js +0 -272
  141. package/dist/vm/stdlib/url.d.ts +0 -25
  142. package/dist/vm/stdlib/url.js +0 -255
  143. package/dist/vm/stdlib/value.d.ts +0 -6
  144. package/dist/vm/stdlib/value.js +0 -32
  145. package/dist/vm/stdlib/web.d.ts +0 -5
  146. package/dist/vm/stdlib/web.js +0 -97
  147. /package/dist/{vm/async.js → async.js} +0 -0
  148. /package/dist/{vm/code.d.ts → code.d.ts} +0 -0
  149. /package/dist/{vm/code.js → code.js} +0 -0
  150. /package/dist/{vm/compiler → compiler}/compile.d.ts +0 -0
  151. /package/dist/{vm/compiler → compiler}/compile.js +0 -0
  152. /package/dist/{vm/compiler → compiler}/scope.d.ts +0 -0
  153. /package/dist/{vm/compiler → compiler}/scope.js +0 -0
  154. /package/dist/{vm/generators.d.ts → generators.d.ts} +0 -0
  155. /package/dist/{vm/generators.js → generators.js} +0 -0
  156. /package/dist/{vm/host.js → host.js} +0 -0
  157. /package/dist/{vm/internal-prelude.d.ts → internal-prelude.d.ts} +0 -0
  158. /package/dist/{vm/internal-prelude.js → internal-prelude.js} +0 -0
  159. /package/dist/{vm/opcodes.js → opcodes.js} +0 -0
  160. /package/dist/{vm/prelude → prelude}/bytecode.d.ts +0 -0
  161. /package/dist/{vm/prelude → prelude}/bytecode.js +0 -0
  162. /package/dist/{vm/prelude → prelude}/bytecode.json +0 -0
  163. /package/dist/{vm/prelude → prelude}/helpers.d.ts +0 -0
  164. /package/dist/{vm/prelude → prelude}/prelude.d.ts +0 -0
  165. /package/dist/{vm/prelude → prelude}/prelude.js +0 -0
  166. /package/dist/{vm/prelude → prelude}/source.d.ts +0 -0
  167. /package/dist/{vm/prelude → prelude}/source.js +0 -0
  168. /package/dist/{vm/runtime → runtime}/callback.d.ts +0 -0
  169. /package/dist/{vm/runtime → runtime}/callback.js +0 -0
  170. /package/dist/{interpreter → runtime}/errors.d.ts +0 -0
  171. /package/dist/{vm/runtime → runtime}/generators.d.ts +0 -0
  172. /package/dist/{vm/runtime → runtime}/generators.js +0 -0
  173. /package/dist/{interpreter → runtime}/globals.d.ts +0 -0
  174. /package/dist/{vm/runtime → runtime}/interpreter.js +0 -0
  175. /package/dist/{vm/runtime → runtime}/intrinsic-names.d.ts +0 -0
  176. /package/dist/{vm/runtime → runtime}/intrinsic-names.js +0 -0
  177. /package/dist/{vm/runtime → runtime}/intrinsics.d.ts +0 -0
  178. /package/dist/{vm/runtime → runtime}/intrinsics.js +0 -0
  179. /package/dist/{interpreter → runtime}/limits.d.ts +0 -0
  180. /package/dist/{interpreter → runtime}/limits.js +0 -0
  181. /package/dist/{vm/runtime → runtime}/model.js +0 -0
  182. /package/dist/{interpreter → runtime}/modules.d.ts +0 -0
  183. /package/dist/{interpreter → runtime}/modules.js +0 -0
  184. /package/dist/{vm/runtime → runtime}/native.d.ts +0 -0
  185. /package/dist/{vm/runtime → runtime}/native.js +0 -0
  186. /package/dist/{vm/runtime → runtime}/promises.d.ts +0 -0
  187. /package/dist/{vm/runtime → runtime}/promises.js +0 -0
  188. /package/dist/{interpreter → runtime}/references.d.ts +0 -0
  189. /package/dist/{interpreter → runtime}/references.js +0 -0
  190. /package/dist/{vm/runtime → runtime}/signals.d.ts +0 -0
  191. /package/dist/{vm/runtime → runtime}/signals.js +0 -0
  192. /package/dist/{vm/runtime → runtime}/source.d.ts +0 -0
  193. /package/dist/{vm/runtime → runtime}/source.js +0 -0
  194. /package/dist/{vm/runtime → runtime}/table.d.ts +0 -0
  195. /package/dist/{vm/runtime → runtime}/table.js +0 -0
  196. /package/dist/{vm/scheduler.js → scheduler.js} +0 -0
  197. /package/dist/{vm/snapshot.d.ts → snapshot.d.ts} +0 -0
@@ -1,480 +0,0 @@
1
- import { Cause, Effect, Exit, Fiber } from "effect";
2
- import { Interruption } from "./callback.js";
3
- import { locate, normalizeError } from "./errors.js";
4
- import { MAX_PENDING_PROMISES } from "./limits.js";
5
- import { PendingThrow, rangeError, Throw, typeError } from "./model.js";
6
- import { fn } from "./native.js";
7
- import { get, Obj, PromiseObj } from "./objects.js";
8
- import { typeofValue } from "./references.js";
9
- export const normal = (value) => ({ ok: true, value });
10
- export const abrupt = (error) => ({ ok: false, error });
11
- /** Run `body` as a new activation; a boundary marks where a suspended body splits off the stack. */
12
- export class Call {
13
- body;
14
- boundary;
15
- constructor(body, boundary) {
16
- this.body = body;
17
- this.boundary = boundary;
18
- }
19
- }
20
- /** Push saved activations back on the stack and continue the top one with `input`. */
21
- export class Enter {
22
- entries;
23
- input;
24
- constructor(entries, input) {
25
- this.entries = entries;
26
- this.input = input;
27
- }
28
- }
29
- /** Suspend the innermost async body until `value` settles; a stall while it waits is reported at `node`. */
30
- export class Await {
31
- value;
32
- node;
33
- constructor(value, node) {
34
- this.value = value;
35
- this.node = node;
36
- }
37
- }
38
- /** Suspend the innermost generator body, producing `value`; it continues with the next request. */
39
- export class Yield {
40
- value;
41
- constructor(value) {
42
- this.value = value;
43
- }
44
- }
45
- /** Block the current job on host work: no other job runs until it ends, as with a synchronous host call. */
46
- export class Host {
47
- effect;
48
- constructor(effect) {
49
- this.effect = effect;
50
- }
51
- }
52
- /** Let the host run; the current job continues before any other job. */
53
- export const Slice = Symbol("codemode.slice");
54
- /** The boundary of an async body: the body's completion settles it, and the caller receives `result` at once. */
55
- export class AsyncBoundary {
56
- settle;
57
- result;
58
- async = true;
59
- generator = false;
60
- constructor(settle, result) {
61
- this.settle = settle;
62
- this.result = result;
63
- }
64
- finish(completion) {
65
- this.settle(completion);
66
- return normal(this.result);
67
- }
68
- suspended() {
69
- return normal(this.result);
70
- }
71
- yielded() {
72
- return abrupt(typeError("yield is only valid inside a generator."));
73
- }
74
- }
75
- /** Paused or running program code: activations on an explicit stack, innermost last. */
76
- export class Task {
77
- stack;
78
- constructor(stack) {
79
- this.stack = stack;
80
- }
81
- }
82
- /** Most activations one task may hold, as the call-stack limit. */
83
- export const MAX_CALL_DEPTH = 10_000;
84
- /** Interpreter steps between clock checks, and how long one slice may run before the host gets a turn. */
85
- const FUEL = 64;
86
- const SLICE_MS = 1;
87
- /**
88
- * One execution's job queue. Program code runs only inside a job, one job at a time and each to completion, as in a
89
- * JavaScript engine: promise reactions and resumed awaits queue in order, host work runs concurrently and settles its
90
- * promise as a later job, and the program is stuck exactly when no job is queued and no host work is running.
91
- */
92
- export class Runner {
93
- ctx;
94
- services;
95
- /** The intrinsic `Promise.prototype.then`, so adopting a native promise skips exposing its rejection first. */
96
- intrinsicThen;
97
- queue = [];
98
- head = 0;
99
- current;
100
- fuel = FUEL;
101
- sliceStart = 0;
102
- pending = 0;
103
- nextID = 0;
104
- /** Rejections nothing handled yet, described when they happened so reporting them at the end is cheap. */
105
- unhandled = new Map();
106
- /** Bodies suspended at an `await` and the promise each waits on, so a stall can point at the one that is stuck. */
107
- parked = new Map();
108
- fibers = new Set();
109
- inbox = [];
110
- wake;
111
- stopping = false;
112
- constructor(ctx,
113
- /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
114
- services) {
115
- this.ctx = ctx;
116
- this.services = services;
117
- }
118
- /** Activations on the running task's stack. */
119
- get depth() {
120
- return this.current?.stack.length ?? 0;
121
- }
122
- /**
123
- * Runs the program as the first job until its body completes, then returns how it ended. Host work it started may
124
- * still be running; `interrupt` stops it.
125
- */
126
- run(main) {
127
- const self = this;
128
- return Effect.gen(function* () {
129
- let outcome;
130
- let start = {
131
- task: new Task([
132
- {
133
- body: main,
134
- boundary: new AsyncBoundary((completion) => {
135
- outcome = completion;
136
- }, undefined),
137
- },
138
- ]),
139
- input: normal(undefined),
140
- };
141
- self.sliceStart = performance.now();
142
- while (outcome === undefined) {
143
- if (start === undefined) {
144
- const job = self.dequeue();
145
- if (job !== undefined) {
146
- start = job() ?? undefined;
147
- if (start === undefined && self.tick())
148
- yield* self.yieldToHost;
149
- continue;
150
- }
151
- const settle = self.inbox.shift();
152
- if (settle !== undefined) {
153
- settle();
154
- continue;
155
- }
156
- if (self.fibers.size > 0) {
157
- yield* self.hostSettled;
158
- continue;
159
- }
160
- return abrupt(new PendingThrow("Error", "The program is waiting on a promise that can never settle: nothing else is running, so nothing can resolve it. Code Mode has no timers or sleep, so don't wait or poll inside a program.", self.stuckAwait()));
161
- }
162
- const pause = self.drive(start.task, start.input);
163
- if (pause === undefined) {
164
- start = undefined;
165
- if (self.tick())
166
- yield* self.yieldToHost;
167
- continue;
168
- }
169
- if (pause.kind === "slice") {
170
- start = { task: start.task, input: pause.input };
171
- yield* self.yieldToHost;
172
- continue;
173
- }
174
- const exit = yield* Effect.exit(pause.effect);
175
- if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause))
176
- return yield* Effect.failCause(exit.cause);
177
- start = {
178
- task: start.task,
179
- input: Exit.isSuccess(exit) ? normal(exit.value) : abrupt(Cause.squash(exit.cause)),
180
- };
181
- }
182
- if (!outcome.ok && outcome.error instanceof Interruption)
183
- return yield* Effect.failCause(outcome.error.cause);
184
- return outcome;
185
- });
186
- }
187
- /** Stops host work still running, waiting for its cleanup. */
188
- interrupt() {
189
- const self = this;
190
- return Effect.gen(function* () {
191
- self.stopping = true;
192
- while (self.fibers.size > 0)
193
- yield* Fiber.interruptAll([...self.fibers]);
194
- });
195
- }
196
- /**
197
- * Rejections no handler observed, in the order their promises were created. Host work that finished before the
198
- * program did settles first, so its failures count even though no later job ran.
199
- */
200
- diagnostics() {
201
- for (let settle = this.inbox.shift(); settle !== undefined; settle = this.inbox.shift())
202
- settle();
203
- return [...this.unhandled].sort(([left], [right]) => left.id - right.id).map(([, diagnostic]) => diagnostic);
204
- }
205
- /** Counts one interpreter step; true when the slice is over and the caller should yield `Slice`. */
206
- tick() {
207
- if (--this.fuel > 0)
208
- return false;
209
- this.fuel = FUEL;
210
- return performance.now() - this.sliceStart >= SLICE_MS;
211
- }
212
- /** A blocking host call, with the caller's services provided so the runner can run it as is. */
213
- blocking(effect) {
214
- return new Host(Effect.provideContext(effect, this.services));
215
- }
216
- enqueue(job) {
217
- this.queue.push(job);
218
- }
219
- /**
220
- * Starts host work now; its completion settles through `settle` in a later job, in completion order. A defect is
221
- * located at `site`, the call that started the work.
222
- */
223
- host(effect, settle, site) {
224
- // Starts synchronously, so admission and hooks happen at the call site.
225
- const fiber = Effect.runForkWith(this.services)(effect);
226
- this.fibers.add(fiber);
227
- fiber.addObserver((exit) => {
228
- this.fibers.delete(fiber);
229
- // Interrupted by the program ending: nothing is left to settle.
230
- if (this.stopping)
231
- return;
232
- this.inbox.push(() => settle(Exit.isSuccess(exit)
233
- ? normal(exit.value)
234
- : abrupt(Cause.hasInterruptsOnly(exit.cause)
235
- ? new Interruption(exit.cause)
236
- : Cause.hasDies(exit.cause)
237
- ? locate(Cause.squash(exit.cause), site)
238
- : Cause.squash(exit.cause))));
239
- this.wake?.();
240
- });
241
- }
242
- // --- Promise abstract operations ---
243
- newPromise() {
244
- if (this.pending >= MAX_PENDING_PROMISES) {
245
- throw rangeError(`Too many pending promises (limit ${MAX_PENDING_PROMISES}); await promises before creating more.`);
246
- }
247
- this.pending++;
248
- return new PromiseObj(this.ctx.builtins.Promise, this.nextID++);
249
- }
250
- /**
251
- * CreateResolvingFunctions, for host callers; `reject` takes the failure as thrown. A failure without a location is
252
- * located at `site`, the call that created the promise.
253
- */
254
- resolving(promise, site) {
255
- let done = false;
256
- return {
257
- resolve: (resolution) => {
258
- if (done)
259
- return;
260
- done = true;
261
- this.resolveWith(promise, resolution, site);
262
- },
263
- reject: (reason) => {
264
- if (done)
265
- return;
266
- done = true;
267
- this.settle(promise, abrupt(locate(reason, site)));
268
- },
269
- };
270
- }
271
- /** PerformPromiseThen with one reaction for either outcome; marks the promise handled. */
272
- then(promise, reaction) {
273
- if (promise.state === "pending")
274
- promise.reactions.push(reaction);
275
- else {
276
- if (promise.state === "rejected")
277
- this.unhandled.delete(promise);
278
- const settled = promise.state === "fulfilled" ? normal(promise.result) : abrupt(promise.result);
279
- this.enqueue(() => reaction(settled));
280
- }
281
- promise.handled = true;
282
- }
283
- /** Removes a reaction an internal consumer no longer needs, so a long-pending promise does not keep it. */
284
- detach(promise, reaction) {
285
- const index = promise.reactions.indexOf(reaction);
286
- if (index >= 0)
287
- promise.reactions.splice(index, 1);
288
- }
289
- /** PromiseResolve(%Promise%, value). */
290
- promiseResolve(value) {
291
- if (value instanceof PromiseObj)
292
- return value;
293
- const promise = this.newPromise();
294
- this.resolveWith(promise, value);
295
- return promise;
296
- }
297
- settle(promise, completion) {
298
- if (promise.state !== "pending")
299
- return;
300
- this.pending--;
301
- promise.state = completion.ok ? "fulfilled" : "rejected";
302
- promise.result = completion.ok ? completion.value : completion.error;
303
- const reactions = promise.reactions;
304
- promise.reactions = [];
305
- if (!completion.ok && !promise.handled && !(completion.error instanceof Interruption)) {
306
- const failure = normalizeError(completion.error);
307
- this.unhandled.set(promise, {
308
- ...failure,
309
- message: `Unhandled rejection from an un-awaited promise: ${failure.message}`,
310
- });
311
- }
312
- for (const reaction of reactions)
313
- this.enqueue(() => reaction(completion));
314
- }
315
- resolveWith(promise, resolution, site) {
316
- if (resolution === promise) {
317
- const cycle = typeError("Chaining cycle detected: a promise cannot resolve with itself.", site);
318
- return this.settle(promise, abrupt(cycle));
319
- }
320
- if (!(resolution instanceof Obj))
321
- return this.settle(promise, normal(resolution));
322
- const then = get(resolution, "then");
323
- if (typeofValue(then) !== "function")
324
- return this.settle(promise, normal(resolution));
325
- this.enqueue(() => this.thenableJob(promise, resolution, then));
326
- }
327
- // NewPromiseResolveThenableJob. Adopting a native promise through the intrinsic `then` takes the same jobs as
328
- // calling it, and keeps the rejection as thrown so its diagnostic survives.
329
- thenableJob(promise, thenable, then) {
330
- const resolving = this.resolving(promise);
331
- if (then === this.intrinsicThen && thenable instanceof PromiseObj) {
332
- this.then(thenable, (settled) => settled.ok ? resolving.resolve(settled.value) : resolving.reject(settled.error));
333
- return;
334
- }
335
- const builtins = this.ctx.builtins;
336
- const resolve = fn(builtins, "", 1, (_, args) => {
337
- resolving.resolve(args[0]);
338
- return undefined;
339
- });
340
- const reject = fn(builtins, "", 1, (_, args) => {
341
- resolving.reject(new Throw(args[0]));
342
- return undefined;
343
- });
344
- const ctx = this.ctx;
345
- const body = function* () {
346
- try {
347
- yield* ctx.call(then, thenable, [resolve, reject]);
348
- }
349
- catch (error) {
350
- resolving.reject(error);
351
- }
352
- };
353
- return { task: new Task([{ body: body(), boundary: undefined }]), input: normal(undefined) };
354
- }
355
- // --- Driver ---
356
- // Runs a task until its stack empties or it pauses for a slice or host work, which resumes it before any other job.
357
- drive(task, input) {
358
- const stack = task.stack;
359
- this.current = task;
360
- let completion = input;
361
- while (stack.length > 0) {
362
- const entry = stack[stack.length - 1];
363
- let step;
364
- try {
365
- step = completion.ok ? entry.body.next(completion.value) : entry.body.throw(completion.error);
366
- }
367
- catch (error) {
368
- stack.pop();
369
- completion = entry.boundary === undefined ? abrupt(error) : entry.boundary.finish(abrupt(error));
370
- continue;
371
- }
372
- if (step.done) {
373
- stack.pop();
374
- completion = entry.boundary === undefined ? normal(step.value) : entry.boundary.finish(normal(step.value));
375
- continue;
376
- }
377
- const signal = step.value;
378
- if (signal instanceof Call) {
379
- stack.push({ body: signal.body, boundary: signal.boundary });
380
- completion = normal(undefined);
381
- if (this.tick())
382
- return { kind: "slice", input: completion };
383
- continue;
384
- }
385
- if (signal instanceof Enter) {
386
- for (const saved of signal.entries)
387
- stack.push(saved);
388
- completion = signal.input;
389
- if (this.tick())
390
- return { kind: "slice", input: completion };
391
- continue;
392
- }
393
- if (signal instanceof Await) {
394
- const index = stack.findLastIndex((item) => item.boundary?.async === true);
395
- if (index < 0) {
396
- completion = abrupt(typeError("await is only valid in async functions."));
397
- continue;
398
- }
399
- let promise;
400
- try {
401
- promise = this.promiseResolve(signal.value);
402
- }
403
- catch (error) {
404
- completion = abrupt(error);
405
- continue;
406
- }
407
- const boundary = stack[index].boundary;
408
- const continuation = new Task(stack.splice(index));
409
- this.parked.set(continuation, { promise, node: signal.node });
410
- this.then(promise, (settled) => {
411
- this.parked.delete(continuation);
412
- return { task: continuation, input: settled };
413
- });
414
- completion = boundary.suspended();
415
- continue;
416
- }
417
- if (signal instanceof Yield) {
418
- const index = stack.findLastIndex((item) => item.boundary?.generator === true);
419
- if (index < 0) {
420
- completion = abrupt(typeError("yield is only valid inside a generator."));
421
- continue;
422
- }
423
- completion = stack[index].boundary.yielded(signal.value, () => stack.splice(index));
424
- continue;
425
- }
426
- if (signal instanceof Host)
427
- return { kind: "host", effect: signal.effect };
428
- return { kind: "slice", input: normal(undefined) };
429
- }
430
- this.current = undefined;
431
- if (!completion.ok)
432
- throw completion.error;
433
- return undefined;
434
- }
435
- // The innermost stuck `await`: an outer one waits on the result of a parked async body, so prefer one that does not.
436
- // Bodies that wait on each other in a cycle leave no such await; any located one is then as good as another.
437
- stuckAwait() {
438
- const results = new Set();
439
- for (const task of this.parked.keys()) {
440
- const boundary = task.stack[0]?.boundary;
441
- if (boundary instanceof AsyncBoundary)
442
- results.add(boundary.result);
443
- }
444
- const located = [...this.parked.values()].filter((parked) => parked.node !== undefined);
445
- return (located.find((parked) => !results.has(parked.promise)) ?? located[0])?.node;
446
- }
447
- dequeue() {
448
- if (this.head === this.queue.length) {
449
- if (this.head > 0) {
450
- this.queue.length = 0;
451
- this.head = 0;
452
- }
453
- return undefined;
454
- }
455
- const job = this.queue[this.head++];
456
- if (this.head > 4096 && this.head * 2 > this.queue.length) {
457
- this.queue.splice(0, this.head);
458
- this.head = 0;
459
- }
460
- return job;
461
- }
462
- get yieldToHost() {
463
- return Effect.map(Effect.yieldNow, () => {
464
- this.sliceStart = performance.now();
465
- });
466
- }
467
- get hostSettled() {
468
- return Effect.callback((resume) => {
469
- if (this.inbox.length > 0)
470
- return resume(Effect.void);
471
- this.wake = () => {
472
- this.wake = undefined;
473
- resume(Effect.void);
474
- };
475
- return Effect.sync(() => {
476
- this.wake = undefined;
477
- });
478
- });
479
- }
480
- }
@@ -1,16 +0,0 @@
1
- import { type AstNode, type Binding } from "./model.js";
2
- import type { Value } from "./objects.js";
3
- export declare class ScopeStack {
4
- private readonly scopes;
5
- constructor(scopes: Array<Map<string, Binding>>);
6
- reserve(name: string, mutable: boolean, node: AstNode): void;
7
- initialize(name: string, value: Value, node: AstNode): void;
8
- declare(name: string, value: Value, mutable: boolean, node: AstNode): void;
9
- get(name: string, node: AstNode): Value;
10
- set(name: string, value: Value, node: AstNode): Value;
11
- resolve(name: string): Binding | undefined;
12
- current(): Map<string, Binding>;
13
- push(scope?: Map<string, Binding>): void;
14
- pop(): void;
15
- capture(): Array<Map<string, Binding>>;
16
- }
@@ -1,79 +0,0 @@
1
- import { referenceError, typeError } from "./model.js";
2
- export class ScopeStack {
3
- scopes;
4
- constructor(scopes) {
5
- this.scopes = scopes;
6
- }
7
- reserve(name, mutable, node) {
8
- const scope = this.current();
9
- if (scope.has(name)) {
10
- throw typeError(`Identifier '${name}' has already been declared.`, node);
11
- }
12
- scope.set(name, { mutable, value: undefined, initialized: false });
13
- }
14
- initialize(name, value, node) {
15
- const binding = this.current().get(name);
16
- if (!binding || binding.initialized !== false) {
17
- throw typeError(`Identifier '${name}' has not been reserved for initialization.`, node);
18
- }
19
- binding.value = value;
20
- binding.initialized = true;
21
- }
22
- declare(name, value, mutable, node) {
23
- const scope = this.current();
24
- if (scope.has(name)) {
25
- throw typeError(`Identifier '${name}' has already been declared.`, node);
26
- }
27
- scope.set(name, { mutable, value, initialized: true });
28
- }
29
- get(name, node) {
30
- const binding = this.resolve(name);
31
- if (!binding) {
32
- throw referenceError(`Unknown identifier '${name}'.`, node);
33
- }
34
- if (binding.initialized === false) {
35
- throw referenceError(`Cannot access '${name}' before initialization.`, node);
36
- }
37
- return binding.value;
38
- }
39
- set(name, value, node) {
40
- const binding = this.resolve(name);
41
- if (!binding) {
42
- throw referenceError(`Unknown identifier '${name}'.`, node);
43
- }
44
- if (binding.initialized === false) {
45
- throw referenceError(`Cannot access '${name}' before initialization.`, node);
46
- }
47
- if (!binding.mutable) {
48
- throw typeError(`Cannot assign to constant '${name}'.`, node);
49
- }
50
- binding.value = value;
51
- return value;
52
- }
53
- resolve(name) {
54
- for (let index = this.scopes.length - 1; index >= 0; index -= 1) {
55
- const scope = this.scopes[index];
56
- const binding = scope?.get(name);
57
- if (binding) {
58
- return binding;
59
- }
60
- }
61
- return undefined;
62
- }
63
- current() {
64
- const scope = this.scopes[this.scopes.length - 1];
65
- if (!scope) {
66
- throw typeError("Interpreter scope stack is empty.");
67
- }
68
- return scope;
69
- }
70
- push(scope = new Map()) {
71
- this.scopes.push(scope);
72
- }
73
- pop() {
74
- this.scopes.pop();
75
- }
76
- capture() {
77
- return this.scopes.slice();
78
- }
79
- }
@@ -1,24 +0,0 @@
1
- import { Schema } from "effect";
2
- import type { Snapshot } from "./vm/snapshot/snapshot.js";
3
- declare const SuspendError_base: Schema.Class<SuspendError, Schema.TaggedStruct<"SuspendError", {
4
- readonly message: Schema.String;
5
- readonly running: Schema.$Array<Schema.Struct<{
6
- readonly key: Schema.String;
7
- readonly path: Schema.String;
8
- }>>;
9
- }>, import("effect/Cause").YieldableError>;
10
- /**
11
- * A suspend that failed, leaving the run running: `running` names each host call that blocked it by its key and its
12
- * path (`tools.x.y`, `search`, or an extension function's path such as `fetch`). Empty when the state couldn't be
13
- * saved or was too large.
14
- */
15
- export declare class SuspendError extends SuspendError_base {
16
- }
17
- export declare class SnapshotError extends Error {
18
- readonly name = "SnapshotError";
19
- }
20
- /** A snapshot as bytes: UTF-8 JSON. */
21
- export declare const toBytes: (snapshot: Snapshot) => Uint8Array;
22
- /** Reads bytes `toBytes` wrote; `restore` checks what they hold. */
23
- export declare const fromBytes: (bytes: Uint8Array) => unknown;
24
- export {};
@@ -1,25 +0,0 @@
1
- import { Schema } from "effect";
2
- /**
3
- * A suspend that failed, leaving the run running: `running` names each host call that blocked it by its key and its
4
- * path (`tools.x.y`, `search`, or an extension function's path such as `fetch`). Empty when the state couldn't be
5
- * saved or was too large.
6
- */
7
- export class SuspendError extends Schema.TaggedError()("SuspendError", {
8
- message: Schema.String,
9
- running: Schema.Array(Schema.Struct({ key: Schema.String, path: Schema.String })),
10
- }) {
11
- }
12
- export class SnapshotError extends Error {
13
- name = "SnapshotError";
14
- }
15
- /** A snapshot as bytes: UTF-8 JSON. */
16
- export const toBytes = (snapshot) => new TextEncoder().encode(JSON.stringify(snapshot));
17
- /** Reads bytes `toBytes` wrote; `restore` checks what they hold. */
18
- export const fromBytes = (bytes) => {
19
- try {
20
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
21
- }
22
- catch (error) {
23
- throw new SnapshotError(`Invalid snapshot: the bytes are not UTF-8 JSON (${String(error)}).`);
24
- }
25
- };
package/dist/vm/data.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export * as Data from "./data.js";
2
- import type { Json } from "../data.js";
3
- import type { Interpreter } from "./runtime/interpreter.js";
4
- import { type Value } from "./runtime/objects.js";
5
- export type { Json };
6
- /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
7
- export declare const fromJson: <R>(ctx: Interpreter<R>, value: Json | undefined) => Value;
package/dist/vm/data.js DELETED
@@ -1,13 +0,0 @@
1
- export * as Data from "./data.js";
2
- import { Arr, define, Obj } from "./runtime/objects.js";
3
- /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
4
- export const fromJson = (ctx, value) => {
5
- if (value === null || typeof value !== "object")
6
- return value;
7
- if (Array.isArray(value))
8
- return new Arr(ctx.builtins.Array, value.map((item) => fromJson(ctx, item)));
9
- const copied = new Obj(ctx.builtins.Object);
10
- for (const [key, item] of Object.entries(value))
11
- define(copied, key, fromJson(ctx, item));
12
- return copied;
13
- };
@@ -1,6 +0,0 @@
1
- export * as VmEngine from "./index.js";
2
- export { fromJson } from "./data.js";
3
- export { execute, finishExecution, resumeProgram, type Running, type Setup, startProgram } from "./runtime/execute.js";
4
- export { extensionGlobals } from "./runtime/extensions.js";
5
- export { globalNames } from "./runtime/globals.js";
6
- export { fromBytes, type Snapshot, SnapshotError, type SnapshotHeader, toBytes } from "./snapshot/snapshot.js";
package/dist/vm/index.js DELETED
@@ -1,6 +0,0 @@
1
- export * as VmEngine from "./index.js";
2
- export { fromJson } from "./data.js";
3
- export { execute, finishExecution, resumeProgram, startProgram } from "./runtime/execute.js";
4
- export { extensionGlobals } from "./runtime/extensions.js";
5
- export { globalNames } from "./runtime/globals.js";
6
- export { fromBytes, SnapshotError, toBytes } from "./snapshot/snapshot.js";