@deepseek-ai/dsh-ptc-runtime-node 0.2.2-rc.5 → 0.2.3-alpha.1

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 (71) hide show
  1. package/README.i18n.yaml +24 -24
  2. package/README.md +49 -17
  3. package/README.zh.md +49 -17
  4. package/lib/configuration.js +15 -5
  5. package/lib/index.js +439 -148
  6. package/lib/persistent-process.js +683 -90
  7. package/lib/process.js +683 -90
  8. package/lib/types/bindings.d.ts +10 -5
  9. package/lib/types/bindings.d.ts.map +1 -1
  10. package/lib/types/bindings.js.map +1 -1
  11. package/lib/types/bootstrap.d.ts +42 -24
  12. package/lib/types/bootstrap.d.ts.map +1 -1
  13. package/lib/types/bootstrap.js.map +1 -1
  14. package/lib/types/config.d.ts +14 -2
  15. package/lib/types/config.d.ts.map +1 -1
  16. package/lib/types/config.js.map +1 -1
  17. package/lib/types/configuration.d.ts +5 -4
  18. package/lib/types/configuration.d.ts.map +1 -1
  19. package/lib/types/configuration.js.map +1 -1
  20. package/lib/types/environment.d.ts +13 -0
  21. package/lib/types/environment.d.ts.map +1 -1
  22. package/lib/types/environment.js.map +1 -1
  23. package/lib/types/evaluators/index.d.ts.map +1 -1
  24. package/lib/types/evaluators/index.js.map +1 -1
  25. package/lib/types/evaluators/scoped-repl-evaluator.d.ts +22 -0
  26. package/lib/types/evaluators/scoped-repl-evaluator.d.ts.map +1 -0
  27. package/lib/types/evaluators/scoped-repl-evaluator.js.map +1 -0
  28. package/lib/types/evaluators/scoped-repl.d.ts +130 -0
  29. package/lib/types/evaluators/scoped-repl.d.ts.map +1 -0
  30. package/lib/types/evaluators/scoped-repl.js.map +1 -0
  31. package/lib/types/evaluators/types.d.ts +3 -3
  32. package/lib/types/evaluators/types.d.ts.map +1 -1
  33. package/lib/types/evaluators/types.js.map +1 -1
  34. package/lib/types/execution.d.ts +3 -2
  35. package/lib/types/execution.d.ts.map +1 -1
  36. package/lib/types/execution.js.map +1 -1
  37. package/lib/types/index.d.ts +6 -1
  38. package/lib/types/index.d.ts.map +1 -1
  39. package/lib/types/index.js.map +1 -1
  40. package/lib/types/json-wire.d.ts +16 -4
  41. package/lib/types/json-wire.d.ts.map +1 -1
  42. package/lib/types/json-wire.js.map +1 -1
  43. package/lib/types/output-ledger.d.ts +10 -10
  44. package/lib/types/output-ledger.d.ts.map +1 -1
  45. package/lib/types/output-ledger.js.map +1 -1
  46. package/lib/types/process.d.ts +2 -0
  47. package/lib/types/process.d.ts.map +1 -1
  48. package/lib/types/process.js.map +1 -1
  49. package/lib/types/protocol.d.ts +31 -5
  50. package/lib/types/protocol.d.ts.map +1 -1
  51. package/lib/types/protocol.js.map +1 -1
  52. package/lib/types/worker.d.ts +6 -3
  53. package/lib/types/worker.d.ts.map +1 -1
  54. package/lib/types/worker.js.map +1 -1
  55. package/package.json +23 -21
  56. package/src/bindings.ts +33 -26
  57. package/src/bootstrap.ts +159 -57
  58. package/src/config.ts +21 -3
  59. package/src/configuration.ts +13 -6
  60. package/src/environment.ts +39 -0
  61. package/src/evaluators/index.ts +2 -0
  62. package/src/evaluators/scoped-repl-evaluator.ts +110 -0
  63. package/src/evaluators/scoped-repl.ts +339 -0
  64. package/src/evaluators/types.ts +3 -3
  65. package/src/execution.ts +37 -17
  66. package/src/index.ts +58 -13
  67. package/src/json-wire.ts +44 -8
  68. package/src/output-ledger.ts +42 -45
  69. package/src/process.ts +89 -18
  70. package/src/protocol.ts +37 -10
  71. package/src/worker.ts +75 -40
@@ -3,16 +3,23 @@ import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
3
3
  import type { Config } from './config.ts'
4
4
  import { assertNever } from '@deepseek-ai/dsh-util-values'
5
5
 
