@opencode/codemode 0.0.0-dev-513 → 0.0.0-dev-520
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.
- package/README.md +16 -1
- package/dist/codemode.d.ts +1 -1
- package/dist/extension.d.ts +14 -9
- package/dist/extension.js +2 -2
- package/dist/interpreter/execute.d.ts +1 -1
- package/dist/interpreter/execute.js +16 -4
- package/dist/interpreter/extensions.d.ts +3 -3
- package/dist/interpreter/extensions.js +17 -11
- package/dist/interpreter/globals.js +10 -0
- package/dist/interpreter/interpreter.d.ts +11 -1
- package/dist/interpreter/interpreter.js +86 -2
- package/dist/interpreter/modules.d.ts +4 -0
- package/dist/interpreter/modules.js +33 -0
- package/dist/tool-runtime.d.ts +4 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,7 +14,8 @@ The idea of code mode was originally introduced by Cloudflare. See
|
|
|
14
14
|
## How it differs from JavaScript
|
|
15
15
|
|
|
16
16
|
- **Only supported APIs are available.** Programs can use the provided tools, supported JavaScript built-ins, and the
|
|
17
|
-
globals the host adds through extensions. Timers, `process`, filesystem access,
|
|
17
|
+
globals the host adds through extensions. Timers, `process`, filesystem access, packages, and `export` are
|
|
18
|
+
unavailable.
|
|
18
19
|
- **Unfinished work is interrupted.** Tool calls and async functions start when called. When the program finishes,
|
|
19
20
|
anything still running is interrupted. Unhandled rejections from un-awaited promises are returned as warnings.
|
|
20
21
|
- **REPL-style results.** Without an explicit `return`, the final top-level expression becomes the result. `undefined`
|
|
@@ -136,6 +137,20 @@ Every value crossing in either direction is converted, never shared: arguments c
|
|
|
136
137
|
copies, and a function inside a result is callable the same way. A global that shadows a built-in or another
|
|
137
138
|
extension throws at `CodeMode.make`.
|
|
138
139
|
|
|
140
|
+
A global can also be an object of functions, such as `fs`. Every function reachable from it is an entry point like a
|
|
141
|
+
global, so calls fire the `extension` hooks with their path as the name (`fs.readFile`, `fs.promises.readFile`).
|
|
142
|
+
|
|
143
|
+
Programs load globals the way Node code loads modules. `import` and `require` take a global by its Node module name,
|
|
144
|
+
with or without `node:`; `fs/promises`, `url`, `util`, and `buffer` resolve to the globals that provide them. There are
|
|
145
|
+
no packages, so anything else throws.
|
|
146
|
+
|
|
147
|
+
```js
|
|
148
|
+
import fs, { readFile } from "node:fs" // the `fs` global, if the host provides one
|
|
149
|
+
import { URL } from "url"
|
|
150
|
+
const crypto = require("crypto")
|
|
151
|
+
const { default: same } = await import("fs")
|
|
152
|
+
```
|
|
153
|
+
|
|
139
154
|
### OpenAPI tools
|
|
140
155
|
|
|
141
156
|
`OpenAPI.fromSpec` converts an OpenAPI 3.x document into one tool per supported operation. Dotted `operationId` values
|
package/dist/codemode.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export type Options<Provided extends Record<string, unknown> = {}, Extensions ex
|
|
|
34
34
|
tools?: Provided & Tools<Services<Provided>>;
|
|
35
35
|
/** Hooks around every tool and extension call the program makes; see `Hooks`. */
|
|
36
36
|
hooks?: ToolRuntime.Hooks<Environment<Provided, Extensions>>;
|
|
37
|
-
/** Host functions exposed as globals; see `Extension.make`. */
|
|
37
|
+
/** Host functions and objects exposed as globals, also importable by Node module name; see `Extension.make`. */
|
|
38
38
|
extensions?: Extensions;
|
|
39
39
|
/** Resource limits enforced on each execution. */
|
|
40
40
|
limits?: ExecutionLimits;
|
package/dist/extension.d.ts
CHANGED
|
@@ -1,24 +1,29 @@
|
|
|
1
1
|
export * as Extension from "./extension.js";
|
|
2
2
|
import type { Effect } from "effect";
|
|
3
3
|
/**
|
|
4
|
-
* Host
|
|
5
|
-
* shared: arguments come in as copies, results go out as copies, and a
|
|
6
|
-
* same way. Extension calls are not tool calls. A global may return a value,
|
|
7
|
-
* Effect's requirements join the runtime's environment.
|
|
4
|
+
* Host values a program reaches directly as globals: functions, or objects of functions such as `fs`. Values crossing
|
|
5
|
+
* in either direction are converted, never shared: arguments come in as copies, results go out as copies, and a
|
|
6
|
+
* function inside a result is callable the same way. Extension calls are not tool calls. A global may return a value,
|
|
7
|
+
* a Promise, or an Effect, and an Effect's requirements join the runtime's environment.
|
|
8
8
|
*
|
|
9
9
|
* A global is synchronous unless it is an `async` function or is marked with `async`. The `extension.before` hook
|
|
10
10
|
* runs before the call, so a denied call never reaches the host; it fails the way the global would, by rejecting the
|
|
11
|
-
* promise of an asynchronous global and by throwing from a synchronous one.
|
|
11
|
+
* promise of an asynchronous global and by throwing from a synchronous one. Functions inside a global object are
|
|
12
|
+
* called the same way, named by their path (`fs.readFile`).
|
|
13
|
+
*
|
|
14
|
+
* Programs can also `import` or `require` a global by its Node module name; see `interpreter/modules.ts`.
|
|
12
15
|
*/
|
|
13
|
-
export type Extension<Globals extends Readonly<Record<string,
|
|
16
|
+
export type Extension<Globals extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>> = {
|
|
14
17
|
readonly name: string;
|
|
15
18
|
readonly globals: Globals;
|
|
16
19
|
};
|
|
17
|
-
/** The Effect environment required by an extension's Effect-returning
|
|
20
|
+
/** The Effect environment required by an extension's Effect-returning functions, at the top level or one level in. */
|
|
18
21
|
export type Services<E> = E extends {
|
|
19
22
|
readonly globals: infer Globals;
|
|
20
|
-
} ? Globals[keyof Globals]
|
|
21
|
-
|
|
23
|
+
} ? GlobalServices<Globals[keyof Globals]> : never;
|
|
24
|
+
type GlobalServices<Global> = Global extends (...args: never) => unknown ? Requirements<Global> : Global extends object ? Requirements<Global[keyof Global]> : never;
|
|
25
|
+
type Requirements<F> = F extends (...args: never) => infer Result ? Effect.Services<Result> : never;
|
|
26
|
+
export declare const make: <const Globals extends Readonly<Record<string, unknown>>>(options: Extension<Globals>) => Extension<Globals>;
|
|
22
27
|
/** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
|
|
23
28
|
export declare const async: <F extends Function>(global: F) => F;
|
|
24
29
|
export declare const isAsync: (global: Function) => boolean;
|
package/dist/extension.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export * as Extension from "./extension.js";
|
|
2
2
|
export const make = (options) => {
|
|
3
3
|
for (const [name, value] of Object.entries(options.globals)) {
|
|
4
|
-
if (typeof value !== "function") {
|
|
5
|
-
throw new TypeError(`Extension "${options.name}" global "${name}" must be a function.`);
|
|
4
|
+
if (typeof value !== "function" && (typeof value !== "object" || value === null)) {
|
|
5
|
+
throw new TypeError(`Extension "${options.name}" global "${name}" must be a function or an object.`);
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
8
|
return { name: options.name, globals: { ...options.globals } };
|
|
@@ -2,8 +2,8 @@ import { type Program } from "acorn";
|
|
|
2
2
|
import { Effect } from "effect";
|
|
3
3
|
import type { Diagnostic, ResolvedExecutionLimits, Result } from "../codemode.js";
|
|
4
4
|
import { ToolRuntime } from "../tool-runtime.js";
|
|
5
|
-
import type { Value } from "./objects.js";
|
|
6
5
|
import { Interpreter } from "./interpreter.js";
|
|
6
|
+
import type { Value } from "./objects.js";
|
|
7
7
|
export declare const executeProgram: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>) => Effect.Effect<Result, never, R>;
|
|
8
8
|
export declare const parseProgram: (code: string) => {
|
|
9
9
|
ok: true;
|
|
@@ -4,7 +4,7 @@ import { ToolRuntime } from "../tool-runtime.js";
|
|
|
4
4
|
import { normalizeError } from "./errors.js";
|
|
5
5
|
import { createBuiltins } from "./intrinsics.js";
|
|
6
6
|
import { Interpreter } from "./interpreter.js";
|
|
7
|
-
import { formatLocation } from "./model.js";
|
|
7
|
+
import { formatLocation, sourceLocation } from "./model.js";
|
|
8
8
|
export const executeProgram = (code, prepared, limits, hooks, globals) => {
|
|
9
9
|
if (code.trim().length === 0) {
|
|
10
10
|
return Effect.succeed({
|
|
@@ -93,8 +93,22 @@ export const parseProgram = (code) => {
|
|
|
93
93
|
sourceType: "script",
|
|
94
94
|
allowReturnOutsideFunction: true,
|
|
95
95
|
allowAwaitOutsideFunction: true,
|
|
96
|
+
// Imports bind globals by module name; scripts keep sloppy-mode semantics, which module source would make strict.
|
|
97
|
+
allowImportExportEverywhere: true,
|
|
96
98
|
locations: true,
|
|
97
99
|
});
|
|
100
|
+
const exported = program.body.find((statement) => statement.type.startsWith("Export"));
|
|
101
|
+
if (exported) {
|
|
102
|
+
const location = sourceLocation(exported);
|
|
103
|
+
return {
|
|
104
|
+
ok: false,
|
|
105
|
+
error: {
|
|
106
|
+
kind: "ParseError",
|
|
107
|
+
message: `SyntaxError: Exports aren't available. Return the result instead.${formatLocation(location)}`,
|
|
108
|
+
location,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
98
112
|
return { ok: true, program };
|
|
99
113
|
}
|
|
100
114
|
catch (error) {
|
|
@@ -114,9 +128,7 @@ const decodeAcornError = Schema.decodeUnknownOption(AcornError);
|
|
|
114
128
|
const parseDiagnostic = (error) => {
|
|
115
129
|
const location = { line: error.loc.line, column: error.loc.column + 1 };
|
|
116
130
|
const reason = error.message.replace(/ \(\d+:\d+\)$/, "");
|
|
117
|
-
const text = reason
|
|
118
|
-
? "Imports and exports aren't available. Call tools through `tools` and use the built-in globals."
|
|
119
|
-
: `${reason.endsWith(".") ? reason : `${reason}.`} Code must be plain JavaScript written as a program body.`;
|
|
131
|
+
const text = `${reason.endsWith(".") ? reason : `${reason}.`} Code must be plain JavaScript written as a program body.`;
|
|
120
132
|
return { kind: "ParseError", message: `SyntaxError: ${text}${formatLocation(location)}`, location };
|
|
121
133
|
};
|
|
122
134
|
const utf8ByteLength = (value) => new TextEncoder().encode(value).byteLength;
|
|
@@ -2,8 +2,8 @@ import { type Extension } from "../extension.js";
|
|
|
2
2
|
import type { Interpreter } from "./interpreter.js";
|
|
3
3
|
import { type Value } from "./objects.js";
|
|
4
4
|
/**
|
|
5
|
-
* The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and built-in
|
|
6
|
+
* wrappers are copied, a host function becomes a program function whose calls cross the same way, and a host Promise
|
|
7
|
+
* or Effect becomes a program promise.
|
|
8
8
|
*/
|
|
9
9
|
export declare const extensionGlobals: <R>(ctx: Interpreter<R>, extensions: ReadonlyArray<Extension>) => ReadonlyArray<readonly [string, Value]>;
|
|
@@ -9,9 +9,9 @@ import { fn } from "./native.js";
|
|
|
9
9
|
import { define, get, has, hidden, keys, Arr, Bytes, DateObj, ErrorObj, HeadersObj, MapObj, Obj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, coerceToString, } from "./objects.js";
|
|
10
10
|
import { describeValue, isOpaque } from "./references.js";
|
|
11
11
|
/**
|
|
12
|
-
* The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and
|
|
13
|
-
*
|
|
14
|
-
*
|
|
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
15
|
*/
|
|
16
16
|
export const extensionGlobals = (ctx, extensions) => {
|
|
17
17
|
const builtins = ctx.builtins;
|
|
@@ -52,15 +52,16 @@ export const extensionGlobals = (ctx, extensions) => {
|
|
|
52
52
|
seen.delete(value);
|
|
53
53
|
return copied;
|
|
54
54
|
};
|
|
55
|
-
|
|
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) => {
|
|
56
57
|
if (depth > MAX_VALUE_DEPTH)
|
|
57
58
|
throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
|
|
58
59
|
if (isPrimitive(value))
|
|
59
60
|
return value;
|
|
60
61
|
if (typeof value === "function")
|
|
61
|
-
return wrap(value, label);
|
|
62
|
+
return wrap(value, label, extension === undefined ? undefined : (args) => ({ extension, name: label, args }));
|
|
62
63
|
if (value !== null && typeof value === "object") {
|
|
63
|
-
const next = (item, path) => fromHost(item, path, depth + 1, seen);
|
|
64
|
+
const next = (item, path) => fromHost(item, path, depth + 1, seen, extension);
|
|
64
65
|
// Nothing a host value hands back is kept: results are read as primitives or copied. Where the value's own
|
|
65
66
|
// method could hand back host storage or an object (`getTime`, `slice`, `map`), its internal data is read.
|
|
66
67
|
if (value instanceof Date)
|
|
@@ -145,10 +146,10 @@ export const extensionGlobals = (ctx, extensions) => {
|
|
|
145
146
|
}
|
|
146
147
|
throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
|
|
147
148
|
};
|
|
148
|
-
// A host function as a program function. Arguments cross in; for a global
|
|
149
|
-
// the host function is called, so a call it denies never reaches the host. The
|
|
150
|
-
// crosses out so the program catches a copy, and `extension.after` sees how the
|
|
151
|
-
// results are part of a value's API and skip the hooks.
|
|
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.
|
|
152
153
|
const wrap = (value, label, describe) => {
|
|
153
154
|
// The host function's own `name` and `length` can be anything, even getters: each is read once, and only text
|
|
154
155
|
// and a count cross.
|
|
@@ -180,7 +181,12 @@ export const extensionGlobals = (ctx, extensions) => {
|
|
|
180
181
|
ctx.runner.host(work, (settled) => (settled.ok ? resolving.resolve(settled.value) : resolving.reject(settled.error)), site);
|
|
181
182
|
return promise;
|
|
182
183
|
};
|
|
183
|
-
return extensions.flatMap((extension) => Object.entries(extension.globals).map(([name, value]) => [
|
|
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
|
+
]));
|
|
184
190
|
};
|
|
185
191
|
/**
|
|
186
192
|
* Calls a host function and describes what the program waits on. A returned Effect or Promise settles later; a
|
|
@@ -84,6 +84,16 @@ const symbolGlobal = (ctx) => {
|
|
|
84
84
|
const table = {
|
|
85
85
|
tools: () => new ToolReference([]),
|
|
86
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
|
+
}),
|
|
87
97
|
undefined: () => undefined,
|
|
88
98
|
NaN: () => NaN,
|
|
89
99
|
Infinity: () => Infinity,
|
|
@@ -4,7 +4,7 @@ import { type Json } from "../data.js";
|
|
|
4
4
|
import { type ToolRuntime } from "../tool-runtime.js";
|
|
5
5
|
import { type AstNode } from "./model.js";
|
|
6
6
|
import { type Builtins } from "./intrinsics.js";
|
|
7
|
-
import { type Cursor, Arr, type Value } from "./objects.js";
|
|
7
|
+
import { type Cursor, Arr, Obj, type Value } from "./objects.js";
|
|
8
8
|
import { type Eval, Runner } from "./runner.js";
|
|
9
9
|
/** One program execution: the tool bridge, job queue, captured logs, and the global scope built once. */
|
|
10
10
|
export declare class Interpreter<R> {
|
|
@@ -15,6 +15,9 @@ export declare class Interpreter<R> {
|
|
|
15
15
|
/** Template objects by site: a tag sees the same `strings` array every time its literal is evaluated, as in JS. */
|
|
16
16
|
readonly templates: WeakMap<TaggedTemplateExpression, Arr>;
|
|
17
17
|
private readonly root;
|
|
18
|
+
private readonly globalScope;
|
|
19
|
+
private readonly modules;
|
|
20
|
+
private readonly namespaces;
|
|
18
21
|
constructor(options: {
|
|
19
22
|
readonly tools: ToolRuntime<R>;
|
|
20
23
|
/** The caller's services, which host work runs with. */
|
|
@@ -23,6 +26,13 @@ export declare class Interpreter<R> {
|
|
|
23
26
|
readonly logs?: Array<string>;
|
|
24
27
|
readonly globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
|
|
25
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;
|
|
26
36
|
/** The program's body, as the first job: its completion value, copied out for the host. */
|
|
27
37
|
main(program: Program): Eval<Json | undefined>;
|
|
28
38
|
/** Calls into the program; a built-in passes its own call site so failures inside are located there. */
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { fromJson, toBoundary } from "../data.js";
|
|
2
2
|
import { ToolReference } from "../tool-runtime.js";
|
|
3
|
-
import { AsyncIteratorSymbol, GeneratorReturn, IteratorSymbol, OptionalShortCircuit, invalidData, Throw, rangeError, typeError, unsupportedSyntax, } from "./model.js";
|
|
3
|
+
import { AsyncIteratorSymbol, GeneratorReturn, IteratorSymbol, OptionalShortCircuit, invalidData, PendingThrow, syntaxError, Throw, rangeError, typeError, unsupportedSyntax, } from "./model.js";
|
|
4
4
|
import { checkStringLength } from "./limits.js";
|
|
5
5
|
import { locate, materialize } from "./errors.js";
|
|
6
6
|
import { primitivePrototype } from "./intrinsics.js";
|
|
7
7
|
import { globals } from "./globals.js";
|
|
8
|
-
import { assign, Callable, define, frozen, get, hostCursor, IteratorObj, has, hasOwn, hidden, hasPrototype, keys, Native, parseArrayIndex, Arguments, Arr, Fn, GeneratorObj, Obj, PromiseObj, iteratorResult, remove, set, coerceToNumber, coerceToString, } from "./objects.js";
|
|
8
|
+
import { assign, Callable, define, frozen, get, hostCursor, IteratorObj, has, hasOwn, hidden, hasPrototype, keys, Native, parseArrayIndex, Arguments, Arr, Fn, GeneratorObj, Obj, PromiseObj, iteratorResult, remove, set, coerceToNumber, coerceToString, entries, getOwn, } from "./objects.js";
|
|
9
9
|
import { preserveConsumerError, toPrimitive } from "./callback.js";
|
|
10
10
|
import { AsyncBoundary, Await, Call, Interruption, isEval, MAX_CALL_DEPTH, Runner, Slice, Task, Yield, normal, } from "./runner.js";
|
|
11
|
+
import { moduleName, resolveModule } from "./modules.js";
|
|
11
12
|
import { describeValue, isOpaque, rejectCircularInsertion, typeofValue } from "./references.js";
|
|
12
13
|
import { fn } from "./native.js";
|
|
13
14
|
import { capability, promiseLike } from "./promises.js";
|
|
@@ -252,6 +253,9 @@ export class Interpreter {
|
|
|
252
253
|
/** Template objects by site: a tag sees the same `strings` array every time its literal is evaluated, as in JS. */
|
|
253
254
|
templates = new WeakMap();
|
|
254
255
|
root;
|
|
256
|
+
globalScope;
|
|
257
|
+
modules = new Map();
|
|
258
|
+
namespaces = new Map();
|
|
255
259
|
constructor(options) {
|
|
256
260
|
this.tools = options.tools;
|
|
257
261
|
this.builtins = options.builtins;
|
|
@@ -261,10 +265,44 @@ export class Interpreter {
|
|
|
261
265
|
const globalScope = new Map([["this", { mutable: false, value: undefined }]]);
|
|
262
266
|
// Calling back into the program never reads frame state, so any frame serves; the root is always alive.
|
|
263
267
|
this.root = new Frame(this, new ScopeStack([globalScope]));
|
|
268
|
+
this.globalScope = globalScope;
|
|
264
269
|
for (const [name, value] of [...globals(this), ...(options.globals?.(this) ?? [])]) {
|
|
265
270
|
globalScope.set(name, { mutable: false, value });
|
|
266
271
|
}
|
|
267
272
|
}
|
|
273
|
+
/** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */
|
|
274
|
+
module(specifier, site) {
|
|
275
|
+
const name = moduleName(specifier);
|
|
276
|
+
const cached = this.modules.get(name);
|
|
277
|
+
if (cached !== undefined)
|
|
278
|
+
return cached;
|
|
279
|
+
const module = resolveModule(name, (global) => {
|
|
280
|
+
const binding = this.globalScope.get(global);
|
|
281
|
+
return binding && "value" in binding ? binding.value : undefined;
|
|
282
|
+
});
|
|
283
|
+
if (module === undefined)
|
|
284
|
+
throw new PendingThrow("Error", `Cannot import "${specifier}": it isn't available in Code Mode, which can't load packages or files. Use the provided globals, or call tools through \`tools\`.`, site);
|
|
285
|
+
this.modules.set(name, module);
|
|
286
|
+
return module;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way
|
|
290
|
+
* Node presents a CommonJS module.
|
|
291
|
+
*/
|
|
292
|
+
namespace(specifier, site) {
|
|
293
|
+
const module = this.module(specifier, site);
|
|
294
|
+
const name = moduleName(specifier);
|
|
295
|
+
const cached = this.namespaces.get(name);
|
|
296
|
+
if (cached)
|
|
297
|
+
return cached;
|
|
298
|
+
const namespace = new Obj(null);
|
|
299
|
+
if (module instanceof Obj)
|
|
300
|
+
for (const [key, value] of entries(module))
|
|
301
|
+
define(namespace, key, value);
|
|
302
|
+
define(namespace, "default", module);
|
|
303
|
+
this.namespaces.set(name, namespace);
|
|
304
|
+
return namespace;
|
|
305
|
+
}
|
|
268
306
|
/** The program's body, as the first job: its completion value, copied out for the host. */
|
|
269
307
|
*main(program) {
|
|
270
308
|
return yield* toBoundary(this, yield* this.root.run(program));
|
|
@@ -310,11 +348,17 @@ class Frame {
|
|
|
310
348
|
// Keep top-level declarations separate so they can shadow builtins.
|
|
311
349
|
this.scopes.push();
|
|
312
350
|
try {
|
|
351
|
+
// Imports load before any code runs, as in a module.
|
|
352
|
+
for (const statement of program.body)
|
|
353
|
+
if (statement.type === "ImportDeclaration")
|
|
354
|
+
this.bindImport(statement);
|
|
313
355
|
this.predeclareLexical(program.body);
|
|
314
356
|
this.hoistFunctions(program.body);
|
|
315
357
|
this.hoistVars(program.body);
|
|
316
358
|
let value = undefined;
|
|
317
359
|
for (const [index, statement] of program.body.entries()) {
|
|
360
|
+
if (statement.type === "ImportDeclaration")
|
|
361
|
+
continue;
|
|
318
362
|
if (index === program.body.length - 1 && statement.type === "ExpressionStatement") {
|
|
319
363
|
value = yield* this.evaluateExpression(statement.expression);
|
|
320
364
|
break;
|
|
@@ -335,6 +379,26 @@ class Frame {
|
|
|
335
379
|
this.scopes.pop();
|
|
336
380
|
}
|
|
337
381
|
}
|
|
382
|
+
bindImport(node) {
|
|
383
|
+
const specifier = String(node.source.value);
|
|
384
|
+
if (node.specifiers.length === 0)
|
|
385
|
+
this.ctx.module(specifier, node);
|
|
386
|
+
for (const binding of node.specifiers) {
|
|
387
|
+
this.scopes.declare(binding.local.name, this.imported(binding, specifier), false, binding);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
// A default import binds the module itself and a named import one of its properties, as Node imports CommonJS.
|
|
391
|
+
imported(binding, specifier) {
|
|
392
|
+
if (binding.type === "ImportDefaultSpecifier")
|
|
393
|
+
return this.ctx.module(specifier, binding);
|
|
394
|
+
const namespace = this.ctx.namespace(specifier, binding);
|
|
395
|
+
if (binding.type === "ImportNamespaceSpecifier")
|
|
396
|
+
return namespace;
|
|
397
|
+
const name = binding.imported.type === "Identifier" ? binding.imported.name : String(binding.imported.value);
|
|
398
|
+
if (!hasOwn(namespace, name))
|
|
399
|
+
throw syntaxError(`"${specifier}" has no export named "${name}".`, binding);
|
|
400
|
+
return getOwn(namespace, name);
|
|
401
|
+
}
|
|
338
402
|
// The call returns its promise at once. Arguments cross on the caller's stack, since `toJSON` is program code, and a
|
|
339
403
|
// promise argument is awaited first; the host call starts once they have crossed, so admission and hooks happen at
|
|
340
404
|
// the call site, and runs concurrently with the program.
|
|
@@ -404,6 +468,8 @@ class Frame {
|
|
|
404
468
|
return none;
|
|
405
469
|
case "FunctionDeclaration":
|
|
406
470
|
return none;
|
|
471
|
+
case "ImportDeclaration":
|
|
472
|
+
throw syntaxError("An import declaration may only appear at the top level of the program.", node);
|
|
407
473
|
default:
|
|
408
474
|
throw unsupportedSyntax(node.type, node);
|
|
409
475
|
}
|
|
@@ -1311,6 +1377,8 @@ class Frame {
|
|
|
1311
1377
|
return this.evaluateYieldExpression(node);
|
|
1312
1378
|
case "NewExpression":
|
|
1313
1379
|
return this.evaluateNewExpression(node);
|
|
1380
|
+
case "ImportExpression":
|
|
1381
|
+
return this.evaluateImportExpression(node);
|
|
1314
1382
|
default:
|
|
1315
1383
|
throw unsupportedSyntax(node.type, node);
|
|
1316
1384
|
}
|
|
@@ -1625,6 +1693,22 @@ class Frame {
|
|
|
1625
1693
|
}
|
|
1626
1694
|
throw typeError("Update target must be an Identifier or MemberExpression.", argument);
|
|
1627
1695
|
}
|
|
1696
|
+
// A module that fails to load rejects the promise, as a failed dynamic import does.
|
|
1697
|
+
*evaluateImportExpression(node) {
|
|
1698
|
+
const specifier = coerceToString(yield* this.evaluateExpression(node.source));
|
|
1699
|
+
if (node.options)
|
|
1700
|
+
yield* this.evaluateExpression(node.options);
|
|
1701
|
+
const promise = capability(this.ctx, node);
|
|
1702
|
+
try {
|
|
1703
|
+
promise.resolve(this.ctx.namespace(specifier, node));
|
|
1704
|
+
}
|
|
1705
|
+
catch (error) {
|
|
1706
|
+
if (!(error instanceof PendingThrow))
|
|
1707
|
+
throw error;
|
|
1708
|
+
promise.reject(error);
|
|
1709
|
+
}
|
|
1710
|
+
return promise.promise;
|
|
1711
|
+
}
|
|
1628
1712
|
// EvaluateCall: a member callee supplies its base object as `this`; anything else calls with undefined.
|
|
1629
1713
|
*evaluateCallExpression(node) {
|
|
1630
1714
|
const callee = node.callee;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { define, get, Obj } from "./objects.js";
|
|
2
|
+
/**
|
|
3
|
+
* What `import` and `require` load: a global, by the Node module name that provides it. `fs` loads the `fs` global
|
|
4
|
+
* and `crypto` the `crypto` global; the names below come from globals with different names. A module that would be
|
|
5
|
+
* empty isn't available.
|
|
6
|
+
*/
|
|
7
|
+
const aliases = {
|
|
8
|
+
"fs/promises": (global) => {
|
|
9
|
+
const fs = global("fs");
|
|
10
|
+
return fs instanceof Obj ? get(fs, "promises") : undefined;
|
|
11
|
+
},
|
|
12
|
+
url: (global) => pick(global, ["URL", "URLSearchParams"]),
|
|
13
|
+
util: (global) => pick(global, ["TextEncoder", "TextDecoder"]),
|
|
14
|
+
buffer: (global) => pick(global, ["Buffer", "atob", "btoa"]),
|
|
15
|
+
};
|
|
16
|
+
/** `node:fs` names the same module as `fs`. */
|
|
17
|
+
export const moduleName = (specifier) => (specifier.startsWith("node:") ? specifier.slice(5) : specifier);
|
|
18
|
+
export const resolveModule = (specifier, global) => {
|
|
19
|
+
const name = moduleName(specifier);
|
|
20
|
+
return global(name) ?? aliases[name]?.(global);
|
|
21
|
+
};
|
|
22
|
+
function pick(global, names) {
|
|
23
|
+
const found = names.flatMap((name) => {
|
|
24
|
+
const value = global(name);
|
|
25
|
+
return value === undefined ? [] : [[name, value]];
|
|
26
|
+
});
|
|
27
|
+
if (found.length === 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
const module = new Obj(null);
|
|
30
|
+
for (const [name, value] of found)
|
|
31
|
+
define(module, name, value);
|
|
32
|
+
return module;
|
|
33
|
+
}
|
package/dist/tool-runtime.d.ts
CHANGED
|
@@ -18,7 +18,10 @@ export type ToolInvocation = {
|
|
|
18
18
|
readonly name: string;
|
|
19
19
|
readonly input: unknown;
|
|
20
20
|
};
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* A call the program is making to an extension global or module function, with its arguments. A module function is
|
|
23
|
+
* named by its path from the module, such as `fs.readFile`.
|
|
24
|
+
*/
|
|
22
25
|
export type ExtensionInvocation = {
|
|
23
26
|
readonly extension: string;
|
|
24
27
|
readonly name: string;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@opencode/codemode",
|
|
4
|
-
"version": "0.0.0-dev-
|
|
4
|
+
"version": "0.0.0-dev-520",
|
|
5
5
|
"description": "Effect-native confined code execution over schema-described tools",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"license": "MIT",
|