@acryldev/harness-runtime 0.0.0-stage → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +49 -0
  2. package/lib/index.mjs +5693 -0
  3. package/lib/index.mjs.map +1 -0
  4. package/lib/types/acryl-home.d.ts +81 -0
  5. package/lib/types/app/new-app.d.ts +65 -0
  6. package/lib/types/app/start-source.d.ts +47 -0
  7. package/lib/types/blueprint/blueprint.d.ts +74 -0
  8. package/lib/types/blueprint/brand-identity.d.ts +26 -0
  9. package/lib/types/blueprint/compose.d.ts +53 -0
  10. package/lib/types/blueprint/definition.d.ts +22 -0
  11. package/lib/types/blueprint/index.d.ts +7 -0
  12. package/lib/types/blueprint/manifest.d.ts +35 -0
  13. package/lib/types/blueprint/selection.d.ts +19 -0
  14. package/lib/types/cli-market-install.d.ts +97 -0
  15. package/lib/types/cli-market-plugins.d.ts +81 -0
  16. package/lib/types/coding-capabilities.d.ts +29 -0
  17. package/lib/types/durable-message.d.ts +18 -0
  18. package/lib/types/engine-dsh.d.ts +181 -0
  19. package/lib/types/engine-files.d.ts +8 -0
  20. package/lib/types/engine-host.d.ts +32 -0
  21. package/lib/types/engine-tools.d.ts +11 -0
  22. package/lib/types/index.d.ts +67 -0
  23. package/lib/types/instance/announce-self.d.ts +38 -0
  24. package/lib/types/instance/app-instance.d.ts +125 -0
  25. package/lib/types/instance/index.d.ts +6 -0
  26. package/lib/types/instance/offline-lock.d.ts +29 -0
  27. package/lib/types/instance/online-secret.d.ts +29 -0
  28. package/lib/types/instance/registry.d.ts +26 -0
  29. package/lib/types/instance/select.d.ts +43 -0
  30. package/lib/types/module-hooks.d.ts +19 -0
  31. package/lib/types/module-resolution.d.ts +31 -0
  32. package/lib/types/package-overlay.d.ts +41 -0
  33. package/lib/types/pinned-pnpm.d.ts +15 -0
  34. package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
  35. package/lib/types/plugin-doctor.d.ts +49 -0
  36. package/lib/types/plugin-lifecycle-state.d.ts +92 -0
  37. package/lib/types/plugin-lifecycle.d.ts +87 -0
  38. package/lib/types/profile-layout.d.ts +17 -0
  39. package/lib/types/profile-owner.d.ts +25 -0
  40. package/lib/types/profile-repair/backup.d.ts +37 -0
  41. package/lib/types/profile-repair/findings.d.ts +29 -0
  42. package/lib/types/profile-repair/index.d.ts +9 -0
  43. package/lib/types/profile-repair/inspector.d.ts +11 -0
  44. package/lib/types/profile-repair/repair.d.ts +38 -0
  45. package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
  46. package/lib/types/profile-resolution/resolver.d.ts +41 -0
  47. package/lib/types/profile-resolution/service.d.ts +22 -0
  48. package/lib/types/prompt-budget.d.ts +44 -0
  49. package/lib/types/session-bridge.d.ts +57 -0
  50. package/lib/types/session-log-exporter.d.ts +31 -0
  51. package/lib/types/system-prompt-capture.d.ts +29 -0
  52. package/lib/types/web-favicon-data.d.ts +5 -0
  53. package/lib/types/web-favicon.d.ts +23 -0
  54. package/lib/types/web-market-install.d.ts +114 -0
  55. package/lib/types/web-market-plugins.d.ts +106 -0
  56. package/lib/types/web-port.d.ts +15 -0
  57. package/package.json +211 -3
  58. package/src/acryl-home.ts +103 -0
  59. package/src/app/new-app.ts +239 -0
  60. package/src/app/start-source.ts +110 -0
  61. package/src/blueprint/blueprint.ts +141 -0
  62. package/src/blueprint/brand-identity.ts +75 -0
  63. package/src/blueprint/compose.ts +222 -0
  64. package/src/blueprint/definition.ts +92 -0
  65. package/src/blueprint/index.ts +20 -0
  66. package/src/blueprint/manifest.ts +145 -0
  67. package/src/blueprint/selection.ts +74 -0
  68. package/src/cli-market-install.ts +181 -0
  69. package/src/cli-market-plugins.ts +176 -0
  70. package/src/coding-capabilities.ts +61 -0
  71. package/src/durable-message.ts +23 -0
  72. package/src/engine-dsh.ts +856 -0
  73. package/src/engine-files.ts +9 -0
  74. package/src/engine-host.ts +128 -0
  75. package/src/engine-tools.ts +26 -0
  76. package/src/index.ts +436 -0
  77. package/src/instance/announce-self.ts +88 -0
  78. package/src/instance/app-instance.ts +240 -0
  79. package/src/instance/index.ts +45 -0
  80. package/src/instance/offline-lock.ts +71 -0
  81. package/src/instance/online-secret.ts +55 -0
  82. package/src/instance/registry.ts +53 -0
  83. package/src/instance/select.ts +134 -0
  84. package/src/module-hooks.ts +41 -0
  85. package/src/module-resolution.ts +187 -0
  86. package/src/package-overlay.ts +160 -0
  87. package/src/pinned-pnpm.ts +67 -0
  88. package/src/plugin-acryl-workspace-status.ts +99 -0
  89. package/src/plugin-doctor.ts +141 -0
  90. package/src/plugin-lifecycle-state.ts +347 -0
  91. package/src/plugin-lifecycle.ts +223 -0
  92. package/src/profile-layout.ts +97 -0
  93. package/src/profile-owner.ts +52 -0
  94. package/src/profile-repair/backup.ts +119 -0
  95. package/src/profile-repair/findings.ts +43 -0
  96. package/src/profile-repair/index.ts +10 -0
  97. package/src/profile-repair/inspector.ts +156 -0
  98. package/src/profile-repair/repair.ts +137 -0
  99. package/src/profile-resolution/moved-framework.ts +64 -0
  100. package/src/profile-resolution/resolver.ts +876 -0
  101. package/src/profile-resolution/service.ts +99 -0
  102. package/src/prompt-budget.ts +118 -0
  103. package/src/session-bridge.ts +350 -0
  104. package/src/session-log-exporter.ts +68 -0
  105. package/src/system-prompt-capture.ts +99 -0
  106. package/src/web-favicon-data.ts +6 -0
  107. package/src/web-favicon.ts +43 -0
  108. package/src/web-market-install.ts +206 -0
  109. package/src/web-market-plugins.ts +215 -0
  110. package/src/web-port.ts +39 -0
  111. package/tests/account-callback.spec.ts +173 -0
  112. package/tests/acryl-home.spec.ts +39 -0
  113. package/tests/agent-self-hosting.spec.ts +101 -0
  114. package/tests/announce-self.spec.ts +84 -0
  115. package/tests/app-lifecycle.spec.ts +99 -0
  116. package/tests/blank-blueprint.spec.ts +110 -0
  117. package/tests/blueprint-definition.spec.ts +128 -0
  118. package/tests/blueprint.spec.ts +138 -0
  119. package/tests/bulkhead.spec.ts +187 -0
  120. package/tests/coding-vocabulary.spec.ts +15 -0
  121. package/tests/dump-system-prompt.spec.ts +65 -0
  122. package/tests/e2e-real-model.spec.ts +71 -0
  123. package/tests/e2e-restart-real-model.spec.ts +77 -0
  124. package/tests/engine-dsh.spec.ts +340 -0
  125. package/tests/engine-host-mount-root-include.spec.ts +118 -0
  126. package/tests/engine-host.spec.ts +176 -0
  127. package/tests/engine-optional.spec.ts +81 -0
  128. package/tests/extension-examples.spec.ts +261 -0
  129. package/tests/hooks-thread-stack.ts +27 -0
  130. package/tests/instance-patches.spec.ts +25 -0
  131. package/tests/instance.spec.ts +235 -0
  132. package/tests/live/community-plugins.spec.ts +83 -0
  133. package/tests/module-hooks.spec.ts +35 -0
  134. package/tests/module-resolution.spec.ts +265 -0
  135. package/tests/moved-framework.spec.ts +61 -0
  136. package/tests/new-app.spec.ts +132 -0
  137. package/tests/organizer-growth.spec.ts +117 -0
  138. package/tests/pinned-pnpm.spec.ts +34 -0
  139. package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
  140. package/tests/plugin-context.spec.ts +640 -0
  141. package/tests/plugin-doctor.spec.ts +183 -0
  142. package/tests/plugin-enablement-one-store.spec.ts +130 -0
  143. package/tests/plugin-lifecycle-state.spec.ts +169 -0
  144. package/tests/profile-layout.spec.ts +58 -0
  145. package/tests/profile-owner.spec.ts +38 -0
  146. package/tests/profile-repair/profile-repair.spec.ts +231 -0
  147. package/tests/profile-resolution-port.spec.ts +30 -0
  148. package/tests/profile-resolution-service.spec.ts +273 -0
  149. package/tests/profile-resolution-swap.spec.ts +69 -0
  150. package/tests/profile-resolution.spec.ts +2535 -0
  151. package/tests/profile.spec.ts +70 -0
  152. package/tests/project-registry.spec.ts +81 -0
  153. package/tests/prompt-budget.spec.ts +58 -0
  154. package/tests/real-home-guard.spec.ts +178 -0
  155. package/tests/session-bridge.spec.ts +316 -0
  156. package/tests/start-source.spec.ts +65 -0
  157. package/tests/system-prompt-shape.spec.ts +95 -0
  158. package/tests/three-levels.spec.ts +84 -0
  159. package/tests/tool-gateway.spec.ts +116 -0
  160. package/tests/tool-schemas.spec.ts +41 -0
  161. package/tests/web-favicon.spec.ts +42 -0
  162. package/tests/web-port.spec.ts +38 -0
  163. package/tests/web-startup-hold.spec.ts +79 -0
  164. package/tsconfig.json +24 -0
  165. package/tsdown.config.ts +2 -0
  166. package/vitest.config.ts +18 -0
  167. package/README.md +0 -3