6
+ /** `replScoped` written for retained function bodies and REPL statements; the Node provider also uses it when `replScoped` is omitted. */
7
+ const SCOPED_REPL_BY_DEFAULT: boolean = true
8
+
6
9
  /**
7
- * Select retained Node execution while preserving Script syntax.
8
- * @param programFormat - Effective syntax; omission uses the Node provider's default function-body syntax.
9
- * @returns Both execution settings to merge into the profile atomically; function bodies switch to the retained REPL.
10
+ * Select retained Node execution while preserving Script and scoped REPL syntax.
11
+ * @param programFormat - Effective syntax; omission selects function bodies.
12
+ * @returns All three settings to merge into the profile atomically, replacing stale values; function bodies and REPL statements
13
+ * switch to `persistent-in-memory` with `SCOPED_REPL_BY_DEFAULT`, which is also the default when `replScoped` is omitted.
10
14
  */
11
- export function resolvePersistentExecution(programFormat: PtcProgramFormat = 'function-body'): Pick<Required<Config>, 'executionMode' | 'scriptPersistence'> {
15
+ export function resolvePersistentExecution(
16
+ programFormat: PtcProgramFormat = 'function-body',
17
+ ): Pick<Required<Config>, 'executionMode' | 'scriptPersistence' | 'replScoped'> {
12
18
  switch (programFormat) {
13
- case 'script': return { executionMode: 'vm-script', scriptPersistence: true }
19
+ case 'script': return { executionMode: 'vm-script', scriptPersistence: true, replScoped: false }
14
20
  case 'function-body':
15
- case 'repl': return { executionMode: 'persistent-in-memory', scriptPersistence: false }
21
+ case 'repl': return { executionMode: 'persistent-in-memory', scriptPersistence: false, replScoped: SCOPED_REPL_BY_DEFAULT }
22
+ case 'scoped-repl': return { executionMode: 'persistent-in-memory', scriptPersistence: false, replScoped: true }
16
23
  /* v8 ignore next -- The runtime supplies the closed, typed program-format union. */
17
24
  default: return assertNever(programFormat)
18
25
  }
@@ -4,6 +4,45 @@ import { syncBuiltinESMExports } from 'node:module'
4
4
  /** Native executable search, Windows system paths, and sandbox temporary paths retained in the OS environment. */
5
5
  export const STARTUP_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set(['PATH', 'PATHEXT', 'SYSTEMROOT', 'WINDIR', 'TEMP', 'TMP'])
6
6
 
7
+ /** Warnings that the runtime's own use of experimental Node features emits once per process. */
8
+ const RUNTIME_WARNINGS = new Set([
9
+ 'vm.USE_MAIN_CONTEXT_DEFAULT_LOADER is an experimental feature and might change at any time',
10
+ 'stripTypeScriptTypes is an experimental feature and might change at any time',
11
+ ])
12
+
13
+ function withoutRuntimeWarning(emitWarning: typeof process.emitWarning): typeof process.emitWarning {
14
+ return function (this: unknown, warning: string | Error, ...rest: unknown[]): void {
15
+ const message = typeof warning === 'string' ? warning : warning instanceof Error ? warning.message : undefined
16
+ if (message !== undefined && RUNTIME_WARNINGS.has(message)) return
17
+ Reflect.apply(emitWarning, this, [warning, ...rest])
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Drop warnings that the runtime itself triggers in the child, which would otherwise appear in program output; other warnings still print.
23
+ * @param state - Child process whose `emitWarning` is wrapped; structural test doubles without it stay unchanged.
24
+ */
25
+ export function filterRuntimeWarnings(state: { emitWarning?: typeof process.emitWarning }): void {
26
+ if (state.emitWarning !== undefined) state.emitWarning = withoutRuntimeWarning(state.emitWarning)
27
+ }
28
+
29
+ /**
30
+ * Run a synchronous host call without printing the runtime's own experimental-feature warnings.
31
+ * @param call - Synchronous work, such as type stripping, that may emit such a warning on first use.
32
+ * @returns The call's result; `process.emitWarning` is restored before returning or rethrowing.
33
+ */
34
+ export function quietRuntimeCall<T>(call: () => T): T {
35
+ // oxlint-disable-next-line typescript/unbound-method -- The original method is restored unchanged after the call.
36
+ const emitWarning = process.emitWarning
37
+ // The replacement exists only during this synchronous call, so no other code observes it.
38
+ process.emitWarning = withoutRuntimeWarning(emitWarning)
39
+ try {
40
+ return call()
41
+ } finally {
42
+ process.emitWarning = emitWarning
43
+ }
44
+ }
45
+
7
46
  /**
8
47
  * Clear inherited credentials while preserving native child-process startup paths.
9
48
  * With the native child process, preloaded node:process exports observe the replacement.
@@ -2,6 +2,7 @@
2
2
  import type { PtcProgramFormat } from '@deepseek-ai/dsh-ptc-runtime'
3
3
  import { createAsyncFunctionEvaluator } from './async-function.ts'
4
4
  import { createReplEvaluator } from './repl.ts'
5
+ import { createScopedReplEvaluator } from './scoped-repl-evaluator.ts'
5
6
  import { createVmScriptEvaluator } from './vm-script.ts'
6
7
  import type { ProgramEvaluator, ProgramEvaluatorOptions, ProgramImportHandler } from './types.ts'
7
8
 
@@ -9,6 +10,7 @@ const evaluators: Record<PtcProgramFormat, (options: ProgramEvaluatorOptions) =>
9
10
  'function-body': createAsyncFunctionEvaluator,
10
11
  repl: createReplEvaluator,
11
12
  script: createVmScriptEvaluator,
13
+ 'scoped-repl': createScopedReplEvaluator,
12
14
  }
13
15
 
14
16
  /**
@@ -0,0 +1,110 @@
1
+ /** Scoped REPL evaluation for the child loop: context, dynamic imports, completion, and REPL-style asynchronous failures. */
2
+ import { resolve } from 'node:path'
3
+ import { inspect, types } from 'node:util'
4
+ import { constants, createContext, Script } from 'node:vm'
5
+ import { VmModuleImportLoader } from '../imports/vm-modules.ts'
6
+ import { ScopedReplScopes, type ScopedReplProgram, type ScopedReplRedeclaration } from './scoped-repl.ts'
7
+ import type { ProgramEvaluator, ProgramEvaluatorOptions } from './types.ts'
8
+
9
+ /** Environment choices for one scoped REPL evaluator; omitted fields use the documented defaults. */
10
+ export interface ScopedReplEvaluatorOptions extends ProgramEvaluatorOptions {
11
+ /** Force strict mode for every program; when off, a program's own leading "use strict" decides. Defaults to true. */
12
+ strict?: boolean
13
+ /** Allow eval, new Function and WebAssembly compilation inside the program context; defaults to false. */
14
+ codeGeneration?: boolean
15
+ /** Use the last top-level expression statement as the completion value; defaults to true. */
16
+ finalExpression?: boolean
17
+ }
18
+
19
+ /**
20
+ * Create an evaluator whose programs see copies of earlier top-level bindings and may declare any of them again.
21
+ * Each program is a separate Script in one retained context; the scope chain lives in {@link ScopedReplScopes}.
22
+ * Programs load modules only with dynamic `import()`; there is no `require`, `module`, or built-in module global.
23
+ * Relative specifiers resolve from the working directory at creation, also after later calls change directory.
24
+ * A final Promise is returned without being awaited. Asynchronous program failures go to `reportError` through a domain,
25
+ * as in Node's REPL, instead of terminating the process.
26
+ * @param options - Runner diagnostics, optional import handling, and environment choices.
27
+ * @returns Context globals, sequential evaluation, and resource cleanup.
28
+ */
29
+ export function createScopedReplEvaluator(options: ScopedReplEvaluatorOptions): ProgramEvaluator {
30
+ const finalExpression = options.finalExpression ?? true
31
+ // Generated filenames are import referrers; relative file access in programs still follows process.cwd().
32
+ const baseDirectory = process.cwd()
33
+ // A null prototype keeps global lookups from reaching the main realm's Function. Copied main-realm values still expose it
34
+ // (setTimeout.constructor), so codeGeneration limits only this context's own eval, Function and WebAssembly; it is not isolation.
35
+ const sandbox = Object.create(null) as Record<string, unknown>
36
+ const context = createContext(sandbox, options.codeGeneration === true ? {} : { codeGeneration: { strings: false, wasm: false } })
37
+ const realm = new Script('globalThis').runInContext(context) as object
38
+ for (const key of Reflect.ownKeys(globalThis)) {
39
+ if (key !== 'global' && !Object.hasOwn(realm, key)) Object.defineProperty(sandbox, key, Object.getOwnPropertyDescriptor(globalThis, key) as PropertyDescriptor)
40
+ }
41
+ sandbox.global = realm
42
+ const imports = options.importHandler === undefined ? undefined : new VmModuleImportLoader(options.importHandler, context)
43
+ // Loaded on use: bundles that never run scoped REPL programs, such as the browser worker image, carry no domain module.
44
+ const programDomain = process.getBuiltinModule('node:domain').create()
45
+ programDomain.on('error', (error: unknown) => { options.reportError(`Uncaught ${describeThrown(error)}`) })
46
+ const scopes = new ScopedReplScopes({ strict: options.strict ?? true, onRedeclaration: reportRedeclarations })
47
+ let submissions = 0
48
+ let closed = false
49
+ return {
50
+ globals: sandbox,
51
+ evaluate(code, finish) {
52
+ if (closed) throw new Error('PTC evaluator is closed')
53
+ // No file exists at this hidden path; its directory anchors relative imports.
54
+ const filename = resolve(baseDirectory, `.ptc-repl-${++submissions}.js`)
55
+ let program: ScopedReplProgram
56
+ try {
57
+ program = scopes.compile(code, {
58
+ filename, context, finalExpression,
59
+ importModuleDynamically: imports?.forFile(filename) ?? constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
60
+ })
61
+ } catch (error: unknown) {
62
+ finish({ ok: false, error })
63
+ return
64
+ }
65
+ // The bound Reflect.apply lets the microtask call the program itself, so synchronous throws carry no evaluator frames.
66
+ const start = Reflect.apply.bind(undefined, program, undefined, []) as ScopedReplProgram
67
+ void programDomain.run(() => Promise.resolve().then(start)).then(
68
+ (completion) => { finish({ ok: true, value: completion?.value }) },
69
+ (error: unknown) => { finish({ ok: false, error }) },
70
+ )
71
+ },
72
+ close() {
73
+ closed = true
74
+ imports?.close()
75
+ },
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Describe a value thrown by asynchronous program work without ever throwing.
81
+ * A throw escaping the domain error listener would end the process, and programs control the values they throw.
82
+ * @param error - Value the program threw or rejected with.
83
+ * @returns The error's string stack or `name: message`, the inspected value without domain markers, or a fixed description.
84
+ */
85
+ function describeThrown(error: unknown): string {
86
+ try {
87
+ if (types.isNativeError(error)) {
88
+ // Programs can replace stack with any value; only a string stack is shown.
89
+ const stack: unknown = error.stack
90
+ return typeof stack === 'string' ? stack : `${error.name}: ${error.message}`
91
+ }
92
+ // The domain marks thrown objects; node:repl removes these markers before printing them.
93
+ if (typeof error === 'object' && error !== null && Reflect.get(error, 'domainThrown') === true) {
94
+ Reflect.deleteProperty(error, 'domain')
95
+ Reflect.deleteProperty(error, 'domainThrown')
96
+ }
97
+ return inspect(error)
98
+ } catch (_failure: unknown) {
99
+ // The program can make its stack accessor, toString, or custom inspection throw.
100
+ return 'program threw an unrenderable value'
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Report names declared again after an earlier program bound them.
106
+ * @param _redeclarations - Each redeclared name with its earlier and current keyword.
107
+ */
108
+ function reportRedeclarations(_redeclarations: readonly ScopedReplRedeclaration[]): void {
109
+ // TODO: Write redeclaration warnings to the program console once their wording is decided.
110
+ }
@@ -0,0 +1,339 @@
1
+ /** Scope chain for scoped REPL programs: acorn scanning, copied bindings between programs, and Script compilation. */
2
+ import { getLineInfo, parse } from 'acorn'
3
+ import type { Identifier, ModuleDeclaration, Pattern, Program, Statement } from 'acorn'
4
+ import { Script, type Context, type ScriptOptions } from 'node:vm'
5
+
6
+ /** Declaration keyword recorded for a top-level binding; later programs copy `var` bindings as `var` and every other binding as `let`. */
7
+ export type ScopedReplBindingKind = 'var' | 'let' | 'const' | 'function' | 'class'
8
+
9
+ /** One top-level binding passed from earlier programs to later ones. */
10
+ export interface ScopedReplBinding {
11
+ /** Binding identifier. */
12
+ name: string
13
+ /** Keyword of the declaration that created the binding. */
14
+ kind: ScopedReplBindingKind
15
+ }
16
+
17
+ /** Source offsets of the last top-level expression statement. */
18
+ export interface ScopedReplFinalExpression {
19
+ /** Offset where the statement begins, including a leading parenthesis. */
20
+ statementStart: number
21
+ /** Offset where the expression begins. */
22
+ expressionStart: number
23
+ /** Offset where the expression ends, before a trailing parenthesis or semicolon. */
24
+ expressionEnd: number
25
+ }
26
+
27
+ /** Own declarations and completion position found by one scan. */
28
+ export interface ScopedReplScan {
29
+ /** Top-level bindings declared by the program, in source order. */
30
+ declarations: ReadonlyMap<string, ScopedReplBindingKind>
31
+ /** Whether the program's leading directives include "use strict". */
32
+ useStrict: boolean
33
+ /** Last top-level statement when it is an expression statement. */
34
+ finalExpression?: ScopedReplFinalExpression
35
+ }
36
+
37
+ /** Prefix of every generated name; programs that contain it anywhere are rejected. */
38
+ export const RESERVED_PREFIX = '__$binding_'
39
+ /** Generated parameter receiving the values copied from earlier programs. */
40
+ export const BINDING_VALUES = `${RESERVED_PREFIX}vals`
41
+ /** Generated parameter receiving one read function per binding, in binding order. */
42
+ export const BINDING_GETTERS = `${RESERVED_PREFIX}getters`
43
+
44
+ /**
45
+ * Parse a program once and list its own top-level bindings, leading strict directive, and final expression.
46
+ * Every program uses script rules with top-level await: strictness comes from the generated Script or the program's directive,
47
+ * and V8 reports strict-mode violations when compiling. Script rules reject top-level `using` and static `import`.
48
+ * Top-level declarations are read, and so are var declarations inside blocks and other statements, which hoist to the program's scope;
49
+ * declarations inside nested functions and classes are not read.
50
+ * @param code - Type-stripped JavaScript submitted for one evaluation.
51
+ * @param options - Filename shown by syntax errors.
52
+ * @returns Declarations in source order, whether a "use strict" directive leads, and the final expression offsets.
53
+ * @throws {SyntaxError} Laid out like V8's for parse errors, top-level return, a hashbang, and any occurrence of {@link RESERVED_PREFIX}.
54
+ */
55
+ export function scanProgram(code: string, options: { filename: string }): ScopedReplScan {
56
+ // A hashbang is valid only at the start of a Script, and the generated prefix precedes the program.
57
+ if (code.startsWith('#!')) throw programSyntaxError(code, options.filename, 0, 'Hashbang lines are not supported')
58
+ const reserved = code.indexOf(RESERVED_PREFIX)
59
+ if (reserved >= 0) throw programSyntaxError(code, options.filename, reserved, `Names starting with '${RESERVED_PREFIX}' are reserved`)
60
+ let program: Program
61
+ try {
62
+ program = parse(code, { ecmaVersion: 'latest', sourceType: 'script', allowAwaitOutsideFunction: true })
63
+ } catch (error: unknown) {
64
+ throw parseFailure(code, options.filename, error)
65
+ }
66
+ const declarations = new Map<string, ScopedReplBindingKind>()
67
+ const declare = (identifier: Identifier, kind: ScopedReplBindingKind): void => {
68
+ // A function declaration initializes the name before any statement runs, so a var of the same name never replaces it.
69
+ if (kind === 'var' && declarations.get(identifier.name) === 'function') return
70
+ declarations.set(identifier.name, kind)
71
+ }
72
+ const collectVar = (statement: Statement | ModuleDeclaration): void => {
73
+ switch (statement.type) {
74
+ case 'VariableDeclaration':
75
+ if (statement.kind === 'var') for (const declarator of statement.declarations) bindingNames(declarator.id, (identifier) => { declare(identifier, 'var') })
76
+ break
77
+ case 'BlockStatement': statement.body.forEach(collectVar); break
78
+ case 'IfStatement':
79
+ collectVar(statement.consequent)
80
+ if (statement.alternate) collectVar(statement.alternate)
81
+ break
82
+ case 'ForStatement':
83
+ if (statement.init?.type === 'VariableDeclaration') collectVar(statement.init)
84
+ collectVar(statement.body)
85
+ break
86
+ case 'ForInStatement':
87
+ case 'ForOfStatement':
88
+ if (statement.left.type === 'VariableDeclaration') collectVar(statement.left)
89
+ collectVar(statement.body)
90
+ break
91
+ case 'WhileStatement':
92
+ case 'DoWhileStatement':
93
+ case 'LabeledStatement':
94
+ case 'WithStatement': collectVar(statement.body); break
95
+ case 'TryStatement':
96
+ collectVar(statement.block)
97
+ if (statement.handler) collectVar(statement.handler.body)
98
+ if (statement.finalizer) collectVar(statement.finalizer)
99
+ break
100
+ case 'SwitchStatement': for (const branch of statement.cases) branch.consequent.forEach(collectVar); break
101
+ default: break // Functions and classes start their own var scope; other statements declare nothing.
102
+ }
103
+ }
104
+ for (const statement of program.body) {
105
+ switch (statement.type) {
106
+ case 'VariableDeclaration': {
107
+ const kind = statement.kind === 'var' || statement.kind === 'let' ? statement.kind : 'const'
108
+ for (const declarator of statement.declarations) bindingNames(declarator.id, (identifier) => { declare(identifier, kind) })
109
+ break
110
+ }
111
+ case 'FunctionDeclaration': declare(statement.id, 'function'); break
112
+ case 'ClassDeclaration': declare(statement.id, 'class'); break
113
+ default: collectVar(statement)
114
+ }
115
+ }
116
+ let useStrict = false
117
+ for (const statement of program.body) {
118
+ if (statement.type !== 'ExpressionStatement' || statement.directive === undefined) break
119
+ if (statement.directive === 'use strict') useStrict = true
120
+ }
121
+ const last = program.body.findLast(statement => statement.type !== 'EmptyStatement')
122
+ if (last?.type !== 'ExpressionStatement') return { declarations, useStrict }
123
+ const finalExpression = { statementStart: last.start, expressionStart: last.expression.start, expressionEnd: last.expression.end }
124
+ return { declarations, useStrict, finalExpression }
125
+ }
126
+
127
+ /**
128
+ * Build the Script source that copies earlier bindings, exposes read functions, and runs the program.
129
+ * The generated prefix occupies line 0, so compiling with `lineOffset: -1` reports program line N as line N.
130
+ * A copy exists exactly for each carried binding. A name the program declares again starts from its earlier value through a `var` copy,
131
+ * other `var` bindings are copied as `var`, and all others as `let`.
132
+ * With `strict` off, a program whose directives include "use strict" gets that directive at the start of its function body.
133
+ * @param code - Program text that produced `scan`.
134
+ * @param scan - Result of {@link scanProgram} for `code`.
135
+ * @param carried - Earlier bindings to copy, in the order of the copied values: names the program does not declare,
136
+ * and names it declares again only with `var`.
137
+ * @param options - Whether the whole Script is strict, and whether the final expression becomes the completion value.
138
+ * @returns Source evaluating to a factory, and every binding in the order of the read functions it pushes.
139
+ */
140
+ export function buildProgramSource(
141
+ code: string, scan: ScopedReplScan, carried: readonly ScopedReplBinding[], options: { strict: boolean; finalExpression: boolean },
142
+ ): { source: string; bindings: ScopedReplBinding[] } {
143
+ const copiedOnly = carried.filter(({ name }) => !scan.declarations.has(name))
144
+ const bindings = [...copiedOnly, ...Array.from(scan.declarations, ([name, kind]) => ({ name, kind }))]
145
+ // A copy only carries the earlier value in; declaring it const would only forbid later assignments.
146
+ const copies = carried.map(({ name, kind }, index) => {
147
+ const keyword = kind === 'var' || scan.declarations.has(name) ? 'var' : 'let'
148
+ return ` ${keyword} ${name} = ${BINDING_VALUES}[${index}];`
149
+ }).join('')
150
+ const getters = bindings.length === 0 ? '' : ` ${BINDING_GETTERS}.push(${bindings.map(({ name }) => `() => ${name}`).join(', ')});`
151
+ const final = options.finalExpression ? scan.finalExpression : undefined
152
+ const body = final === undefined ? code : `${code.slice(0, final.statementStart)}return ${code.slice(final.statementStart, final.expressionStart)}{ value: (${code.slice(final.expressionStart, final.expressionEnd)}) }${code.slice(final.expressionEnd)}`
153
+ // The copies precede the program, so a directive the program wrote no longer leads the function body unless repeated here.
154
+ const directive = !options.strict && scan.useStrict ? '"use strict";' : ''
155
+ const prefix = `${options.strict ? '"use strict";' : ''}(function (${BINDING_VALUES}, ${BINDING_GETTERS}) { return async function () {${directive}${copies}${getters}`
156
+ // The closing line stays separate because the program's last line may end with a line comment.
157
+ return { source: `${prefix}\n${body}\n} })`, bindings }
158
+ }
159
+
160
+ /** A name declared again after an earlier program bound it. */
161
+ export interface ScopedReplRedeclaration {
162
+ /** Redeclared identifier. */
163
+ name: string
164
+ /** Keyword recorded for the earlier binding: its most recent declaration, kept by programs that only copied it. */
165
+ previous: ScopedReplBindingKind
166
+ /** Keyword of the redeclaring program's declaration. */
167
+ current: ScopedReplBindingKind
168
+ }
169
+
170
+ /** Completion of one program: the boxed final expression, or undefined when there is none or it is disabled. */
171
+ export type ScopedReplCompletion = { value: unknown } | undefined
172
+ /** A compiled program bound to its copied values; each call runs the program body once. */
173
+ export type ScopedReplProgram = () => Promise<ScopedReplCompletion>
174
+
175
+ /** Choices fixed for every program of one scope chain. */
176
+ export interface ScopedReplScopesOptions {
177
+ /** Force strict mode for every program; otherwise a program's own leading "use strict" directive decides. */
178
+ strict: boolean
179
+ /** Receives the names a successfully compiled program declares again, before that program runs. */
180
+ onRedeclaration?: (redeclarations: readonly ScopedReplRedeclaration[]) => void
181
+ }
182
+
183
+ /** Inputs for compiling one program. */
184
+ export interface ScopedReplCompileOptions {
185
+ /** Filename shown by syntax errors and stack frames of this program. */
186
+ filename: string
187
+ /** Context shared by every program of the chain. */
188
+ context: Context
189
+ /** Use the last top-level expression statement as the boxed completion. */
190
+ finalExpression: boolean
191
+ /** Dynamic import handling for this program; omission leaves import() without a callback. */
192
+ importModuleDynamically?: ScriptOptions['importModuleDynamically']
193
+ }
194
+
195
+ type ScopedReplFactory = (values: unknown[], getters: (() => unknown)[]) => ScopedReplProgram
196
+ interface CarriedValue { kind: ScopedReplBindingKind; value: unknown }
197
+ /** Bindings, pushed read functions, and replaced values of the most recently compiled program. */
198
+ interface CompiledProgram {
199
+ bindings: readonly ScopedReplBinding[]
200
+ getters: readonly (() => unknown)[]
201
+ replaced: ReadonlyMap<string, CarriedValue>
202
+ }
203
+
204
+ /**
205
+ * Compile programs that each run in their own scope and start with copies of the top-level bindings earlier programs left.
206
+ * A program reads earlier bindings when it is compiled: values earlier code assigns afterwards stay with that code.
207
+ * A var redeclaration starts from the earlier value. An earlier name whose let, const, or class redeclaration never finished initializing
208
+ * keeps the value it had before; an uninitialized new name is dropped.
209
+ */
210
+ export class ScopedReplScopes {
211
+ private readonly options: ScopedReplScopesOptions
212
+ private bindings = new Map<string, { kind: ScopedReplBindingKind; read: () => unknown }>()
213
+ private replaced: ReadonlyMap<string, CarriedValue> = new Map()
214
+ private compiled: CompiledProgram | undefined
215
+
216
+ /**
217
+ * Start an empty scope chain.
218
+ * @param options - Strictness and the redeclaration observer shared by every program.
219
+ */
220
+ constructor(options: ScopedReplScopesOptions) {
221
+ // Source child processes run under Node's erasable-only type stripping, which rejects parameter properties.
222
+ this.options = options
223
+ }
224
+
225
+ /**
226
+ * Scan and compile one program against the bindings current at this moment.
227
+ * Bindings of the previously compiled program apply once its body has started; a syntax error leaves the chain unchanged.
228
+ * @param code - Type-stripped JavaScript of the program.
229
+ * @param options - Filename, shared context, completion choice, and import handling.
230
+ * @returns The program, which the caller runs once.
231
+ * @throws {SyntaxError} From scanning or V8 compilation, with its location and caret and without compiler frames.
232
+ */
233
+ compile(code: string, options: ScopedReplCompileOptions): ScopedReplProgram {
234
+ this.adoptCompiled()
235
+ const strict = this.options.strict
236
+ const scan = scanProgram(code, { filename: options.filename })
237
+ const carried: ScopedReplBinding[] = []
238
+ const values: unknown[] = []
239
+ const replaced = new Map<string, CarriedValue>()
240
+ const redeclarations: ScopedReplRedeclaration[] = []
241
+ for (const [name, binding] of this.bindings) {
242
+ const current = this.currentValue(name, binding)
243
+ if (current === undefined) continue
244
+ const kind = scan.declarations.get(name)
245
+ // A var redeclaration starts from the earlier value, as a global var does in Node's REPL, so an unreached one keeps it.
246
+ if (kind === undefined || kind === 'var') {
247
+ carried.push({ name, kind: current.kind })
248
+ values.push(current.value)
249
+ }
250
+ if (kind !== undefined) {
251
+ replaced.set(name, current)
252
+ redeclarations.push({ name, previous: current.kind, current: kind })
253
+ }
254
+ }
255
+ const { source, bindings } = buildProgramSource(code, scan, carried, { strict, finalExpression: options.finalExpression })
256
+ const scriptOptions: ScriptOptions = {
257
+ filename: options.filename,
258
+ lineOffset: -1,
259
+ ...options.importModuleDynamically === undefined ? {} : { importModuleDynamically: options.importModuleDynamically },
260
+ }
261
+ let factory: ScopedReplFactory
262
+ try {
263
+ factory = new Script(source, scriptOptions).runInContext(options.context) as ScopedReplFactory
264
+ } catch (error: unknown) {
265
+ throw withoutCompilerFrames(error)
266
+ }
267
+ if (redeclarations.length > 0) this.options.onRedeclaration?.(redeclarations)
268
+ const getters: (() => unknown)[] = []
269
+ const program = factory(values, getters)
270
+ this.compiled = { bindings, getters, replaced }
271
+ return program
272
+ }
273
+
274
+ private adoptCompiled(): void {
275
+ const program = this.compiled
276
+ this.compiled = undefined
277
+ // The prefix pushes every read function before the program body runs; an unstarted program is skipped.
278
+ if (program === undefined || program.getters.length < program.bindings.length) return
279
+ const { getters } = program
280
+ this.bindings = new Map(program.bindings.map(({ name, kind }, index) => [name, { kind, read: getters[index] as () => unknown }]))
281
+ this.replaced = program.replaced
282
+ }
283
+
284
+ private currentValue(name: string, binding: { kind: ScopedReplBindingKind; read: () => unknown }): CarriedValue | undefined {
285
+ try {
286
+ return { kind: binding.kind, value: binding.read() }
287
+ } catch (_error: unknown) {
288
+ // The declaration never finished initializing; later programs see the value it replaced, if any.
289
+ return this.replaced.get(name)
290
+ }
291
+ }
292
+ }
293
+
294
+ /** Drop the compiler frames V8 appends after a compile error's heading; the location and caret precede the heading. */
295
+ function withoutCompilerFrames(error: unknown): unknown {
296
+ /* v8 ignore next -- V8 reports every compile failure of the generated source as a SyntaxError. */
297
+ if (!(error instanceof SyntaxError)) return error
298
+ const heading = `\n${error.name}: ${error.message}`
299
+ error.stack = `${String(error.stack).split(heading, 1).join('')}${heading}`
300
+ return error
301
+ }
302
+
303
+ /** Collect identifiers bound by a declaration pattern. */
304
+ function bindingNames(pattern: Pattern, visit: (identifier: Identifier) => void): void {
305
+ switch (pattern.type) {
306
+ case 'Identifier': visit(pattern); break
307
+ case 'ObjectPattern':
308
+ for (const property of pattern.properties) bindingNames(property.type === 'RestElement' ? property.argument : property.value, visit)
309
+ break
310
+ case 'ArrayPattern':
311
+ for (const element of pattern.elements) if (element !== null) bindingNames(element, visit)
312
+ break
313
+ case 'RestElement': bindingNames(pattern.argument, visit); break
314
+ case 'AssignmentPattern': bindingNames(pattern.left, visit); break
315
+ /* v8 ignore next -- Declaration patterns never bind member expressions; acorn rejects them first. */
316
+ case 'MemberExpression': break
317
+ }
318
+ }
319
+
320
+ /** Convert an acorn parse error to a positioned program SyntaxError. */
321
+ function parseFailure(code: string, filename: string, error: unknown): unknown {
322
+ /* v8 ignore next -- acorn raises every parse failure, including exhausted parser stack, as a positioned SyntaxError. */
323
+ if (!(error instanceof SyntaxError) || !('pos' in error) || typeof error.pos !== 'number') return error
324
+ const detail = error.message.replace(/ \(\d+:\d+\)$/, '')
325
+ const message = detail === "'return' outside of function" ? 'Illegal return statement'
326
+ : detail === 'Unexpected token' && error.pos >= code.length ? 'Unexpected end of input'
327
+ : detail
328
+ return programSyntaxError(code, filename, error.pos, message)
329
+ }
330
+
331
+ /** Create a SyntaxError whose stack shows the location, source line, and caret like V8's. */
332
+ function programSyntaxError(code: string, filename: string, offset: number, message: string): SyntaxError {
333
+ const { line, column } = getLineInfo(code, offset)
334
+ const rest = code.slice(offset - column)
335
+ const end = rest.search(/[\n\r\u2028\u2029]/)
336
+ const error = new SyntaxError(message)
337
+ error.stack = `${filename}:${line}\n${end < 0 ? rest : rest.slice(0, end)}\n${' '.repeat(column)}^\n\n${error.name}: ${message}`
338
+ return error
339
+ }
@@ -1,4 +1,4 @@
1
- /** Evaluation results and operations shared by the three child evaluators. */
1
+ /** Evaluation results and operations shared by the four child evaluators. */
2
2
 
3
3
  /** An import requested by a program or its VM-loaded ESM dependencies in the runner process. */
4
4
  export interface ProgramImportRequest {
@@ -26,12 +26,12 @@ export type ProgramImportResult =
26
26
 
27
27
  /**
28
28
  * Intercept program imports inside the runner, independently of evaluation syntax.
29
- * VM Script recursively loads .mjs files and .js files in type: module packages in its context.
29
+ * VM Script and scoped REPL recursively load .mjs files and .js files in type: module packages in their context.
30
30
  * Their static and dynamic imports also consult the handler; each static request binds once.
31
31
  * Default and redirect use Node's active resolution conditions relative to the importer; replacements do not reenter the handler.
32
32
  * Other formats, AsyncFunction and Node REPL use Node's loader without intercepting dependencies.
33
33
  * A thrown or rejected value rejects the program's import; there is no fallback after failure.
34
- * VM Script accepts async handlers and requires --experimental-vm-modules.
34
+ * VM Script and scoped REPL accept async handlers and require --experimental-vm-modules.
35
35
  * AsyncFunction and Node REPL require synchronous decisions and no VM startup flag.
36
36
  * @param request - Specifier, importing filename and import attributes.
37
37
  * @returns Default loading, one redirect, or runner-local module exports.