@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,248 +0,0 @@
1
- import { Effect } from "effect";
2
- import { isAsync } from "../extension.js";
3
- import { hooked } from "../tool-runtime.js";
4
- import { errorMessage, errorType } from "./errors.js";
5
- import { createErrorValue } from "./intrinsics.js";
6
- import { MAX_ARRAY_LENGTH, MAX_VALUE_DEPTH } from "./limits.js";
7
- import { PendingThrow, rangeError, Throw, typeError } from "./model.js";
8
- import { fn } from "./native.js";
9
- import { define, get, has, hidden, keys, Arr, Bytes, DateObj, ErrorObj, HeadersObj, MapObj, Obj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, coerceToString, } from "./objects.js";
10
- import { describeValue, isOpaque } from "./references.js";
11
- /**
12
- * The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and built-in
13
- * wrappers are copied, a host function becomes a program function whose calls cross the same way, and a host Promise
14
- * or Effect becomes a program promise.
15
- */
16
- export const extensionGlobals = (ctx, extensions) => {
17
- const builtins = ctx.builtins;
18
- const toHost = (value, label, depth = 0, seen = new Set()) => {
19
- if (depth > MAX_VALUE_DEPTH)
20
- throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
21
- if (isPrimitive(value))
22
- return value;
23
- if (!(value instanceof Obj) || isOpaque(value)) {
24
- throw typeError(`${label} contains ${describeValue(value)}, which cannot be passed to an extension.`);
25
- }
26
- if (seen.has(value))
27
- throw typeError(`${label} contains a circular value.`);
28
- seen.add(value);
29
- const next = (item) => toHost(item, label, depth + 1, seen);
30
- if (value instanceof ErrorObj) {
31
- const name = coerceToString(get(value, "name"));
32
- const message = get(value, "message");
33
- const text = message === undefined ? "" : coerceToString(message);
34
- const copied = name === "AggregateError" ? new AggregateError([], text) : new (hostErrors.get(name) ?? Error)(text);
35
- for (const key of new Set(["cause", ...keys(value)])) {
36
- if (uncrossed.has(key) || !has(value, key))
37
- continue;
38
- const item = crossing(() => next(get(value, key)));
39
- if (item === left)
40
- continue;
41
- Object.defineProperty(copied, key, {
42
- value: item,
43
- writable: true,
44
- configurable: true,
45
- enumerable: key !== "cause",
46
- });
47
- }
48
- seen.delete(value);
49
- return copied;
50
- }
51
- const copied = value.toHost(next);
52
- seen.delete(value);
53
- return copied;
54
- };
55
- // `extension` is set while converting a global object, whose functions are entry points like globals and fire the hooks.
56
- const fromHost = (value, label, depth = 0, seen = new Set(), extension) => {
57
- if (depth > MAX_VALUE_DEPTH)
58
- throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
59
- if (isPrimitive(value))
60
- return value;
61
- if (typeof value === "function")
62
- return wrap(value, label, extension === undefined ? undefined : (args) => ({ extension, name: label, args }));
63
- if (value !== null && typeof value === "object") {
64
- const next = (item, path) => fromHost(item, path, depth + 1, seen, extension);
65
- // Nothing a host value hands back is kept: results are read as primitives or copied. Where the value's own
66
- // method could hand back host storage or an object (`getTime`, `slice`, `map`), its internal data is read.
67
- if (value instanceof Date)
68
- return new DateObj(builtins.Date, Date.prototype.getTime.call(value));
69
- if (value instanceof RegExp)
70
- return new RegExpObj(builtins.RegExp, value.source, value.flags);
71
- if (value instanceof Uint8Array)
72
- return new Bytes(builtins.Uint8Array, new Uint8Array(value));
73
- if (value instanceof ArrayBuffer) {
74
- const view = new Uint8Array(value);
75
- // Only a real buffer has bytes to view; anything else would be read as array-like and lose them silently.
76
- if (view.buffer !== value)
77
- throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
78
- return new Bytes(builtins.Uint8Array, new Uint8Array(view));
79
- }
80
- if (value instanceof Error) {
81
- if (seen.has(value))
82
- throw typeError(`${label} produced a circular value.`);
83
- seen.add(value);
84
- const copied = createErrorValue(builtins[errorType(value)], errorMessage(value));
85
- const fields = value;
86
- for (const key of new Set(["cause", ...Object.keys(value)])) {
87
- if (uncrossed.has(key) || !(key in value))
88
- continue;
89
- // Read once: a getter could pass the check and then hand back a function.
90
- const field = fields[key];
91
- if (typeof field === "function")
92
- continue;
93
- const item = crossing(() => next(field, `${label}.${key}`));
94
- if (item === left)
95
- continue;
96
- define(copied, key, item, key === "cause" ? hidden : undefined);
97
- }
98
- seen.delete(value);
99
- return copied;
100
- }
101
- if (value instanceof URL)
102
- return new URLObj(builtins.URL, builtins.URLSearchParams, new URL(value.href));
103
- if (value instanceof URLSearchParams) {
104
- return new URLSearchParamsObj(builtins.URLSearchParams, new URLSearchParams(value));
105
- }
106
- if (value instanceof Headers)
107
- return new HeadersObj(builtins.Headers, new Headers(value));
108
- if (value instanceof Map) {
109
- const wrapped = new MapObj(builtins.Map);
110
- for (const [key, item] of value)
111
- wrapped.map.set(next(key, label), next(item, label));
112
- return wrapped;
113
- }
114
- if (value instanceof Set) {
115
- const wrapped = new SetObj(builtins.Set);
116
- for (const item of value)
117
- wrapped.set.add(next(item, label));
118
- return wrapped;
119
- }
120
- if (seen.has(value))
121
- throw typeError(`${label} produced a circular value.`);
122
- seen.add(value);
123
- if (Array.isArray(value)) {
124
- const length = value.length;
125
- if (length > MAX_ARRAY_LENGTH) {
126
- throw rangeError(`${label} produced an array of ${length} items; at most ${MAX_ARRAY_LENGTH} can cross.`);
127
- }
128
- // Filled in order so the copy stays a dense array; holes stay holes, as a copy made with `map` would leave them.
129
- const items = [];
130
- for (let index = 0; index < length; index += 1) {
131
- if (index in value)
132
- items[index] = next(value[index], `${label}[${index}]`);
133
- }
134
- items.length = length;
135
- seen.delete(value);
136
- return new Arr(builtins.Array, items);
137
- }
138
- const prototype = Object.getPrototypeOf(value);
139
- if (prototype === Object.prototype || prototype === null) {
140
- const copied = new Obj(builtins.Object);
141
- for (const [key, item] of Object.entries(value))
142
- define(copied, key, next(item, `${label}.${key}`));
143
- seen.delete(value);
144
- return copied;
145
- }
146
- }
147
- throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
148
- };
149
- // A host function as a program function. Arguments cross in; for a global or a global object's function, the
150
- // `extension.before` hook runs before the host function is called, so a call it denies never reaches the host. The
151
- // host's result, or what it threw, crosses out so the program catches a copy, and `extension.after` sees how the
152
- // call ended. Functions inside results are part of a value's API and skip the hooks.
153
- const wrap = (value, label, describe) => {
154
- // The host function's own `name` and `length` can be anything, even getters: each is read once, and only text
155
- // and a count cross.
156
- const name = value.name;
157
- const length = value.length;
158
- return fn(builtins, typeof name === "string" ? name : "", typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? length : 0, function* (_, values, site) {
159
- const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`));
160
- const cross = (reason) => new Throw(fromHost(reason, label));
161
- const call = describe?.(args);
162
- const hooks = ctx.tools.hooks;
163
- const before = call && hooks["extension.before"]?.(call).pipe(Effect.mapError(cross));
164
- const after = call && hooks["extension.after"];
165
- const settle = (effect) => (after ? hooked(call, undefined, after, effect) : effect).pipe(Effect.mapBoth({ onFailure: cross, onSuccess: (result) => fromHost(result, label) }));
166
- // A denied call fails the way the global would: an async global rejects its promise, a sync one throws.
167
- if (isAsync(value))
168
- return pending(Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => callHost(value, args).effect))), site);
169
- if (before)
170
- yield ctx.runner.blocking(before);
171
- const host = callHost(value, args);
172
- if (host.async)
173
- return pending(settle(host.effect), site);
174
- return (yield ctx.runner.blocking(settle(host.effect)));
175
- });
176
- };
177
- // An asynchronous host call: the program holds a promise that settles when the host's work does.
178
- const pending = (work, site) => {
179
- const promise = ctx.runner.newPromise();
180
- const resolving = ctx.runner.resolving(promise, site);
181
- ctx.runner.host(work, (settled) => (settled.ok ? resolving.resolve(settled.value) : resolving.reject(settled.error)), site);
182
- return promise;
183
- };
184
- return extensions.flatMap((extension) => Object.entries(extension.globals).map(([name, value]) => [
185
- name,
186
- typeof value === "function"
187
- ? wrap(value, name, (args) => ({ extension: extension.name, name, args }))
188
- : fromHost(value, name, 0, new Set(), extension.name),
189
- ]));
190
- };
191
- /**
192
- * Calls a host function and describes what the program waits on. A returned Effect or Promise settles later; a
193
- * returned value or a throw settles now.
194
- */
195
- const callHost = (value, args) => {
196
- try {
197
- const result = value.apply(undefined, args);
198
- // Extension.Services adds an Effect global's requirements to R.
199
- if (Effect.isEffect(result))
200
- return { async: true, effect: result };
201
- if (result instanceof Promise)
202
- return { async: true, effect: Effect.tryPromise({ try: () => result, catch: (reason) => reason }) };
203
- return { async: false, effect: Effect.succeed(result) };
204
- }
205
- catch (reason) {
206
- return { async: false, effect: Effect.fail(reason) };
207
- }
208
- };
209
- /**
210
- * An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`,
211
- * `syscall`, and `path`. `stack` stays on its own side, `message` crosses once as text, and no field may shadow an
212
- * Error method. A field that cannot cross (a socket, a handle, a function) is left behind so the error itself always
213
- * arrives.
214
- */
215
- const uncrossed = new Set(["stack", "message", "constructor", "toString", "__proto__"]);
216
- const left = Symbol("left behind");
217
- const crossing = (convert) => {
218
- try {
219
- return convert();
220
- }
221
- catch (reason) {
222
- if (reason instanceof PendingThrow)
223
- return left;
224
- throw reason;
225
- }
226
- };
227
- const hostErrors = new Map([
228
- ["TypeError", TypeError],
229
- ["RangeError", RangeError],
230
- ["SyntaxError", SyntaxError],
231
- ["ReferenceError", ReferenceError],
232
- ["EvalError", EvalError],
233
- ["URIError", URIError],
234
- ]);
235
- // The primitives the interpreter operates on; symbols and BigInts are not among them.
236
- const isPrimitive = (value) => value === null ||
237
- value === undefined ||
238
- typeof value === "string" ||
239
- typeof value === "number" ||
240
- typeof value === "boolean";
241
- const describeHost = (value) => {
242
- if (typeof value !== "object" || value === null)
243
- return `a ${typeof value}`;
244
- const name = value.constructor?.name;
245
- if (name === undefined || name === "")
246
- return "an object";
247
- return `${/^[AEIO]/.test(name) ? "an" : "a"} ${name}`;
248
- };
@@ -1,3 +0,0 @@
1
- import type { Interpreter } from "./interpreter.js";
2
- /** `next`/`return`/`throw` on the generator prototypes; async generators answer with promises. */
3
- export declare const generatorGlobals: <R>(ctx: Interpreter<R>) => void;
@@ -1,168 +0,0 @@
1
- import { fn, methods, receiver } from "./native.js";
2
- import { AsyncIteratorSymbol, IteratorSymbol, Throw, typeError } from "./model.js";
3
- import { define, hidden, GeneratorObj, iteratorResult } from "./objects.js";
4
- import { abrupt, Enter, normal, } from "./runner.js";
5
- /** `next`/`return`/`throw` on the generator prototypes; async generators answer with promises. */
6
- export const generatorGlobals = (ctx) => {
7
- const builtins = ctx.builtins;
8
- const sync = (kind) => [
9
- kind,
10
- 1,
11
- (thisValue, args) => {
12
- const method = `Generator.prototype.${kind}`;
13
- const generator = receiver(GeneratorObj, thisValue, method);
14
- if (generator.asynchronous)
15
- throw typeError(`${method} called on incompatible receiver an async generator.`);
16
- return step(ctx, generator, kind, args[0]);
17
- },
18
- ];
19
- const async = (kind) => [
20
- kind,
21
- 1,
22
- (thisValue, args) => request(ctx, thisValue, kind, args[0]),
23
- ];
24
- methods(builtins, builtins.Generator, [sync("next"), sync("return"), sync("throw")]);
25
- methods(builtins, builtins.AsyncGenerator, [async("next"), async("return"), async("throw")]);
26
- define(builtins.Iterator, IteratorSymbol, fn(builtins, "[Symbol.iterator]", 0, (thisValue) => thisValue), hidden);
27
- define(builtins.AsyncIterator, AsyncIteratorSymbol, fn(builtins, "[Symbol.asyncIterator]", 0, (thisValue) => thisValue), hidden);
28
- };
29
- const result = (ctx, value, done) => iteratorResult(ctx.builtins.Object, value, done);
30
- // Puts the suspended body back on the stack and continues it with `request`; the boundary answers the caller when
31
- // the body next yields or ends.
32
- const resume = (ctx, generator, request) => {
33
- const started = generator.state !== "suspendedStart";
34
- generator.state = "executing";
35
- if (!started) {
36
- return new Enter([{ body: generator.body, boundary: new GeneratorBoundary(ctx, generator) }], normal(undefined));
37
- }
38
- const entries = generator.entries;
39
- generator.entries = undefined;
40
- return new Enter(entries, normal(request));
41
- };
42
- // A synchronous generator step: the body runs on the caller's stack until it yields, returns, or throws.
43
- function* step(ctx, generator, kind, value) {
44
- if (generator.state === "executing")
45
- throw typeError("Generator is already running.");
46
- if (generator.state === "suspendedStart" && kind !== "next")
47
- generator.state = "completed";
48
- if (generator.state === "completed") {
49
- if (kind === "throw")
50
- throw new Throw(value);
51
- return result(ctx, kind === "return" ? value : undefined, true);
52
- }
53
- return (yield resume(ctx, generator, { kind, value }));
54
- }
55
- // AsyncGenerator.prototype.next/return/throw: queue the request with its promise, and run the body now if it is
56
- // waiting for one. A request that arrives while the body runs is answered when the body reaches it.
57
- function* request(ctx, thisValue, kind, value) {
58
- const runner = ctx.runner;
59
- const promise = runner.newPromise();
60
- const resolving = runner.resolving(promise);
61
- if (!(thisValue instanceof GeneratorObj) || !thisValue.asynchronous) {
62
- resolving.reject(typeError(`AsyncGenerator.prototype.${kind} called on incompatible receiver.`));
63
- return promise;
64
- }
65
- const generator = thisValue;
66
- const state = generator.state;
67
- if (kind === "next" && state === "completed") {
68
- resolving.resolve(result(ctx, undefined, true));
69
- return promise;
70
- }
71
- if (kind === "throw") {
72
- if (state === "suspendedStart")
73
- generator.state = "completed";
74
- if (generator.state === "completed") {
75
- resolving.reject(new Throw(value));
76
- return promise;
77
- }
78
- }
79
- const queued = { kind, value };
80
- generator.queue.push({ request: queued, resolving });
81
- if (kind === "return" && (state === "suspendedStart" || state === "completed")) {
82
- generator.state = "awaiting-return";
83
- awaitReturn(ctx, generator);
84
- return promise;
85
- }
86
- if (state === "suspendedStart" || state === "suspendedYield")
87
- yield resume(ctx, generator, queued);
88
- return promise;
89
- }
90
- // AsyncGeneratorCompleteStep: answer the oldest request.
91
- const completeStep = (ctx, generator, completion, done) => {
92
- const next = generator.queue.shift();
93
- if (completion.ok)
94
- next.resolving.resolve(result(ctx, completion.value, done));
95
- else
96
- next.resolving.reject(completion.error);
97
- };
98
- // AsyncGeneratorDrainQueue: once the body has ended, answer the remaining requests in order.
99
- const drainQueue = (ctx, generator) => {
100
- generator.state = "draining";
101
- while (true) {
102
- const next = generator.queue[0];
103
- if (next === undefined) {
104
- generator.state = "completed";
105
- return;
106
- }
107
- if (next.request.kind === "return") {
108
- generator.state = "awaiting-return";
109
- return awaitReturn(ctx, generator);
110
- }
111
- completeStep(ctx, generator, next.request.kind === "throw" ? abrupt(new Throw(next.request.value)) : normal(undefined), true);
112
- }
113
- };
114
- // AsyncGeneratorAwaitReturn: a `return(value)` on an ended or unstarted generator settles once `value` does.
115
- const awaitReturn = (ctx, generator) => {
116
- const runner = ctx.runner;
117
- const finish = (completion) => {
118
- completeStep(ctx, generator, completion, true);
119
- drainQueue(ctx, generator);
120
- };
121
- try {
122
- runner.then(runner.promiseResolve(generator.queue[0].request.value), finish);
123
- }
124
- catch (error) {
125
- finish(abrupt(error));
126
- }
127
- };
128
- /** Where a generator body splits off the stack when it yields, and how its end answers the request that ran it. */
129
- class GeneratorBoundary {
130
- ctx;
131
- target;
132
- generator = true;
133
- async;
134
- constructor(ctx, target) {
135
- this.ctx = ctx;
136
- this.target = target;
137
- this.async = target.asynchronous;
138
- }
139
- finish(completion) {
140
- const generator = this.target;
141
- if (!generator.asynchronous) {
142
- generator.state = "completed";
143
- return completion.ok ? normal(result(this.ctx, completion.value, true)) : completion;
144
- }
145
- completeStep(this.ctx, generator, completion, true);
146
- drainQueue(this.ctx, generator);
147
- return normal(undefined);
148
- }
149
- suspended() {
150
- return normal(undefined);
151
- }
152
- yielded(value, split) {
153
- const generator = this.target;
154
- if (!generator.asynchronous) {
155
- generator.entries = split();
156
- generator.state = "suspendedYield";
157
- return normal(result(this.ctx, value, false));
158
- }
159
- // AsyncGeneratorYield: answer the oldest request, and keep running if another is already waiting.
160
- completeStep(this.ctx, generator, normal(value), false);
161
- const next = generator.queue[0];
162
- if (next !== undefined)
163
- return normal(next.request);
164
- generator.entries = split();
165
- generator.state = "suspendedYield";
166
- return normal(undefined);
167
- }
168
- }
@@ -1,144 +0,0 @@
1
- import { Arr, Callable, coerceToInteger, coerceToString, get, Obj } from "./objects.js";
2
- import { arrayGlobal } from "../stdlib/array.js";
3
- import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js";
4
- import { mapGlobal, setGlobal, weakMapGlobal, weakSetGlobal } from "../stdlib/collections.js";
5
- import { consoleGlobal } from "../stdlib/console.js";
6
- import { dateGlobal } from "../stdlib/date.js";
7
- import { jsonGlobal } from "../stdlib/json.js";
8
- import { mathGlobal } from "../stdlib/math.js";
9
- import { booleanGlobal, numberGlobal } from "../stdlib/number.js";
10
- import { objectGlobal } from "../stdlib/object.js";
11
- import { regexpGlobal } from "../stdlib/regexp.js";
12
- import { stringGlobal } from "../stdlib/string.js";
13
- import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js";
14
- import { headersGlobal } from "../stdlib/headers.js";
15
- import { iteratorGlobals } from "../stdlib/iterator.js";
16
- import { coercion } from "../stdlib/value.js";
17
- import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js";
18
- import { ToolReference } from "../tool-runtime.js";
19
- import { errorGlobal } from "./errors.js";
20
- import { errorTypes } from "./intrinsics.js";
21
- import { constants, constructor, methods, native, receiver } from "./native.js";
22
- import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js";
23
- import { checkArrayLength } from "./limits.js";
24
- import { generatorGlobals } from "./generators.js";
25
- import { promiseGlobal } from "./promises.js";
26
- // Function.prototype.constructor exists so `fn.constructor === Function` holds; dynamic code is unsupported.
27
- const functionGlobal = (ctx) => {
28
- const reject = () => {
29
- throw typeError("The Function constructor is not supported; write the function inline.");
30
- };
31
- const target = (thisValue, method) => receiver(Callable, thisValue, `Function.prototype.${method}`);
32
- methods(ctx.builtins, ctx.builtins.Function, [
33
- ["call", 1, (thisValue, args, site) => ctx.call(target(thisValue, "call"), args[0], args.slice(1), site)],
34
- [
35
- "apply",
36
- 2,
37
- (thisValue, args, site) => ctx.call(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site),
38
- ],
39
- [
40
- "bind",
41
- 1,
42
- (thisValue, args) => {
43
- const fn = target(thisValue, "bind");
44
- const bound = args.slice(1);
45
- return native(ctx.builtins, {
46
- name: `bound ${coerceToString(get(fn, "name"))}`,
47
- length: Math.max(0, fn.length - bound.length),
48
- call: (_, rest, site) => ctx.call(fn, args[0], [...bound, ...rest], site),
49
- });
50
- },
51
- ],
52
- ]);
53
- return constructor(ctx.builtins, ctx.builtins.Function, {
54
- name: "Function",
55
- length: 1,
56
- call: reject,
57
- construct: reject,
58
- });
59
- };
60
- // CreateListFromArrayLike: `apply` reads `length` and the indexed properties of any object.
61
- const listFromArrayLike = (value) => {
62
- if (value === undefined || value === null)
63
- return [];
64
- if (value instanceof Arr)
65
- return [...value.items];
66
- if (!(value instanceof Obj))
67
- throw typeError("Function.prototype.apply expects an array-like argument list.");
68
- const length = Math.max(0, coerceToInteger(get(value, "length")));
69
- checkArrayLength(length);
70
- return Array.from({ length }, (_, index) => get(value, String(index)));
71
- };
72
- const symbolGlobal = (ctx) => {
73
- const symbol = native(ctx.builtins, {
74
- name: "Symbol",
75
- call: () => {
76
- throw typeError("Symbol is not callable; only Symbol.asyncIterator and Symbol.iterator are available.");
77
- },
78
- callback: false,
79
- });
80
- constants(symbol, { asyncIterator: AsyncIteratorSymbol, iterator: IteratorSymbol });
81
- return symbol;
82
- };
83
- // A table rather than a list so the names are known before any runtime exists.
84
- const table = {
85
- tools: () => new ToolReference([]),
86
- search: (ctx) => native(ctx.builtins, { name: "search", call: (_, args) => ctx.search(args), callback: false }),
87
- require: (ctx) => native(ctx.builtins, {
88
- name: "require",
89
- length: 1,
90
- call: (_, args, site) => {
91
- const specifier = args[0];
92
- if (typeof specifier !== "string")
93
- throw typeError("require expects a module name string.");
94
- return ctx.module(specifier, site);
95
- },
96
- }),
97
- undefined: () => undefined,
98
- NaN: () => NaN,
99
- Infinity: () => Infinity,
100
- Object: (ctx) => objectGlobal(ctx),
101
- Function: (ctx) => functionGlobal(ctx),
102
- Array: (ctx) => arrayGlobal(ctx),
103
- Math: (ctx) => mathGlobal(ctx),
104
- JSON: (ctx) => jsonGlobal(ctx),
105
- console: (ctx) => consoleGlobal(ctx),
106
- Promise: (ctx) => promiseGlobal(ctx),
107
- Symbol: (ctx) => symbolGlobal(ctx),
108
- Iterator: (ctx) => iteratorGlobals(ctx),
109
- Number: (ctx) => numberGlobal(ctx),
110
- String: (ctx) => stringGlobal(ctx),
111
- Boolean: (ctx) => booleanGlobal(ctx),
112
- parseInt: (ctx) => coercion(ctx, "parseInt", 2),
113
- parseFloat: (ctx) => coercion(ctx, "parseFloat"),
114
- isFinite: (ctx) => coercion(ctx, "isFinite"),
115
- isNaN: (ctx) => coercion(ctx, "isNaN"),
116
- Date: (ctx) => dateGlobal(ctx),
117
- RegExp: (ctx) => regexpGlobal(ctx),
118
- Map: (ctx) => mapGlobal(ctx),
119
- Set: (ctx) => setGlobal(ctx),
120
- WeakMap: (ctx) => weakMapGlobal(ctx),
121
- WeakSet: (ctx) => weakSetGlobal(ctx),
122
- URL: (ctx) => urlGlobal(ctx),
123
- URLSearchParams: (ctx) => urlSearchParamsGlobal(ctx),
124
- Headers: (ctx) => headersGlobal(ctx),
125
- Uint8Array: (ctx) => uint8ArrayGlobal(ctx),
126
- TextEncoder: (ctx) => textEncoderGlobal(ctx),
127
- TextDecoder: (ctx) => textDecoderGlobal(ctx),
128
- encodeURI: (ctx) => uriGlobal(ctx, "encodeURI"),
129
- encodeURIComponent: (ctx) => uriGlobal(ctx, "encodeURIComponent"),
130
- decodeURI: (ctx) => uriGlobal(ctx, "decodeURI"),
131
- decodeURIComponent: (ctx) => uriGlobal(ctx, "decodeURIComponent"),
132
- atob: (ctx) => base64Global(ctx, "atob"),
133
- btoa: (ctx) => base64Global(ctx, "btoa"),
134
- crypto: (ctx) => cryptoGlobal(ctx),
135
- structuredClone: (ctx) => structuredCloneGlobal(ctx),
136
- ...Object.fromEntries(errorTypes.map((type) => [type, (ctx) => errorGlobal(type, ctx)])),
137
- };
138
- /** Names bound in every program before extensions apply. */
139
- export const globalNames = new Set(Object.keys(table));
140
- /** The immutable global bindings of every program, in declaration order. */
141
- export const globals = (ctx) => {
142
- generatorGlobals(ctx);
143
- return Object.entries(table).map(([name, factory]) => [name, factory(ctx)]);
144
- };
@@ -1,48 +0,0 @@
1
- import type { Program, TaggedTemplateExpression } from "acorn";
2
- import type { Context } from "effect";
3
- import { type Json } from "../data.js";
4
- import { type ToolRuntime } from "../tool-runtime.js";
5
- import { type AstNode } from "./model.js";
6
- import { type Builtins } from "./intrinsics.js";
7
- import { type Cursor, Arr, Obj, type Value } from "./objects.js";
8
- import { type Eval, Runner } from "./runner.js";
9
- /** One program execution: the tool bridge, job queue, captured logs, and the global scope built once. */
10
- export declare class Interpreter<R> {
11
- readonly tools: ToolRuntime<R>;
12
- readonly runner: Runner<R>;
13
- readonly builtins: Builtins;
14
- readonly logs: Array<string>;
15
- /** Template objects by site: a tag sees the same `strings` array every time its literal is evaluated, as in JS. */
16
- readonly templates: WeakMap<TaggedTemplateExpression, Arr>;
17
- private readonly root;
18
- private readonly globalScope;
19
- private readonly modules;
20
- private readonly namespaces;
21
- constructor(options: {
22
- readonly tools: ToolRuntime<R>;
23
- /** The caller's services, which host work runs with. */
24
- readonly services: Context.Context<R>;
25
- readonly builtins: Builtins;
26
- readonly logs?: Array<string>;
27
- readonly globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
28
- });
29
- /** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
30
- module(specifier: string, site?: AstNode): Value;
31
- /**
32
- * What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
33
- * Node presents a CommonJS module.
34
- */
35
- namespace(specifier: string, site?: AstNode): Obj;
36
- /** The program's body, as the first job: its completion value, copied out for the host. */
37
- main(program: Program): Eval<Json | undefined>;
38
- /** Calls into the program; a built-in passes its own call site so failures inside are located there. */
39
- call(callable: Value, thisValue: Value, args: Array<Value>, site?: AstNode): Eval<Value>;
40
- /** Await: suspends the innermost async body until `value` settles. */
41
- awaitValue(value: Value, node?: AstNode): Eval<Value>;
42
- iterate(value: Value): Eval<Cursor | undefined>;
43
- iterateDirect(value: Value): Cursor;
44
- /** Runs one host call to completion before any other job: arguments cross as JSON, the result comes back as values. */
45
- tool(run: ToolRuntime<R>["search"], args: Array<Value>): Generator<import("./runner.js").Signal, Value, import("effect/Schema").Json | undefined>;
46
- /** The built-in search: its result is usable directly, and can also be awaited or chained like a Promise. */
47
- search(args: Array<Value>): Generator<import("./runner.js").Signal, Value, import("effect/Schema").Json | undefined>;
48
- }