@@ -0,0 +1,876 @@
1
+ /*
2
+ * Ported from DeepSeek Harness, packages/boot/app-boot/src/profile-resolution/resolver.ts at dsh-v0.2.0-rc.2 (639ed01539, MIT,
3
+ * Copyright (c) 2026 DeepSeek; see THIRD_PARTY_NOTICES.md). The routing is the original's, unchanged. Deviation: the original reaches
4
+ * Node's internal ESM loader, CommonJS helpers and ESM resolver through the native node-addon-require-builtin add-on, which Electron
5
+ * builds after 44.0.0 refuse to load; this port uses Node's public module hooks instead (`registerHooks` for ESM resolution,
6
+ * `Module._resolveFilename` for CommonJS, the conditions a hook call reports), and resolves a CommonJS package-imports target with the
7
+ * CommonJS resolver from the anchor rather than the internal ESM `defaultResolve` (the two choose the same `exports` target). The
8
+ * port check in tests/profile-resolution-port.spec.ts fails when the original changes, so a DeepSeek Harness bump re-ports it.
9
+ */
10
+ /** In-memory profile package routing for Node's default ESM and CommonJS loaders. */
11
+
12
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
13
+ import Module, { createRequire, isBuiltin, type ResolveFnOutput, type ResolveHookContext } from 'node:module'
14
+ import { basename, dirname, join, resolve, sep } from 'node:path'
15
+ import { fileURLToPath, pathToFileURL } from 'node:url'
16
+ import { getEnvironmentData, setEnvironmentData } from 'node:worker_threads'
17
+ import { imports as resolvePackageImports, type Package as ResolvePackageManifest } from 'resolve.exports'
18
+ import type { RuntimeResolution, RuntimeResolutionEntry } from '@deepseek-ai/dsh-app-boot'
19
+ import { requireModuleHooks } from '../module-hooks.ts'
20
+
21
+ const WORKER_RESOLUTION_KEY = '@deepseek-ai/dsh-app-boot/profile-resolution'
22
+
23
+ interface CommonJsParent {
24
+ filename?: string | null
25
+ parent?: CommonJsParent | null
26
+ paths?: string[]
27
+ }
28
+
29
+ interface CommonJsOptions {
30
+ paths?: string[]
31
+ conditions?: ReadonlySet<string>
32
+ }
33
+
34
+ interface CommonJsModule {
35
+ new(id?: string, parent?: CommonJsParent): CommonJsParent
36
+ _nodeModulePaths(path: string): string[]
37
+ _resolveFilename(
38
+ request: string, parent: CommonJsParent | null | undefined, isMain: boolean, options?: CommonJsOptions,
39
+ ): string
40
+ }
41
+
42
+ /** One resolve step of Node's public module hooks: the next hook, or Node's default resolver. */
43
+ type NextResolve = (specifier: string, context?: Partial<ResolveHookContext>) => ResolveFnOutput
44
+
45
+ /**
46
+ * Where Node continues a scoped bare request. `native` keeps the importer's own lookup: the chain is
47
+ * answered below the interception layer. `interception` answers at the interception layer from the
48
+ * entry's declaring manifest; `after` anchors Node's chain above the layer for a CommonJS subpath the
49
+ * entry lacks. `native-after-interception` resumes Node's chain from `parent`: the interception layer for a
50
+ * name without an entry, or the layer above it after an `interception` subpath miss.
51
+ */
52
+ type ResolutionRoute =
53
+ | { readonly kind: 'interception'; readonly entry: RuntimeResolutionEntry; readonly after: string }
54
+ | { readonly kind: 'native-after-interception'; readonly parent: string }
55
+ | { readonly kind: 'native'; readonly packageDir?: string }
56
+
57
+ interface ResolutionRouteState {
58
+ readonly route: ResolutionRoute
59
+ packageDir?: string
60
+ esm?: ResolveFnOutput
61
+ cjs?: string
62
+ }
63
+
64
+ interface CommonJsLookup {
65
+ readonly cacheable: boolean
66
+ resolveNative(searchPaths: readonly string[]): string
67
+ resolveEntry(entry: RuntimeResolutionEntry, after: string): string
68
+ }
69
+
70
+ /** The lookup positions that one interception layer fixes on an importer's ancestor chain. */
71
+ interface LayerPositions {
72
+ /** Search paths with this prefix lie below the layer and are answered by their physical content. */
73
+ readonly localPrefix: string
74
+ /** Manifest anchoring Node's lookup at the layer's physical directory. */
75
+ readonly nativeAfter: string
76
+ /** Manifest anchoring Node's lookup above the layer after a CommonJS subpath miss. */
77
+ readonly after: string
78
+ }
79
+
80
+ /**
81
+ * The interception layer of one importer. A profile's layer is its parent's node_modules and answers every entry
82
+ * for the active profile. Linked importers apply current peer declarations at each ancestor node_modules
83
+ * position without memoizing the selected route.
84
+ */
85
+ type InterceptionLayer =
86
+ | LayerPositions & { readonly kind: 'profile'; readonly active: boolean }
87
+ | { readonly kind: 'linked' }
88
+
89
+ interface ParentRoutes {
90
+ readonly parent: string
91
+ readonly layer: InterceptionLayer
92
+ readonly requests: Map<string, ResolutionRouteState>
93
+ selfReferenceName?: string | false | null
94
+ }
95
+
96
+ type ResolutionRoutes = Map<string, ParentRoutes | false>
97
+
98
+ interface CompiledResolution {
99
+ readonly entries: ReadonlyMap<string, RuntimeResolutionEntry>
100
+ readonly profilesDir: string
101
+ readonly profileDir: string | undefined
102
+ readonly profilePaths: readonly string[]
103
+ readonly profile: readonly string[]
104
+ readonly installationPaths: readonly string[]
105
+ readonly linkedPaths: readonly string[]
106
+ readonly localPackageNames: ReadonlySet<string>
107
+ readonly esmRoutes: ResolutionRoutes
108
+ readonly cjsRoutes: ResolutionRoutes
109
+ }
110
+
111
+ /** Active interception in one Node isolate. */
112
+ export interface RuntimeInterception {
113
+ /**
114
+ * Locate a bare package without requiring one of its exports.
115
+ * A package subpath selects its package directory without resolving or validating the requested file.
116
+ * @param specifier - bare package or package-subpath specifier.
117
+ * @param parentURL - file URL whose lookup order applies.
118
+ * @returns selected package directory, or undefined when it is absent.
119
+ */
120
+ packageDir(specifier: string, parentURL: string): string | undefined
121
+ /**
122
+ * Atomically publish a complete successor and fresh caches. Linked roots may be added or removed.
123
+ * Removed roots stop intercepting uncovered directories; existing modules and Node caches remain intact.
124
+ * @param successor - fully constructed generation retaining existing package mappings and local names.
125
+ * @throws when the profile scope or existing mappings change, local names are removed or override
126
+ * existing mappings, or a previously published link name selects a different real directory.
127
+ */
128
+ replace(successor: RuntimeResolution): void
129
+ /** Restore the native resolver methods. Interceptions dispose in reverse order. */
130
+ dispose(): void
131
+ }
132
+
133
+ /**
134
+ * Split a bare request into its package name without allocating path segments.
135
+ * @param request - module specifier to classify.
136
+ * @returns the bare package name, or undefined for non-package requests.
137
+ */
138
+ export function barePackageName(request: string): string | undefined {
139
+ if (!request || request[0] === '.' || request[0] === '/' || request[0] === '\\'
140
+ || request[0] === '#' || request.includes(':') || isBuiltin(request)) return
141
+ const first = request.indexOf('/')
142
+ if (request[0] !== '@') return first < 0 ? request : request.slice(0, first)
143
+ if (first < 0) return
144
+ const second = request.indexOf('/', first + 1)
145
+ return second < 0 ? request : request.slice(0, second)
146
+ }
147
+
148
+ function canonicalPath(path: string): string {
149
+ try {
150
+ return realpathSync(path)
151
+ } catch {
152
+ // A runtime resolution may name a profile scope before that directory is materialized.
153
+ return resolve(path)
154
+ }
155
+ }
156
+
157
+ function prefixes(path: string): readonly string[] {
158
+ const configured = resolve(path) + sep
159
+ const canonical = canonicalPath(path) + sep
160
+ return canonical === configured ? [configured] : [configured, canonical]
161
+ }
162
+
163
+ function compileResolution(resolution: RuntimeResolution): CompiledResolution {
164
+ return {
165
+ entries: new Map(resolution.entries.map(entry => [entry.name, entry])),
166
+ profilesDir: resolution.profilesDir,
167
+ profileDir: resolution.profileDir,
168
+ profilePaths: prefixes(resolution.profilesDir),
169
+ profile: resolution.profileDir === undefined ? [] : prefixes(resolution.profileDir),
170
+ installationPaths: [...new Set(resolution.entries
171
+ .filter(entry => entry.scope === 'installation')
172
+ .flatMap(entry => prefixes(entry.packageDir)))],
173
+ linkedPaths: resolution.linkedRoots.flatMap(root => prefixes(root.realPath)),
174
+ localPackageNames: new Set(resolution.localPackageNames),
175
+ esmRoutes: new Map(),
176
+ cjsRoutes: new Map(),
177
+ }
178
+ }
179
+
180
+ /**
181
+ * The interception layer of a profile is `<profileParent>/node_modules`: an entry occupies its name there, so its
182
+ * subpath misses continue above it, and a name without an entry continues at it.
183
+ */
184
+ function computeProfileLayer(dir: string, active: boolean): InterceptionLayer {
185
+ const profileParent = dirname(dir)
186
+ return {
187
+ kind: 'profile', active,
188
+ localPrefix: dir + sep,
189
+ nativeAfter: join(profileParent, 'package.json'),
190
+ after: join(dirname(profileParent), 'package.json'),
191
+ }
192
+ }
193
+
194
+ /** The interception layer of a module path: from its profile directory inside a profiles tree, or its linked root. */
195
+ function findInterceptionLayer(path: string, resolution: CompiledResolution): InterceptionLayer | undefined {
196
+ const treeRoot = resolution.profilePaths.find(prefix => path.startsWith(prefix))
197
+ const activeProfile = resolution.profile.find(prefix => path.startsWith(prefix))
198
+ const dir = treeRoot !== undefined ? profileChild(path, treeRoot) : activeProfile?.slice(0, -1)
199
+ if (dir !== undefined) return computeProfileLayer(dir, activeProfile !== undefined)
200
+ if (!startsWithin(path, resolution.linkedPaths)) return undefined
201
+ if (startsWithin(path, resolution.installationPaths)) return undefined
202
+ return { kind: 'linked' }
203
+ }
204
+
205
+ /** Package names a directory's current manifest lists as peers; an unreadable manifest lists none. */
206
+ function readPeerNames(directory: string): ReadonlySet<string> {
207
+ try {
208
+ const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as {
209
+ peerDependencies?: unknown
210
+ }
211
+ const peers = manifest.peerDependencies
212
+ return new Set(peers !== null && typeof peers === 'object' ? Object.keys(peers) : [])
213
+ } catch (_error) {
214
+ // Node reports the unreadable or invalid manifest itself when it resolves the package's own imports.
215
+ return new Set()
216
+ }
217
+ }
218
+
219
+ function startsWithin(path: string, roots: readonly string[]): boolean {
220
+ for (const root of roots) {
221
+ if (path.startsWith(root)) return true
222
+ }
223
+ return false
224
+ }
225
+
226
+ /**
227
+ * The profile directory owning a module inside the profiles tree: the first path segment below the tree root.
228
+ * @param path - module path below `treePrefix`.
229
+ * @param treePrefix - profiles directory with a trailing separator.
230
+ * @returns the profile directory without a trailing separator.
231
+ */
232
+ function profileChild(path: string, treePrefix: string): string {
233
+ const rest = path.slice(treePrefix.length)
234
+ const end = rest.indexOf(sep)
235
+ return treePrefix + (end < 0 ? rest : rest.slice(0, end))
236
+ }
237
+
238
+ function nativePackageDir(parent: string, name: string): string | undefined {
239
+ for (const searchPath of createRequire(parent).resolve.paths(name) as string[]) {
240
+ const candidate = join(searchPath, name)
241
+ if (existsSync(join(candidate, 'package.json'))) return candidate
242
+ }
243
+ return undefined
244
+ }
245
+
246
+ function localPackageCandidate(searchPath: string, name: string, flavor: 'esm' | 'cjs'): string | undefined {
247
+ const candidate = join(searchPath, name)
248
+ const stat = statSync(candidate, { throwIfNoEntry: false })
249
+ const found = flavor === 'esm'
250
+ ? stat?.isDirectory() === true
251
+ : stat !== undefined
252
+ || ['.js', '.json', '.node'].some(extension => existsSync(candidate + extension))
253
+ return found ? candidate : undefined
254
+ }
255
+
256
+ function selfReferenceName(parent: string): string | false | null {
257
+ let current = dirname(parent)
258
+ while (true) {
259
+ const manifestPath = join(current, 'package.json')
260
+ if (existsSync(manifestPath)) {
261
+ let manifest: Record<string, unknown>
262
+ try {
263
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record<string, unknown>
264
+ } catch (_error) {
265
+ // Only Node decides whether this request consumes an invalid package manifest.
266
+ return null
267
+ }
268
+ return typeof manifest.name === 'string' && manifest.exports != null
269
+ ? manifest.name
270
+ : false
271
+ }
272
+ /* v8 ignore next -- scoped module requests normally find an owning manifest before node_modules. */
273
+ if (basename(current) === 'node_modules') return false
274
+ const next = dirname(current)
275
+ if (next === current) return false
276
+ current = next
277
+ }
278
+ }
279
+
280
+ function packageImportsTarget(
281
+ parent: string, request: string, conditions: Iterable<string>,
282
+ ): { specifier: string; parentURL: string } | undefined {
283
+ let current = dirname(parent)
284
+ while (true) {
285
+ const manifestPath = join(current, 'package.json')
286
+ if (existsSync(manifestPath)) {
287
+ let manifest: ResolvePackageManifest
288
+ try {
289
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as ResolvePackageManifest
290
+ } catch (_error) {
291
+ // The native resolver retains invalid package-target and manifest diagnostics.
292
+ /* v8 ignore next -- native resolution cannot report MODULE_NOT_FOUND after an invalid scope manifest */
293
+ return undefined
294
+ }
295
+ try {
296
+ const target = resolvePackageImports(manifest, request, {
297
+ conditions: [...conditions],
298
+ unsafe: true,
299
+ })?.[0]
300
+ return target !== undefined && barePackageName(target) !== undefined
301
+ ? { specifier: target, parentURL: pathToFileURL(manifestPath).href }
302
+ : undefined
303
+ } catch (_error) {
304
+ // The native resolver retains missing mappings and unmatched-condition diagnostics.
305
+ /* v8 ignore next -- native resolution cannot report MODULE_NOT_FOUND before selecting a valid mapping */
306
+ return undefined
307
+ }
308
+ }
309
+ if (basename(current) === 'node_modules') return undefined
310
+ const next = dirname(current)
311
+ /* v8 ignore next -- a MODULE_NOT_FOUND package-import target always has an owning package scope */
312
+ if (next === current) return undefined
313
+ current = next
314
+ }
315
+ }
316
+
317
+ function packageSearchPaths(
318
+ entry: RuntimeResolutionEntry, request: string, cjs: CommonJsModule,
319
+ ): string[] {
320
+ const name = barePackageName(request)
321
+ /* v8 ignore next -- interception routes are created only for bare package requests */
322
+ if (name === undefined) return cjs._nodeModulePaths(dirname(entry.declarer))
323
+ const suffix = sep + name.split('/').join(sep)
324
+ return entry.packageDir.endsWith(suffix)
325
+ ? [entry.packageDir.slice(0, -suffix.length)]
326
+ : cjs._nodeModulePaths(dirname(entry.declarer))
327
+ }
328
+
329
+ function localCandidateOwnsResolution(candidate: string, resolved: string, request: string, name: string): boolean {
330
+ if (startsWithin(resolved, prefixes(candidate))) return true
331
+ if (sameResolution(candidate, resolved)) return true
332
+ if (['.js', '.json', '.node'].some(extension => sameResolution(candidate + extension, resolved))) return true
333
+ /* v8 ignore next -- a bounded native lookup can escape a candidate only through its root legacy main */
334
+ if (request !== name) return false
335
+ try {
336
+ const manifest = JSON.parse(readFileSync(join(candidate, 'package.json'), 'utf8')) as Record<string, unknown>
337
+ /* v8 ignore next -- a bounded native lookup outside the package directory requires a legacy main */
338
+ if (typeof manifest.main !== 'string') return false
339
+ const main = createRequire(join(candidate, 'package.json')).resolve(resolve(candidate, manifest.main))
340
+ return sameResolution(main, resolved)
341
+ } catch (_error) {
342
+ // Native resolution already owns malformed manifests and missing legacy entries.
343
+ /* v8 ignore next -- this helper runs only after the same native resolution succeeded */
344
+ return false
345
+ }
346
+ }
347
+
348
+ function isUnselectedPackageMiss(error: unknown): boolean {
349
+ const failure = error as NodeJS.ErrnoException & { path?: unknown }
350
+ return failure.code === 'MODULE_NOT_FOUND' && failure.path === undefined
351
+ }
352
+
353
+ function sameResolution(left: string, right: string): boolean {
354
+ if (left === right) return true
355
+ return canonicalPath(left) === canonicalPath(right)
356
+ }
357
+
358
+ /** One mutable pointer to the immutable runtime resolution. */
359
+ class ResolutionRouter {
360
+ private current: CompiledResolution
361
+ private readonly linkedTargets: Map<string, string>
362
+
363
+ constructor(resolution: RuntimeResolution, private readonly nodeModulePaths: (directory: string) => string[]) {
364
+ this.current = compileResolution(resolution)
365
+ this.linkedTargets = new Map(resolution.linkedRoots.map(root => [root.name, root.realPath]))
366
+ }
367
+
368
+ replace(successor: RuntimeResolution): void {
369
+ const entries = new Map(successor.entries.map(entry => [entry.name, entry]))
370
+ if (successor.profilesDir !== this.current.profilesDir
371
+ || successor.profileDir !== this.current.profileDir) {
372
+ throw new Error('profile resolution: a successor cannot change its profile scope')
373
+ }
374
+ for (const [name, current] of this.current.entries) {
375
+ const next = entries.get(name)
376
+ if (next === undefined
377
+ || !sameResolution(current.packageDir, next.packageDir)
378
+ || !sameResolution(current.declarer, next.declarer)
379
+ || current.version !== next.version
380
+ || current.scope !== next.scope) {
381
+ throw new Error(`profile resolution: replacing ${JSON.stringify(name)} requires a process restart`)
382
+ }
383
+ }
384
+ const localPackageNames = new Set(successor.localPackageNames)
385
+ for (const name of this.current.localPackageNames) {
386
+ if (!localPackageNames.has(name)) {
387
+ throw new Error(`profile resolution: removing local package ${JSON.stringify(name)} requires a process restart`)
388
+ }
389
+ }
390
+ for (const name of localPackageNames) {
391
+ if (!this.current.localPackageNames.has(name) && this.current.entries.has(name)) {
392
+ throw new Error(`profile resolution: overriding ${JSON.stringify(name)} locally requires a process restart`)
393
+ }
394
+ }
395
+ // Node retains realpath caches after a root leaves the interception scope.
396
+ for (const root of successor.linkedRoots) {
397
+ const previous = this.linkedTargets.get(root.name)
398
+ if (previous !== undefined && !sameResolution(previous, root.realPath)) {
399
+ throw new Error(`profile resolution: relinking ${JSON.stringify(root.name)} requires a process restart`)
400
+ }
401
+ }
402
+ const next = compileResolution(successor)
403
+ for (const { name, realPath } of successor.linkedRoots) {
404
+ if (!this.linkedTargets.has(name)) this.linkedTargets.set(name, realPath)
405
+ }
406
+ this.current = next
407
+ }
408
+
409
+ /** Whether a module path has an interception layer: it lies in the profiles tree, the active profile, or a linked root. */
410
+ hasInterceptionLayerForPath(path: string): boolean {
411
+ return findInterceptionLayer(path, this.current) !== undefined
412
+ }
413
+
414
+ /** Whether an importer URL is scoped; the answer is memoized with the importer's routes. */
415
+ hasInterceptionLayerForUrl(parentURL: string): boolean {
416
+ return this.getOrCreateParentRoutesForUrl(parentURL) !== false
417
+ }
418
+
419
+ private createParentRoutes(parent: string, resolution: CompiledResolution): ParentRoutes | undefined {
420
+ const layer = findInterceptionLayer(parent, resolution)
421
+ return layer === undefined ? undefined : { parent, layer, requests: new Map() }
422
+ }
423
+
424
+ private getOrCreateParentRoutesForUrl(parentURL: string): ParentRoutes | false {
425
+ const resolution = this.current
426
+ let parentRoutes = resolution.esmRoutes.get(parentURL)
427
+ if (parentRoutes !== undefined) return parentRoutes
428
+ let parent: string | undefined
429
+ try {
430
+ parent = fileURLToPath(parentURL)
431
+ } catch {
432
+ // Only file URLs can lie inside a profile tree or linked root.
433
+ parent = undefined
434
+ }
435
+ parentRoutes = parent === undefined ? false : this.createParentRoutes(parent, resolution) ?? false
436
+ resolution.esmRoutes.set(parentURL, parentRoutes)
437
+ return parentRoutes
438
+ }
439
+
440
+ private routeScoped(
441
+ request: string,
442
+ parentRoutes: ParentRoutes,
443
+ resolution: CompiledResolution,
444
+ flavor: 'esm' | 'cjs',
445
+ cjs?: CommonJsLookup,
446
+ ): ResolutionRouteState | undefined {
447
+ const { parent, layer, requests } = parentRoutes
448
+ const memo = layer.kind === 'profile' && (cjs === undefined || cjs.cacheable)
449
+ const name = barePackageName(request)
450
+ if (name === undefined) return undefined
451
+
452
+ if (parentRoutes.selfReferenceName === undefined || !memo) {
453
+ parentRoutes.selfReferenceName = selfReferenceName(parent)
454
+ }
455
+ if (parentRoutes.selfReferenceName === name || parentRoutes.selfReferenceName === null) {
456
+ const state = { route: { kind: 'native' as const } }
457
+ if (memo) requests.set(request, state)
458
+ return state
459
+ }
460
+
461
+ if (layer.kind === 'linked') return this.routeLinked(request, name, parent, resolution, flavor, cjs)
462
+
463
+ const target = resolution.entries.get(name)
464
+ const candidates: string[] = []
465
+ const localSearchPaths: string[] = []
466
+ for (const searchPath of createRequire(parent).resolve.paths(name) as string[]) {
467
+ if (!searchPath.startsWith(layer.localPrefix)) break
468
+ localSearchPaths.push(searchPath)
469
+ const candidate = localPackageCandidate(searchPath, name, flavor)
470
+ if (candidate !== undefined) candidates.push(candidate)
471
+ }
472
+ if (candidates.length > 0) {
473
+ if (cjs !== undefined) {
474
+ try {
475
+ const resolved = cjs.resolveNative(localSearchPaths)
476
+ const selected = candidates.find(candidate => (
477
+ localCandidateOwnsResolution(candidate, resolved, request, name)
478
+ ))
479
+ if (selected !== undefined) {
480
+ const state = {
481
+ route: { kind: 'native' as const, packageDir: selected },
482
+ packageDir: selected,
483
+ cjs: resolved,
484
+ }
485
+ if (memo) requests.set(request, state)
486
+ return state
487
+ }
488
+ } catch (error) {
489
+ if (!isUnselectedPackageMiss(error)) throw error
490
+ }
491
+ } else {
492
+ const selected = candidates[0] as string
493
+ const state = {
494
+ route: { kind: 'native' as const, packageDir: selected },
495
+ packageDir: selected,
496
+ }
497
+ requests.set(request, state)
498
+ return state
499
+ }
500
+ }
501
+
502
+ const route: ResolutionRoute = target !== undefined
503
+ && (target.scope === 'installation' || layer.active)
504
+ ? { kind: 'interception', entry: target, after: layer.after }
505
+ : { kind: 'native-after-interception', parent: layer.nativeAfter }
506
+ const state: ResolutionRouteState = { route }
507
+ if (route.kind === 'interception' && memo) requests.set(request, state)
508
+ return state
509
+ }
510
+
511
+ private routeLinked(
512
+ request: string, name: string, parent: string, resolution: CompiledResolution,
513
+ flavor: 'esm' | 'cjs', cjs: CommonJsLookup | undefined,
514
+ ): ResolutionRouteState {
515
+ const target = resolution.entries.get(name)
516
+ if (target === undefined) return { route: { kind: 'native' } }
517
+ const ancestors = this.nodeModulePaths(dirname(parent))
518
+ const ancestorSet = new Set(ancestors)
519
+ const searchPaths = flavor === 'esm' ? ancestors : createRequire(parent).resolve.paths(name) as string[]
520
+ for (const searchPath of searchPaths) {
521
+ const directory = dirname(searchPath)
522
+ if (ancestorSet.has(searchPath) && readPeerNames(directory).has(name)) {
523
+ const route: ResolutionRoute = { kind: 'interception', entry: target, after: join(dirname(directory), 'package.json') }
524
+ if (cjs === undefined) return { route }
525
+ try {
526
+ const resolved = cjs.resolveEntry(target, route.after)
527
+ if (localCandidateOwnsResolution(target.packageDir, resolved, request, name)) {
528
+ return { route, packageDir: target.packageDir, cjs: resolved }
529
+ }
530
+ } catch (error) {
531
+ if (!isUnselectedPackageMiss(error)) throw error
532
+ }
533
+ // This position is occupied even when a legacy CommonJS subpath is absent from the supplied package.
534
+ continue
535
+ }
536
+ const candidate = localPackageCandidate(searchPath, name, flavor)
537
+ if (candidate === undefined) continue
538
+ if (cjs === undefined) return { route: { kind: 'native', packageDir: candidate }, packageDir: candidate }
539
+ try {
540
+ const resolved = cjs.resolveNative([searchPath])
541
+ if (localCandidateOwnsResolution(candidate, resolved, request, name)) {
542
+ return { route: { kind: 'native', packageDir: candidate }, packageDir: candidate, cjs: resolved }
543
+ }
544
+ } catch (error) {
545
+ if (!isUnselectedPackageMiss(error)) throw error
546
+ }
547
+ }
548
+ // An exhausted CommonJS lookup must not retry the physical copies at occupied peer positions.
549
+ return cjs === undefined ? { route: { kind: 'native' } } : { route: { kind: 'native' }, cjs: cjs.resolveNative([]) }
550
+ }
551
+
552
+ private routeLocalPackage(
553
+ request: string, parentRoutes: ParentRoutes, resolution: CompiledResolution,
554
+ ): ResolutionRouteState | undefined {
555
+ const name = barePackageName(request)
556
+ const { layer } = parentRoutes
557
+ if (name === undefined || layer.kind !== 'profile' || !layer.active || !resolution.localPackageNames.has(name)) return undefined
558
+ const state = { route: { kind: 'native' as const } }
559
+ parentRoutes.requests.set(request, state)
560
+ return state
561
+ }
562
+
563
+ routeUrl(request: string, parentURL: string): ResolutionRouteState | undefined {
564
+ const resolution = this.current
565
+ const parentRoutes = this.getOrCreateParentRoutesForUrl(parentURL)
566
+ if (parentRoutes === false) return undefined
567
+ const cached = parentRoutes.requests.get(request)
568
+ if (cached !== undefined) return cached
569
+ const local = this.routeLocalPackage(request, parentRoutes, resolution)
570
+ if (local !== undefined) return local
571
+ return this.routeScoped(request, parentRoutes, resolution, 'esm')
572
+ }
573
+
574
+ routePath(
575
+ request: string, parent: string, cjs: CommonJsLookup,
576
+ ): ResolutionRouteState | undefined {
577
+ const resolution = this.current
578
+ let parentRoutes = resolution.cjsRoutes.get(parent)
579
+ if (parentRoutes === false) return undefined
580
+ const cached = cjs.cacheable ? parentRoutes?.requests.get(request) : undefined
581
+ if (cached !== undefined) return cached
582
+ if (parentRoutes === undefined) {
583
+ parentRoutes = this.createParentRoutes(parent, resolution) ?? false
584
+ resolution.cjsRoutes.set(parent, parentRoutes)
585
+ if (parentRoutes === false) return undefined
586
+ }
587
+ return this.routeScoped(request, parentRoutes, resolution, 'cjs', cjs)
588
+ }
589
+
590
+ packageDir(specifier: string, parentURL: string): string | undefined {
591
+ const name = barePackageName(specifier)
592
+ if (name === undefined) return undefined
593
+ const state = this.routeUrl(name, parentURL)
594
+ if (state?.route.kind === 'interception') return state.route.entry.packageDir
595
+ if (state?.packageDir !== undefined) return state.packageDir
596
+ let parent: string
597
+ try {
598
+ parent = state?.route.kind === 'native-after-interception' ? state.route.parent : fileURLToPath(parentURL)
599
+ } catch {
600
+ return undefined
601
+ }
602
+ const found = nativePackageDir(parent, name)
603
+ if (state !== undefined && found !== undefined) state.packageDir = found
604
+ return found
605
+ }
606
+ }
607
+
608
+ /**
609
+ * The conditions Node's CommonJS loader applies when a call names none: `require`, `node`, `node-addons` unless addons are off,
610
+ * `module-sync` when `require(esm)` is on, and every `--conditions`/`-C` flag. A `require()` passing through the module hooks reports its
611
+ * exact set, which {@link installRuntimeInterception} uses; this is the set for a direct `Module._resolveFilename` call.
612
+ */
613
+ function defaultCommonJsConditions(): ReadonlySet<string> {
614
+ const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? '').split(/\s+/u).filter(flag => flag !== '')]
615
+ const user: string[] = []
616
+ for (let at = 0; at < flags.length; at += 1) {
617
+ const flag = flags[at] as string
618
+ const inline = /^(?:--conditions|-C)=(.+)$/u.exec(flag)
619
+ if (inline !== null) user.push(inline[1] as string)
620
+ else if ((flag === '--conditions' || flag === '-C') && flags[at + 1] !== undefined) user.push(flags[(at += 1)] as string)
621
+ }
622
+ const addons = !flags.includes('--no-addons')
623
+ const requireModule = (process.features as { require_module?: boolean }).require_module === true
624
+ return new Set(['require', 'node', ...(addons ? ['node-addons'] : []), ...user, ...(requireModule ? ['module-sync'] : [])])
625
+ }
626
+
627
+ /**
628
+ * Replace a resolver error's message and the same text in its stack.
629
+ * Node's module-hooks thread serializes errors and returns the stack accessor as a read-only configurable
630
+ * data property, so a rejected stack assignment redefines the property value.
631
+ * @param error - resolver error to update in place.
632
+ * @param message - replacement message.
633
+ */
634
+ function replaceErrorMessage(error: Error, message: string): void {
635
+ const { message: originalMessage, stack } = error
636
+ error.message = message
637
+ /* v8 ignore next -- Node's resolver errors always carry a stack */
638
+ if (stack === undefined) return
639
+ const replaced = stack.replace(originalMessage, message)
640
+ if (!Reflect.set(error, 'stack', replaced)) Object.defineProperty(error, 'stack', { value: replaced })
641
+ }
642
+
643
+ function throwWithImporter(error: unknown, routedParent: string, parent: string): never {
644
+ const code = (error as NodeJS.ErrnoException).code
645
+ if (error instanceof Error && (code === 'ERR_MODULE_NOT_FOUND' || code === 'ERR_PACKAGE_PATH_NOT_EXPORTED')) {
646
+ const routedPath = fileURLToPath(routedParent)
647
+ const parentPath = fileURLToPath(parent)
648
+ replaceErrorMessage(error, error.message.replaceAll(routedParent, parent).replaceAll(routedPath, parentPath))
649
+ }
650
+ throw error
651
+ }
652
+
653
+ function throwWithoutCjsAnchor(error: unknown, anchor: string): never {
654
+ const resolved = error as NodeJS.ErrnoException & { requireStack?: string[] }
655
+ const requireStack = resolved.requireStack
656
+ if (error instanceof Error
657
+ && resolved.code === 'MODULE_NOT_FOUND'
658
+ && requireStack?.[0] !== undefined
659
+ && sameResolution(requireStack[0], anchor)) {
660
+ const originalMessage = error.message
661
+ const originalBlock = `\nRequire stack:\n${requireStack.map(path => `- ${path}`).join('\n')}`
662
+ const remaining = requireStack.slice(1)
663
+ /* v8 ignore next -- routed calls always retain the original importing module */
664
+ const replacement = remaining.length === 0
665
+ ? ''
666
+ : `\nRequire stack:\n${remaining.map(path => `- ${path}`).join('\n')}`
667
+ error.message = originalMessage.replace(originalBlock, replacement)
668
+ resolved.requireStack = remaining
669
+ const stack = error.stack
670
+ /* v8 ignore next -- Node's resolver errors always carry a stack */
671
+ if (stack !== undefined) error.stack = stack.replace(originalMessage, error.message)
672
+ }
673
+ throw error
674
+ }
675
+
676
+ /**
677
+ * Install one runtime resolution as the interception on Node's default ESM and CommonJS resolvers.
678
+ * @param resolution - complete package table and profile scope.
679
+ * @returns an interception that publishes a successor or restores the native methods.
680
+ */
681
+ export function installRuntimeInterception(
682
+ resolution: RuntimeResolution,
683
+ ): RuntimeInterception {
684
+ // Before anything is built or patched, so a runtime without module hooks fails with the message and leaves nothing behind.
685
+ const registerHooks = requireModuleHooks()
686
+ const cjs = Module as unknown as CommonJsModule
687
+ const router = new ResolutionRouter(resolution, directory => cjs._nodeModulePaths(directory))
688
+ // The conditions of the require() in flight: the module hooks see them first and Node then calls `_resolveFilename` inside `nextResolve`.
689
+ let requireConditions: readonly string[] | undefined
690
+
691
+ /** One ESM resolve, routed when its importer has an interception layer; `next` is the rest of the hook chain. */
692
+ const resolveEsm = (request: string, context: ResolveHookContext, next: NextResolve): ResolveFnOutput => {
693
+ const parent = context.parentURL
694
+ const native = (parentURL: string | undefined): ResolveFnOutput => next(request, { ...context, parentURL })
695
+ if (parent === undefined || !router.hasInterceptionLayerForUrl(parent)) return native(parent)
696
+ const state = router.routeUrl(request, parent)
697
+ if (state === undefined) {
698
+ const target = request[0] === '#' ? packageImportsTarget(fileURLToPath(parent), request, context.conditions) : undefined
699
+ if (target === undefined) return native(parent)
700
+ try {
701
+ return resolveEsm(target.specifier, { ...context, parentURL: target.parentURL }, next)
702
+ } catch (error) {
703
+ return throwWithImporter(error, target.parentURL, parent)
704
+ }
705
+ }
706
+ const cacheable = Object.keys(context.importAttributes).length === 0
707
+ // A hook that answers without calling the rest of the chain must say so.
708
+ if (cacheable && state.esm !== undefined) return { ...state.esm, shortCircuit: true }
709
+ const route = state.route
710
+ if (route.kind === 'native') {
711
+ const result = native(parent)
712
+ if (cacheable) state.esm = result
713
+ return result
714
+ }
715
+ const routedParent = pathToFileURL(route.kind === 'interception' ? route.entry.declarer : route.parent).href
716
+ let result: ResolveFnOutput
717
+ try {
718
+ result = native(routedParent)
719
+ } catch (error) {
720
+ return throwWithImporter(error, routedParent, parent)
721
+ }
722
+ if (cacheable) state.esm = result
723
+ return result
724
+ }
725
+
726
+ const hooks = registerHooks({
727
+ resolve(specifier, context, nextResolve) {
728
+ // A require() is routed by the `_resolveFilename` wrapper Node calls inside nextResolve; only its conditions are taken from here.
729
+ if (context.conditions.includes('require') && !context.conditions.includes('import')) {
730
+ const previous = requireConditions
731
+ requireConditions = context.conditions
732
+ try {
733
+ return nextResolve(specifier, context)
734
+ } finally {
735
+ requireConditions = previous
736
+ }
737
+ }
738
+ return resolveEsm(specifier, context, nextResolve)
739
+ },
740
+ })
741
+
742
+ const originalFilename = Reflect.get(cjs, '_resolveFilename')
743
+ let delegatedCjs = 0
744
+ const resolveRoutedCjs = (
745
+ request: string, routed: Exclude<ResolutionRoute, { kind: 'native' }>,
746
+ parent: CommonJsParent, main: boolean, options?: CommonJsOptions,
747
+ ): string => {
748
+ const anchor = routed.kind === 'interception' ? routed.entry.declarer : routed.parent
749
+ const synthetic = new cjs(anchor)
750
+ // Late parent assignment preserves Node's require stack without publishing this routing anchor in parent.children.
751
+ synthetic.parent = parent
752
+ synthetic.filename = anchor
753
+ synthetic.paths = routed.kind === 'interception'
754
+ ? packageSearchPaths(routed.entry, request, cjs)
755
+ : cjs._nodeModulePaths(dirname(anchor))
756
+ try {
757
+ return originalFilename.call(cjs, request, synthetic, main, options)
758
+ } catch (error) {
759
+ return throwWithoutCjsAnchor(error, anchor)
760
+ }
761
+ }
762
+ const resolveNativeCjs = (
763
+ request: string, searchPaths: readonly string[], parent: CommonJsParent,
764
+ parentFilename: string, main: boolean, conditions: ReadonlySet<string> | undefined,
765
+ ): string => {
766
+ const synthetic = new cjs(parentFilename)
767
+ if (parent.parent !== undefined) synthetic.parent = parent.parent
768
+ synthetic.filename = parentFilename
769
+ synthetic.paths = [...searchPaths]
770
+ const options = conditions === undefined ? undefined : { conditions }
771
+ return originalFilename.call(cjs, request, synthetic, main, options)
772
+ }
773
+ const resolvePackageImportCjs = (
774
+ target: { specifier: string; parentURL: string }, conditions: Iterable<string>,
775
+ ): string => {
776
+ const state = router.routeUrl(target.specifier, target.parentURL)
777
+ // Node resolves a package-imports target with its ESM package resolver; the public equivalent is the CommonJS resolver from a
778
+ // synthetic module at the anchor with the same conditions, which selects the same `exports` target.
779
+ const resolveFrom = (parentURL: string): string => {
780
+ const anchor = fileURLToPath(parentURL)
781
+ const synthetic = new cjs(anchor)
782
+ synthetic.filename = anchor
783
+ synthetic.paths = cjs._nodeModulePaths(dirname(anchor))
784
+ delegatedCjs++
785
+ try {
786
+ return originalFilename.call(cjs, target.specifier, synthetic, false, { conditions: new Set(conditions) })
787
+ } finally {
788
+ delegatedCjs--
789
+ }
790
+ }
791
+ /* v8 ignore next -- the target manifest was found inside the established profile scope */
792
+ if (state === undefined) return resolveFrom(target.parentURL)
793
+ if (state.route.kind === 'native') return resolveFrom(target.parentURL)
794
+ const route = state.route
795
+ if (route.kind === 'native-after-interception') return resolveFrom(pathToFileURL(route.parent).href)
796
+ return resolveFrom(pathToFileURL(route.entry.declarer).href)
797
+ }
798
+ const wrappedFilename: CommonJsModule['_resolveFilename'] = (request, parent, main, options) => {
799
+ if (delegatedCjs || !parent?.filename || options?.paths !== undefined) {
800
+ return originalFilename.call(cjs, request, parent, main, options)
801
+ }
802
+ const parentFilename = parent.filename
803
+ const cacheable = options?.conditions === undefined
804
+ const routedOptions = options?.conditions === undefined ? undefined : { conditions: options.conditions }
805
+ const state = router.routePath(request, parentFilename, {
806
+ cacheable,
807
+ resolveNative: searchPaths => resolveNativeCjs(request, searchPaths, parent, parentFilename, main, options?.conditions),
808
+ resolveEntry: (entry, after) => {
809
+ delegatedCjs++
810
+ try {
811
+ return resolveRoutedCjs(request, { kind: 'interception', entry, after }, parent, main, routedOptions)
812
+ } finally {
813
+ delegatedCjs--
814
+ }
815
+ },
816
+ })
817
+ if (state === undefined) {
818
+ const scoped = router.hasInterceptionLayerForPath(parentFilename)
819
+ const conditions = options?.conditions ?? (requireConditions === undefined ? defaultCommonJsConditions() : new Set(requireConditions))
820
+ const target = request[0] === '#' && scoped
821
+ ? packageImportsTarget(parentFilename, request, conditions)
822
+ : undefined
823
+ if (target === undefined) return originalFilename.call(cjs, request, parent, main, options)
824
+ return resolvePackageImportCjs(target, conditions)
825
+ }
826
+ if (state.cjs !== undefined) return state.cjs
827
+ const route = state.route
828
+ if (route.kind === 'native') {
829
+ const result = originalFilename.call(cjs, request, parent, main, options)
830
+ if (cacheable) state.cjs = result
831
+ return result
832
+ }
833
+ delegatedCjs++
834
+ try {
835
+ let expected: string
836
+ try {
837
+ expected = resolveRoutedCjs(request, route, parent, main, routedOptions)
838
+ } catch (error) {
839
+ if (route.kind !== 'interception' || !isUnselectedPackageMiss(error)) throw error
840
+ expected = resolveRoutedCjs(
841
+ request, { kind: 'native-after-interception', parent: route.after }, parent, main, routedOptions,
842
+ )
843
+ }
844
+ if (cacheable) state.cjs = expected
845
+ return expected
846
+ } finally {
847
+ delegatedCjs--
848
+ }
849
+ }
850
+ cjs._resolveFilename = wrappedFilename
851
+
852
+ return {
853
+ packageDir(specifier, parentURL) {
854
+ return router.packageDir(specifier, parentURL)
855
+ },
856
+ replace(next) { router.replace(next) },
857
+ dispose() {
858
+ /* v8 ignore else -- interceptions are disposed in reverse installation order */
859
+ if (cjs._resolveFilename === wrappedFilename) cjs._resolveFilename = originalFilename
860
+ hooks.deregister()
861
+ },
862
+ }
863
+ }
864
+
865
+ /**
866
+ * Publish one runtime resolution for Harness-owned Workers.
867
+ * @param resolution - complete package table and profile scope.
868
+ * @returns a disposer restoring the previous thread environment data.
869
+ */
870
+ export function registerWorkerResolution(
871
+ resolution: RuntimeResolution,
872
+ ): () => void {
873
+ const previous = getEnvironmentData(WORKER_RESOLUTION_KEY)
874
+ setEnvironmentData(WORKER_RESOLUTION_KEY, { resolution })
875
+ return () => { setEnvironmentData(WORKER_RESOLUTION_KEY, previous) }
876
+ }