@ontrails/trails 1.0.0-beta.4 → 1.0.0-beta.42

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 (165) hide show
  1. package/CHANGELOG.md +1106 -4
  2. package/README.md +27 -0
  3. package/package.json +31 -7
  4. package/src/app.ts +147 -3
  5. package/src/cli.ts +345 -11
  6. package/src/completions.ts +240 -0
  7. package/src/lifecycle-source-io.ts +33 -0
  8. package/src/load-app-mirror.ts +202 -0
  9. package/src/local-state-io.ts +173 -0
  10. package/src/mcp-app.ts +42 -0
  11. package/src/mcp-options.ts +91 -0
  12. package/src/mcp.ts +8 -0
  13. package/src/project-writes.ts +377 -0
  14. package/src/regrade/config.ts +152 -0
  15. package/src/regrade/history.ts +430 -0
  16. package/src/regrade/live-api-preserve.ts +8 -0
  17. package/src/regrade/plan-artifact.ts +285 -0
  18. package/src/release/bindings.ts +39 -0
  19. package/src/release/check.ts +844 -0
  20. package/src/release/config.ts +63 -0
  21. package/src/release/contract-facts.ts +425 -0
  22. package/src/release/index.ts +142 -0
  23. package/src/release/lock-roundtrip-smoke.ts +230 -0
  24. package/src/release/native-bun-publish.ts +651 -0
  25. package/src/release/native-bun-registry.ts +765 -0
  26. package/src/release/notes-cli.ts +171 -0
  27. package/src/release/notes.ts +390 -0
  28. package/src/release/pack-coherence.ts +455 -0
  29. package/src/release/packed-artifacts-smoke.ts +236 -0
  30. package/src/release/policy.ts +1687 -0
  31. package/src/release/semver.ts +104 -0
  32. package/src/release/smoke.ts +56 -0
  33. package/src/release/wayfinder-dogfood-smoke.ts +760 -0
  34. package/src/retired-topo-command.ts +36 -0
  35. package/src/run-adapter-check.ts +76 -0
  36. package/src/run-collision.ts +126 -0
  37. package/src/run-completions-install.ts +179 -0
  38. package/src/run-example.ts +149 -0
  39. package/src/run-examples.ts +148 -0
  40. package/src/run-quiet.ts +75 -0
  41. package/src/run-release-check.ts +74 -0
  42. package/src/run-schema.ts +74 -0
  43. package/src/run-trace.ts +273 -0
  44. package/src/run-warden.ts +39 -0
  45. package/src/run-watch.ts +432 -0
  46. package/src/run-wayfind-outline.ts +170 -0
  47. package/src/scaffold-version-sync.ts +183 -0
  48. package/src/scaffold-versions.generated.ts +12 -0
  49. package/src/trails/adapter-check.ts +244 -0
  50. package/src/trails/add-surface.ts +99 -45
  51. package/src/trails/add-trail.ts +84 -37
  52. package/src/trails/add-verify.ts +100 -30
  53. package/src/trails/compile.ts +58 -0
  54. package/src/trails/completions-complete.ts +165 -0
  55. package/src/trails/completions.ts +47 -0
  56. package/src/trails/create-adapter.ts +785 -0
  57. package/src/trails/create-scaffold.ts +401 -106
  58. package/src/trails/create-versions.ts +62 -0
  59. package/src/trails/create.ts +186 -72
  60. package/src/trails/deprecate.ts +59 -0
  61. package/src/trails/dev-clean.ts +82 -0
  62. package/src/trails/dev-reset.ts +50 -0
  63. package/src/trails/dev-stats.ts +72 -0
  64. package/src/trails/dev-support.ts +360 -0
  65. package/src/trails/doctor.ts +77 -0
  66. package/src/trails/draft-promote.ts +949 -0
  67. package/src/trails/guide.ts +70 -68
  68. package/src/trails/load-app.ts +1123 -15
  69. package/src/trails/operator-context.ts +66 -0
  70. package/src/trails/project.ts +17 -3
  71. package/src/trails/regrade.ts +3091 -0
  72. package/src/trails/release-check.ts +105 -0
  73. package/src/trails/release-smoke.ts +49 -0
  74. package/src/trails/revise.ts +53 -0
  75. package/src/trails/root-dir.ts +21 -0
  76. package/src/trails/run-example.ts +475 -0
  77. package/src/trails/run-examples.ts +129 -0
  78. package/src/trails/run.ts +434 -0
  79. package/src/trails/scaffold-json.ts +58 -0
  80. package/src/trails/survey.ts +877 -214
  81. package/src/trails/topo-activation.ts +14 -0
  82. package/src/trails/topo-constants.ts +2 -0
  83. package/src/trails/topo-history.ts +47 -0
  84. package/src/trails/topo-output-schemas.ts +259 -0
  85. package/src/trails/topo-pin.ts +38 -0
  86. package/src/trails/topo-read-support.ts +368 -0
  87. package/src/trails/topo-reports.ts +809 -0
  88. package/src/trails/topo-store-support.ts +325 -0
  89. package/src/trails/topo-support.ts +220 -0
  90. package/src/trails/topo-unpin.ts +61 -0
  91. package/src/trails/topo.ts +92 -0
  92. package/src/trails/validate.ts +27 -0
  93. package/src/trails/version-lifecycle-support.ts +936 -0
  94. package/src/trails/warden-guide.ts +134 -0
  95. package/src/trails/warden.ts +198 -58
  96. package/src/trails/wayfind-outline.ts +876 -0
  97. package/src/trails/wayfind.ts +1053 -0
  98. package/src/versions.ts +31 -0
  99. package/.turbo/turbo-build.log +0 -1
  100. package/.turbo/turbo-lint.log +0 -3
  101. package/.turbo/turbo-typecheck.log +0 -1
  102. package/__tests__/examples.test.ts +0 -6
  103. package/dist/bin/trails.d.ts +0 -3
  104. package/dist/bin/trails.d.ts.map +0 -1
  105. package/dist/bin/trails.js +0 -4
  106. package/dist/bin/trails.js.map +0 -1
  107. package/dist/src/app.d.ts +0 -2
  108. package/dist/src/app.d.ts.map +0 -1
  109. package/dist/src/app.js +0 -11
  110. package/dist/src/app.js.map +0 -1
  111. package/dist/src/clack.d.ts +0 -9
  112. package/dist/src/clack.d.ts.map +0 -1
  113. package/dist/src/clack.js +0 -84
  114. package/dist/src/clack.js.map +0 -1
  115. package/dist/src/cli.d.ts +0 -2
  116. package/dist/src/cli.d.ts.map +0 -1
  117. package/dist/src/cli.js +0 -13
  118. package/dist/src/cli.js.map +0 -1
  119. package/dist/src/trails/add-surface.d.ts +0 -13
  120. package/dist/src/trails/add-surface.d.ts.map +0 -1
  121. package/dist/src/trails/add-surface.js +0 -88
  122. package/dist/src/trails/add-surface.js.map +0 -1
  123. package/dist/src/trails/add-trail.d.ts +0 -10
  124. package/dist/src/trails/add-trail.d.ts.map +0 -1
  125. package/dist/src/trails/add-trail.js +0 -77
  126. package/dist/src/trails/add-trail.js.map +0 -1
  127. package/dist/src/trails/add-verify.d.ts +0 -10
  128. package/dist/src/trails/add-verify.d.ts.map +0 -1
  129. package/dist/src/trails/add-verify.js +0 -67
  130. package/dist/src/trails/add-verify.js.map +0 -1
  131. package/dist/src/trails/create-scaffold.d.ts +0 -15
  132. package/dist/src/trails/create-scaffold.d.ts.map +0 -1
  133. package/dist/src/trails/create-scaffold.js +0 -288
  134. package/dist/src/trails/create-scaffold.js.map +0 -1
  135. package/dist/src/trails/create.d.ts +0 -22
  136. package/dist/src/trails/create.d.ts.map +0 -1
  137. package/dist/src/trails/create.js +0 -121
  138. package/dist/src/trails/create.js.map +0 -1
  139. package/dist/src/trails/guide.d.ts +0 -11
  140. package/dist/src/trails/guide.d.ts.map +0 -1
  141. package/dist/src/trails/guide.js +0 -80
  142. package/dist/src/trails/guide.js.map +0 -1
  143. package/dist/src/trails/load-app.d.ts +0 -4
  144. package/dist/src/trails/load-app.d.ts.map +0 -1
  145. package/dist/src/trails/load-app.js +0 -24
  146. package/dist/src/trails/load-app.js.map +0 -1
  147. package/dist/src/trails/project.d.ts +0 -8
  148. package/dist/src/trails/project.d.ts.map +0 -1
  149. package/dist/src/trails/project.js +0 -43
  150. package/dist/src/trails/project.js.map +0 -1
  151. package/dist/src/trails/survey.d.ts +0 -31
  152. package/dist/src/trails/survey.d.ts.map +0 -1
  153. package/dist/src/trails/survey.js +0 -221
  154. package/dist/src/trails/survey.js.map +0 -1
  155. package/dist/src/trails/warden.d.ts +0 -19
  156. package/dist/src/trails/warden.d.ts.map +0 -1
  157. package/dist/src/trails/warden.js +0 -88
  158. package/dist/src/trails/warden.js.map +0 -1
  159. package/dist/tsconfig.tsbuildinfo +0 -1
  160. package/src/__tests__/create.test.ts +0 -349
  161. package/src/__tests__/guide.test.ts +0 -91
  162. package/src/__tests__/load-app.test.ts +0 -15
  163. package/src/__tests__/survey.test.ts +0 -159
  164. package/src/__tests__/warden.test.ts +0 -74
  165. package/tsconfig.json +0 -9
@@ -1,37 +1,1145 @@
1
- import { isAbsolute, resolve } from 'node:path';
2
- import { pathToFileURL } from 'node:url';
1
+ import {
2
+ existsSync,
3
+ readdirSync,
4
+ readFileSync,
5
+ realpathSync,
6
+ statSync,
7
+ symlinkSync,
8
+ } from 'node:fs';
9
+ import {
10
+ dirname,
11
+ extname,
12
+ isAbsolute,
13
+ join,
14
+ relative,
15
+ resolve,
16
+ } from 'node:path';
17
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
18
 
19
+ import {
20
+ deriveSafePath,
21
+ isTrailsError,
22
+ listWorkspacePackages,
23
+ PermissionError,
24
+ Result,
25
+ ValidationError,
26
+ } from '@ontrails/core';
4
27
  import type { Topo } from '@ontrails/core';
28
+ import { resolveTrailsOverlays } from '@ontrails/adapter-kit';
29
+ import type { TopoGraphOverlayRegistration } from '@ontrails/topography';
30
+ import { findAppModule } from '@ontrails/cli';
31
+
32
+ import {
33
+ createLoadAppMirrorRootPath,
34
+ ensureLoadAppMirrorDirectory,
35
+ LOAD_APP_MIRROR_ENTRY_PREFIX,
36
+ LOAD_APP_MIRROR_PARENT_DIRNAME,
37
+ removeLoadAppMirrorRootQuietly,
38
+ resolveLoadAppMirrorFilePath,
39
+ writeLoadAppMirrorFile,
40
+ } from '../load-app-mirror.js';
5
41
 
6
42
  const URL_SCHEME = /^[a-zA-Z][a-zA-Z\d+.-]*:/;
7
43
 
8
- /** Resolve a module path from cwd so CLI defaults behave like shell paths. */
9
- const resolveModuleSpecifier = (modulePath: string, cwd: string): string => {
10
- if (URL_SCHEME.test(modulePath)) {
11
- return modulePath;
44
+ type TranspilerLoader = 'ts' | 'tsx' | 'js' | 'jsx';
45
+
46
+ /** Extension → Bun.Transpiler loader, so JSX-bearing files parse correctly. */
47
+ const LOADER_BY_EXTENSION: Record<string, TranspilerLoader> = {
48
+ '.cjs': 'js',
49
+ '.cts': 'ts',
50
+ '.js': 'js',
51
+ '.jsx': 'jsx',
52
+ '.mjs': 'js',
53
+ '.mts': 'ts',
54
+ '.ts': 'ts',
55
+ '.tsx': 'tsx',
56
+ };
57
+
58
+ const SCANNABLE_EXTENSIONS = new Set(Object.keys(LOADER_BY_EXTENSION));
59
+
60
+ const TRANSPILER_CACHE = new Map<TranspilerLoader, Bun.Transpiler>();
61
+
62
+ const getImportScanner = (loader: TranspilerLoader): Bun.Transpiler => {
63
+ const cached = TRANSPILER_CACHE.get(loader);
64
+ if (cached !== undefined) {
65
+ return cached;
66
+ }
67
+ const scanner = new Bun.Transpiler({ loader });
68
+ TRANSPILER_CACHE.set(loader, scanner);
69
+ return scanner;
70
+ };
71
+
72
+ /**
73
+ * Mirror roots kept alive for the lifetime of the process.
74
+ *
75
+ * @remarks
76
+ * A fresh-loaded module may expose functions whose deferred relative imports
77
+ * are resolved only when those functions run (for example inside a trail's
78
+ * `implementation`). If we deleted the mirror tree immediately after the initial
79
+ * `import()` resolved, those later resolutions would hit an ENOENT. We keep
80
+ * the mirrors on disk and clean them up once, on process exit.
81
+ */
82
+ const ACTIVE_MIRROR_ROOTS = new Set<string>();
83
+ const RETAINED_MIRROR_ROOTS = new Set<string>();
84
+
85
+ const cleanupAllMirrorRoots = (): void => {
86
+ for (const root of [...ACTIVE_MIRROR_ROOTS, ...RETAINED_MIRROR_ROOTS]) {
87
+ removeLoadAppMirrorRootQuietly(root);
88
+ }
89
+ ACTIVE_MIRROR_ROOTS.clear();
90
+ RETAINED_MIRROR_ROOTS.clear();
91
+ };
92
+
93
+ const mirrorCleanup = (() => {
94
+ let registered = false;
95
+ return {
96
+ ensureRegistered(): void {
97
+ if (registered) {
98
+ return;
99
+ }
100
+ registered = true;
101
+ process.once('exit', cleanupAllMirrorRoots);
102
+ },
103
+ };
104
+ })();
105
+
106
+ const ensureMirrorCleanupHook = (): void => {
107
+ mirrorCleanup.ensureRegistered();
108
+ };
109
+
110
+ /**
111
+ * Retain a fresh-import mirror for the lifetime of the process. A previously
112
+ * returned `loadApp` result may hold deferred relative `import()` calls whose
113
+ * resolution requires the mirror directory to still exist, so we cannot prune
114
+ * these by age without risking ENOENT in long-lived sessions (dev server,
115
+ * survey polling, concurrent fresh loads). Cleanup happens once on process
116
+ * exit via `cleanupAllMirrorRoots`.
117
+ */
118
+ const retainMirrorRoot = (mirrorRoot: string): void => {
119
+ if (RETAINED_MIRROR_ROOTS.has(mirrorRoot)) {
120
+ return;
12
121
  }
122
+ RETAINED_MIRROR_ROOTS.add(mirrorRoot);
123
+ ensureMirrorCleanupHook();
124
+ };
125
+
126
+ const acquireMirrorLease = (mirrorRoot: string): (() => void) => {
127
+ ACTIVE_MIRROR_ROOTS.add(mirrorRoot);
128
+ ensureMirrorCleanupHook();
129
+
130
+ let released = false;
131
+
132
+ return () => {
133
+ if (released) {
134
+ return;
135
+ }
136
+
137
+ released = true;
138
+ ACTIVE_MIRROR_ROOTS.delete(mirrorRoot);
139
+ removeLoadAppMirrorRootQuietly(mirrorRoot);
140
+ };
141
+ };
13
142
 
143
+ const resolveUrlModulePath = (modulePath: string): string => {
144
+ const url = new URL(modulePath);
145
+ return url.protocol === 'file:' ? fileURLToPath(url) : modulePath;
146
+ };
147
+
148
+ const resolveFilesystemModulePath = (
149
+ modulePath: string,
150
+ cwd: string
151
+ ): string => {
14
152
  const absolutePath = isAbsolute(modulePath)
15
153
  ? modulePath
16
154
  : resolve(cwd, modulePath);
17
- return pathToFileURL(absolutePath).href;
155
+ if (!absolutePath.endsWith('.js') || existsSync(absolutePath)) {
156
+ return absolutePath;
157
+ }
158
+
159
+ const tsPath = absolutePath.replace(/\.js$/, '.ts');
160
+ return existsSync(tsPath) ? tsPath : absolutePath;
18
161
  };
19
162
 
20
- /** Load a Topo export from a module path relative to cwd. */
21
- export const loadApp = async (
163
+ const trustBoundaryError = (reason: string): PermissionError =>
164
+ new PermissionError(
165
+ `Refusing to load an app module outside the workspace trust boundary (${reason}). Use a workspace-relative module path, or pass trustedModulePath: true from trusted code.`
166
+ );
167
+
168
+ const asError = (error: unknown): Error =>
169
+ error instanceof Error ? error : new Error(String(error));
170
+
171
+ const toLoadAppError = (error: unknown): Error => {
172
+ if (isTrailsError(error)) {
173
+ return error;
174
+ }
175
+ const cause = asError(error);
176
+ return new ValidationError(`Failed to load app module: ${cause.message}`, {
177
+ cause,
178
+ context: { detail: cause.message },
179
+ });
180
+ };
181
+
182
+ const isPathInside = (root: string, target: string): boolean => {
183
+ const candidate = relative(root, target);
184
+ return (
185
+ candidate === '' || (!candidate.startsWith('..') && !isAbsolute(candidate))
186
+ );
187
+ };
188
+
189
+ const realpathIfPresent = (path: string): string | undefined => {
190
+ try {
191
+ return realpathSync(path);
192
+ } catch {
193
+ return undefined;
194
+ }
195
+ };
196
+
197
+ const ensureRealPathInsideCwd = (
198
+ resolvedModulePath: string,
199
+ cwd: string
200
+ ): string => {
201
+ const realRoot = realpathIfPresent(cwd);
202
+ const realModule = realpathIfPresent(resolvedModulePath);
203
+ if (
204
+ realRoot !== undefined &&
205
+ realModule !== undefined &&
206
+ !isPathInside(realRoot, realModule)
207
+ ) {
208
+ throw trustBoundaryError('symlink_escape');
209
+ }
210
+
211
+ return resolvedModulePath;
212
+ };
213
+
214
+ /** Resolve a caller-trusted module path using the legacy escape hatch policy. */
215
+ const resolveTrustedModulePath = (modulePath: string, cwd: string): string =>
216
+ URL_SCHEME.test(modulePath)
217
+ ? resolveUrlModulePath(modulePath)
218
+ : resolveFilesystemModulePath(modulePath, cwd);
219
+
220
+ /**
221
+ * Resolve the default app module path inside cwd.
222
+ *
223
+ * @remarks
224
+ * CLI and trail callers accept user-supplied module specifiers, so the default
225
+ * policy is deliberately narrower than `import()` itself: no URL schemes, no
226
+ * absolute paths, and no parent traversal. Internal callers that intentionally
227
+ * load a path outside cwd must opt into `trustedModulePath`.
228
+ */
229
+ const resolveContainedModulePath = (
22
230
  modulePath: string,
23
231
  cwd: string
24
- ): Promise<Topo> => {
25
- const mod = (await import(resolveModuleSpecifier(modulePath, cwd))) as Record<
232
+ ): string => {
233
+ if (URL_SCHEME.test(modulePath)) {
234
+ throw trustBoundaryError('url_scheme');
235
+ }
236
+ if (isAbsolute(modulePath)) {
237
+ throw trustBoundaryError('absolute_path');
238
+ }
239
+
240
+ const safePath = deriveSafePath(cwd, modulePath);
241
+ if (safePath.isErr()) {
242
+ throw trustBoundaryError('parent_escape');
243
+ }
244
+
245
+ return ensureRealPathInsideCwd(
246
+ resolveFilesystemModulePath(safePath.value, cwd),
247
+ cwd
248
+ );
249
+ };
250
+
251
+ interface LoadAppTrustOptions {
252
+ readonly trustedModulePath?: boolean | undefined;
253
+ }
254
+
255
+ const resolveLoadAppModulePath = (
256
+ modulePath: string,
257
+ cwd: string,
258
+ options: LoadAppTrustOptions = {}
259
+ ): string =>
260
+ options.trustedModulePath === true
261
+ ? resolveTrustedModulePath(modulePath, cwd)
262
+ : resolveContainedModulePath(modulePath, cwd);
263
+
264
+ const findWorkspaceRelativeAppModule = (cwd: string): string => {
265
+ const discovered = findAppModule(cwd);
266
+ return isAbsolute(discovered) ? relative(cwd, discovered) : discovered;
267
+ };
268
+
269
+ const isLocalFilesystemImport = (importPath: string): boolean =>
270
+ importPath.startsWith('.') ||
271
+ importPath.startsWith('/') ||
272
+ importPath.startsWith('file:');
273
+
274
+ interface PackageJson {
275
+ readonly exports?: unknown;
276
+ readonly imports?: unknown;
277
+ readonly main?: unknown;
278
+ readonly module?: unknown;
279
+ readonly name?: unknown;
280
+ readonly type?: unknown;
281
+ readonly workspaces?: unknown;
282
+ }
283
+
284
+ type NamedPackageJson = PackageJson & { readonly name: string };
285
+
286
+ const readPackageJson = (packagePath: string): PackageJson | undefined => {
287
+ try {
288
+ return JSON.parse(readFileSync(packagePath, 'utf8')) as PackageJson;
289
+ } catch {
290
+ return undefined;
291
+ }
292
+ };
293
+
294
+ const readPackageName = (packagePath: string): string | undefined => {
295
+ const parsed = readPackageJson(packagePath);
296
+ return typeof parsed?.name === 'string' && parsed.name.length > 0
297
+ ? parsed.name
298
+ : undefined;
299
+ };
300
+
301
+ const findNearestPackageName = (directoryPath: string): string | undefined => {
302
+ let current = directoryPath;
303
+ while (true) {
304
+ const name = readPackageName(join(current, 'package.json'));
305
+ if (name !== undefined) {
306
+ return name;
307
+ }
308
+
309
+ const parent = dirname(current);
310
+ if (parent === current) {
311
+ return undefined;
312
+ }
313
+ current = parent;
314
+ }
315
+ };
316
+
317
+ const isPackageLocalImport = (
318
+ importerPath: string,
319
+ importPath: string
320
+ ): boolean => {
321
+ if (importPath.startsWith('#')) {
322
+ return true;
323
+ }
324
+
325
+ const packageName = findNearestPackageName(dirname(importerPath));
326
+ return (
327
+ packageName !== undefined &&
328
+ (importPath === packageName || importPath.startsWith(`${packageName}/`))
329
+ );
330
+ };
331
+
332
+ const isScannableModule = (modulePath: string): boolean =>
333
+ SCANNABLE_EXTENSIONS.has(extname(modulePath));
334
+
335
+ const readDirectoryEntries = (directoryPath: string): readonly string[] => {
336
+ try {
337
+ return readdirSync(directoryPath);
338
+ } catch {
339
+ return [];
340
+ }
341
+ };
342
+
343
+ const safeStat = (
344
+ entryPath: string
345
+ ): ReturnType<typeof statSync> | undefined => {
346
+ try {
347
+ return statSync(entryPath);
348
+ } catch {
349
+ return undefined;
350
+ }
351
+ };
352
+
353
+ const resolveImportedModulePath = (
354
+ importerPath: string,
355
+ importPath: string
356
+ ): string => {
357
+ const resolved = import.meta.resolve(
358
+ importPath,
359
+ pathToFileURL(importerPath).href
360
+ );
361
+ const literalPath = resolveFilesystemModulePath(
362
+ fileURLToPath(resolved),
363
+ dirname(importerPath)
364
+ );
365
+ if (safeStat(literalPath)?.isFile()) {
366
+ return literalPath;
367
+ }
368
+
369
+ // `import.meta.resolve` joins relative specifiers without probing the
370
+ // filesystem, so extensionless imports point at paths that do not exist even
371
+ // though Bun resolves them at runtime. Fall back to the runtime resolver so
372
+ // runtime-valid apps stay fresh-loadable.
373
+ try {
374
+ return resolveFilesystemModulePath(
375
+ Bun.resolveSync(importPath, dirname(importerPath)),
376
+ dirname(importerPath)
377
+ );
378
+ } catch (error) {
379
+ const extensionlessHint =
380
+ extname(importPath) === ''
381
+ ? ' Extensionless relative imports must match a .ts/.tsx/.js module or a directory index.'
382
+ : '';
383
+ throw new ValidationError(
384
+ `Cannot resolve import "${importPath}" from "${importerPath}" while mirroring the app for fresh loading: "${literalPath}" does not exist and runtime resolution found no match. Fix the specifier or add the missing file.${extensionlessHint}`,
385
+ { cause: asError(error), context: { importPath, importerPath } }
386
+ );
387
+ }
388
+ };
389
+
390
+ interface WorkspacePackage {
391
+ readonly name: string;
392
+ readonly packageJson: PackageJson;
393
+ readonly packageRoot: string;
394
+ }
395
+
396
+ const readWorkspacePackages = (cwd: string): readonly WorkspacePackage[] =>
397
+ listWorkspacePackages<NamedPackageJson>(cwd).map((workspacePackage) => ({
398
+ name: workspacePackage.manifest.name,
399
+ packageJson: workspacePackage.manifest,
400
+ packageRoot: workspacePackage.packageRoot,
401
+ }));
402
+
403
+ const parsePackageSpecifier = (
404
+ importPath: string
405
+ ): { packageName: string; subpath: string } | null => {
406
+ if (URL_SCHEME.test(importPath)) {
407
+ return null;
408
+ }
409
+ if (importPath.startsWith('.') || importPath.startsWith('#')) {
410
+ return null;
411
+ }
412
+ const segments = importPath.split('/');
413
+ const [firstSegment, secondSegment] = segments;
414
+ if (firstSegment?.startsWith('@')) {
415
+ const scope = firstSegment;
416
+ const name = secondSegment;
417
+ if (name === undefined) {
418
+ return null;
419
+ }
420
+ const packageName = `${scope}/${name}`;
421
+ const rest = segments.slice(2).join('/');
422
+ return { packageName, subpath: rest.length > 0 ? `./${rest}` : '.' };
423
+ }
424
+ const [name] = segments;
425
+ if (name === undefined || name.length === 0) {
426
+ return null;
427
+ }
428
+ const rest = segments.slice(1).join('/');
429
+ return { packageName: name, subpath: rest.length > 0 ? `./${rest}` : '.' };
430
+ };
431
+
432
+ const resolveConditionalExportTarget = (
433
+ target: unknown
434
+ ): string | undefined => {
435
+ if (typeof target === 'string') {
436
+ return target;
437
+ }
438
+ if (typeof target !== 'object' || target === null || Array.isArray(target)) {
439
+ return undefined;
440
+ }
441
+ const record = target as Record<string, unknown>;
442
+ return (
443
+ resolveConditionalExportTarget(record['import']) ??
444
+ resolveConditionalExportTarget(record['default']) ??
445
+ resolveConditionalExportTarget(record['bun']) ??
446
+ resolveConditionalExportTarget(record['node'])
447
+ );
448
+ };
449
+
450
+ const resolveExportTarget = (
451
+ packageJson: PackageJson,
452
+ subpath: string
453
+ ): string | undefined => {
454
+ const { exports } = packageJson;
455
+ if (exports === undefined) {
456
+ if (subpath === '.') {
457
+ if (typeof packageJson.module === 'string') {
458
+ return packageJson.module;
459
+ }
460
+ if (typeof packageJson.main === 'string') {
461
+ return packageJson.main;
462
+ }
463
+ return './src/index.ts';
464
+ }
465
+ return subpath;
466
+ }
467
+ if (typeof exports === 'string' || Array.isArray(exports)) {
468
+ return subpath === '.'
469
+ ? resolveConditionalExportTarget(exports)
470
+ : undefined;
471
+ }
472
+ if (typeof exports !== 'object' || exports === null) {
473
+ return undefined;
474
+ }
475
+ return resolveConditionalExportTarget(
476
+ (exports as Record<string, unknown>)[subpath]
477
+ );
478
+ };
479
+
480
+ interface WorkspacePackageResolution {
481
+ readonly modulePath: string;
482
+ readonly packageName: string;
483
+ readonly packageRoot: string;
484
+ }
485
+
486
+ const resolveWorkspacePackageImport = (
487
+ importPath: string,
488
+ cwd: string
489
+ ): WorkspacePackageResolution | null => {
490
+ const parsed = parsePackageSpecifier(importPath);
491
+ if (parsed === null) {
492
+ return null;
493
+ }
494
+ const workspacePackage = readWorkspacePackages(cwd).find(
495
+ (candidate) => candidate.name === parsed.packageName
496
+ );
497
+ if (workspacePackage === undefined) {
498
+ return null;
499
+ }
500
+ const target = resolveExportTarget(
501
+ workspacePackage.packageJson,
502
+ parsed.subpath
503
+ );
504
+ if (target === undefined || !target.startsWith('.')) {
505
+ return null;
506
+ }
507
+ const targetPath = deriveSafePath(workspacePackage.packageRoot, target);
508
+ if (targetPath.isErr()) {
509
+ return null;
510
+ }
511
+ return {
512
+ modulePath: resolveFilesystemModulePath(
513
+ ensureRealPathInsideCwd(targetPath.value, cwd),
514
+ workspacePackage.packageRoot
515
+ ),
516
+ packageName: workspacePackage.name,
517
+ packageRoot: workspacePackage.packageRoot,
518
+ };
519
+ };
520
+
521
+ const findPackageRootForName = (
522
+ directoryPath: string,
523
+ packageName: string
524
+ ): string | null => {
525
+ let current = directoryPath;
526
+ while (true) {
527
+ const packagePath = join(current, 'package.json');
528
+ if (readPackageName(packagePath) === packageName) {
529
+ return current;
530
+ }
531
+
532
+ const parent = dirname(current);
533
+ if (parent === current) {
534
+ return null;
535
+ }
536
+ current = parent;
537
+ }
538
+ };
539
+
540
+ interface ExternalPackageResolution {
541
+ readonly packageName: string;
542
+ readonly packageRoot: string;
543
+ }
544
+
545
+ const resolveExternalPackageImport = (
546
+ importerPath: string,
547
+ importPath: string
548
+ ): ExternalPackageResolution | null => {
549
+ const parsed = parsePackageSpecifier(importPath);
550
+ if (parsed === null) {
551
+ return null;
552
+ }
553
+ let resolved: string;
554
+ try {
555
+ resolved = import.meta.resolve(
556
+ importPath,
557
+ pathToFileURL(importerPath).href
558
+ );
559
+ } catch {
560
+ return null;
561
+ }
562
+ if (!resolved.startsWith('file:')) {
563
+ return null;
564
+ }
565
+ const packageRoot = findPackageRootForName(
566
+ dirname(fileURLToPath(resolved)),
567
+ parsed.packageName
568
+ );
569
+ return packageRoot === null
570
+ ? null
571
+ : { packageName: parsed.packageName, packageRoot };
572
+ };
573
+
574
+ type MirrorImportResolution =
575
+ | {
576
+ readonly kind: 'module';
577
+ readonly modulePath: string;
578
+ }
579
+ | {
580
+ readonly kind: 'external-package';
581
+ readonly packageName: string;
582
+ readonly packageRoot: string;
583
+ }
584
+ | {
585
+ readonly kind: 'workspace-package';
586
+ readonly modulePath: string;
587
+ readonly packageName: string;
588
+ readonly packageRoot: string;
589
+ };
590
+
591
+ const resolveMirrorImport = (
592
+ importerPath: string,
593
+ importPath: string,
594
+ cwd: string
595
+ ): MirrorImportResolution | null => {
596
+ if (
597
+ isLocalFilesystemImport(importPath) ||
598
+ isPackageLocalImport(importerPath, importPath)
599
+ ) {
600
+ return {
601
+ kind: 'module',
602
+ modulePath: resolveImportedModulePath(importerPath, importPath),
603
+ };
604
+ }
605
+
606
+ const workspacePackage = resolveWorkspacePackageImport(importPath, cwd);
607
+ if (workspacePackage !== null) {
608
+ return { kind: 'workspace-package', ...workspacePackage };
609
+ }
610
+
611
+ const externalPackage = resolveExternalPackageImport(
612
+ importerPath,
613
+ importPath
614
+ );
615
+ return externalPackage === null
616
+ ? null
617
+ : { kind: 'external-package', ...externalPackage };
618
+ };
619
+
620
+ const collectImportedModuleResolutions = (
621
+ modulePath: string,
622
+ source: string,
623
+ cwd: string
624
+ ): readonly MirrorImportResolution[] => {
625
+ const extension = extname(modulePath);
626
+ const loader = LOADER_BY_EXTENSION[extension];
627
+ if (loader === undefined) {
628
+ return [];
629
+ }
630
+
631
+ return getImportScanner(loader)
632
+ .scanImports(source)
633
+ .map((entry) => entry.path)
634
+ .map((importPath) => resolveMirrorImport(modulePath, importPath, cwd))
635
+ .filter(
636
+ (resolution): resolution is MirrorImportResolution => resolution !== null
637
+ );
638
+ };
639
+
640
+ const copyFileToMirror = async (
641
+ sourcePath: string,
642
+ mirrorRoot: string,
643
+ copied: Set<string>
644
+ ): Promise<void> => {
645
+ if (copied.has(sourcePath)) {
646
+ return;
647
+ }
648
+ copied.add(sourcePath);
649
+
650
+ const written = await writeLoadAppMirrorFile(sourcePath, mirrorRoot);
651
+ if (written.isErr()) {
652
+ throw written.error;
653
+ }
654
+ };
655
+
656
+ /**
657
+ * Directory basenames that are never worth mirroring.
658
+ *
659
+ * @remarks
660
+ * These directories are excluded because they can be large and are never
661
+ * sources of resolvable imports — they hold VCS metadata, package installs,
662
+ * prior mirror artifacts, or build/tooling output that module resolution
663
+ * should not touch.
664
+ */
665
+ const MIRROR_SKIP_DIRECTORIES = new Set([
666
+ '.cache',
667
+ '.git',
668
+ '.next',
669
+ '.nuxt',
670
+ '.output',
671
+ '.svelte-kit',
672
+ '.trails-tmp',
673
+ '.turbo',
674
+ 'build',
675
+ 'coverage',
676
+ 'dist',
677
+ 'node_modules',
678
+ ]);
679
+
680
+ /**
681
+ * Recursively copy every regular file inside `directoryPath` into the
682
+ * mirror, skipping well-known heavy directories.
683
+ *
684
+ * @remarks
685
+ * `Bun.Transpiler#scanImports` only surfaces statically analyzable import
686
+ * specifiers. Computed dynamic imports such as `import(\`./${name}.ts\`)`
687
+ * never appear, so their targets would otherwise be missing from the
688
+ * mirror. Shadowing each directory touched by the static walk with its
689
+ * full subtree keeps those sibling modules resolvable under the mirror
690
+ * root at runtime without pulling in package installs or nested mirror
691
+ * artifacts.
692
+ */
693
+ /**
694
+ * Age threshold (ms) above which a mirror entry in `.trails-tmp/` is
695
+ * considered stale and safe to remove opportunistically.
696
+ *
697
+ * @remarks
698
+ * Fresh loads complete in seconds. Anything older than 10 minutes is almost
699
+ * certainly left over from a crashed or signal-killed process. We intentionally
700
+ * avoid registering SIGTERM/SIGINT handlers here because that would risk
701
+ * clobbering host-app signal handlers (and still wouldn't rescue SIGKILL).
702
+ * Opportunistic cleanup is self-healing across crashes from any cause.
703
+ */
704
+ const STALE_MIRROR_THRESHOLD_MS = 10 * 60 * 1000;
705
+
706
+ const isStaleMirrorEntry = (entryPath: string, now: number): boolean => {
707
+ if (
708
+ ACTIVE_MIRROR_ROOTS.has(entryPath) ||
709
+ RETAINED_MIRROR_ROOTS.has(entryPath)
710
+ ) {
711
+ return false;
712
+ }
713
+ const entryStat = safeStat(entryPath);
714
+ if (entryStat === undefined) {
715
+ return false;
716
+ }
717
+ const mtimeMs = Number(entryStat.mtimeMs);
718
+ return now - mtimeMs >= STALE_MIRROR_THRESHOLD_MS;
719
+ };
720
+
721
+ const removeStaleMirrorEntry = (entryPath: string): void => {
722
+ /*
723
+ * Another concurrent load may own it. Safe to ignore — the next sweep
724
+ * will retry.
725
+ */
726
+ removeLoadAppMirrorRootQuietly(entryPath);
727
+ };
728
+
729
+ /**
730
+ * Best-effort removal of stale mirror directories left by previous (crashed or
731
+ * signal-killed) processes. Called before creating a new mirror root.
732
+ */
733
+ const cleanupStaleMirrorRoots = (mirrorParent: string): void => {
734
+ const entries = readDirectoryEntries(mirrorParent);
735
+ if (entries.length === 0) {
736
+ return;
737
+ }
738
+ const now = Date.now();
739
+ for (const entry of entries) {
740
+ if (!entry.startsWith(LOAD_APP_MIRROR_ENTRY_PREFIX)) {
741
+ continue;
742
+ }
743
+ const entryPath = join(mirrorParent, entry);
744
+ if (isStaleMirrorEntry(entryPath, now)) {
745
+ removeStaleMirrorEntry(entryPath);
746
+ }
747
+ }
748
+ };
749
+
750
+ const freshMirrorRootPath = (cwd: string): string => {
751
+ const mirrorParent = join(cwd, LOAD_APP_MIRROR_PARENT_DIRNAME);
752
+ cleanupStaleMirrorRoots(mirrorParent);
753
+ return createLoadAppMirrorRootPath(cwd);
754
+ };
755
+
756
+ interface MirrorWalkContext {
757
+ readonly cwd: string;
758
+ readonly mirrorRoot: string;
759
+ readonly copied: Set<string>;
760
+ readonly visitedDirectories: Set<string>;
761
+ readonly linkedPackageNames: Set<string>;
762
+ }
763
+
764
+ type DirectoryEntryKind = 'directory' | 'file' | 'skip';
765
+
766
+ const classifyDirectoryEntry = (
767
+ entry: string,
768
+ entryPath: string
769
+ ): DirectoryEntryKind => {
770
+ const entryStat = safeStat(entryPath);
771
+ if (entryStat === undefined) {
772
+ return 'skip';
773
+ }
774
+ if (entryStat.isDirectory()) {
775
+ return MIRROR_SKIP_DIRECTORIES.has(entry) ? 'skip' : 'directory';
776
+ }
777
+ return entryStat.isFile() ? 'file' : 'skip';
778
+ };
779
+
780
+ const copyDirectoryTreeToMirror = async (
781
+ directoryPath: string,
782
+ context: MirrorWalkContext
783
+ ): Promise<void> => {
784
+ if (context.visitedDirectories.has(directoryPath)) {
785
+ return;
786
+ }
787
+ context.visitedDirectories.add(directoryPath);
788
+
789
+ for (const entry of readDirectoryEntries(directoryPath)) {
790
+ const entryPath = join(directoryPath, entry);
791
+ const kind = classifyDirectoryEntry(entry, entryPath);
792
+ if (kind === 'directory') {
793
+ await copyDirectoryTreeToMirror(entryPath, context);
794
+ } else if (kind === 'file') {
795
+ await copyFileToMirror(entryPath, context.mirrorRoot, context.copied);
796
+ }
797
+ }
798
+ };
799
+
800
+ const copyNearestPackageJsonToMirror = async (
801
+ directoryPath: string,
802
+ context: MirrorWalkContext
803
+ ): Promise<void> => {
804
+ let current = directoryPath;
805
+ while (true) {
806
+ const packagePath = join(current, 'package.json');
807
+ const packageStat = safeStat(packagePath);
808
+ if (packageStat?.isFile()) {
809
+ await copyFileToMirror(packagePath, context.mirrorRoot, context.copied);
810
+ return;
811
+ }
812
+
813
+ const parent = dirname(current);
814
+ if (parent === current) {
815
+ return;
816
+ }
817
+ current = parent;
818
+ }
819
+ };
820
+
821
+ const packageLinkSegments = (packageName: string): readonly string[] =>
822
+ packageName.split('/').filter((segment) => segment.length > 0);
823
+
824
+ const createPackageMirrorLink = (
825
+ packageName: string,
826
+ targetRoot: string,
827
+ context: MirrorWalkContext
828
+ ): void => {
829
+ if (context.linkedPackageNames.has(packageName)) {
830
+ return;
831
+ }
832
+ const mirrorWorkspaceRoot = resolveLoadAppMirrorFilePath(
833
+ context.cwd,
834
+ context.mirrorRoot
835
+ );
836
+ if (mirrorWorkspaceRoot.isErr()) {
837
+ throw mirrorWorkspaceRoot.error;
838
+ }
839
+ const linkPath = join(
840
+ mirrorWorkspaceRoot.value,
841
+ 'node_modules',
842
+ ...packageLinkSegments(packageName)
843
+ );
844
+
845
+ const ensured = ensureLoadAppMirrorDirectory(
846
+ dirname(linkPath),
847
+ context.mirrorRoot
848
+ );
849
+ if (ensured.isErr()) {
850
+ throw ensured.error;
851
+ }
852
+
853
+ try {
854
+ symlinkSync(targetRoot, linkPath, 'dir');
855
+ } catch (error) {
856
+ if (
857
+ !(error instanceof Error) ||
858
+ !('code' in error) ||
859
+ error.code !== 'EEXIST'
860
+ ) {
861
+ throw error;
862
+ }
863
+ }
864
+ context.linkedPackageNames.add(packageName);
865
+ };
866
+
867
+ const createWorkspacePackageMirrorLink = (
868
+ packageName: string,
869
+ packageRoot: string,
870
+ context: MirrorWalkContext
871
+ ): void => {
872
+ const mirrorPackageRoot = resolveLoadAppMirrorFilePath(
873
+ packageRoot,
874
+ context.mirrorRoot
875
+ );
876
+ if (mirrorPackageRoot.isErr()) {
877
+ throw mirrorPackageRoot.error;
878
+ }
879
+ createPackageMirrorLink(packageName, mirrorPackageRoot.value, context);
880
+ };
881
+
882
+ const mirrorImportedModule = async (
883
+ modulePath: string,
884
+ context: MirrorWalkContext
885
+ ): Promise<void> => {
886
+ const moduleDirectory = dirname(modulePath);
887
+ await copyNearestPackageJsonToMirror(moduleDirectory, context);
888
+ if (context.visitedDirectories.has(moduleDirectory)) {
889
+ await copyFileToMirror(modulePath, context.mirrorRoot, context.copied);
890
+ return;
891
+ }
892
+ await copyDirectoryTreeToMirror(moduleDirectory, context);
893
+ };
894
+
895
+ const scanAndVisitLocalImports = async (
896
+ modulePath: string,
897
+ context: MirrorWalkContext,
898
+ visit: (path: string) => Promise<void>
899
+ ): Promise<void> => {
900
+ if (!isScannableModule(modulePath)) {
901
+ return;
902
+ }
903
+ const source = await Bun.file(modulePath).text();
904
+ for (const imported of collectImportedModuleResolutions(
905
+ modulePath,
906
+ source,
907
+ context.cwd
908
+ )) {
909
+ if (imported.kind === 'external-package') {
910
+ createPackageMirrorLink(
911
+ imported.packageName,
912
+ imported.packageRoot,
913
+ context
914
+ );
915
+ continue;
916
+ }
917
+ if (imported.kind === 'workspace-package') {
918
+ createWorkspacePackageMirrorLink(
919
+ imported.packageName,
920
+ imported.packageRoot,
921
+ context
922
+ );
923
+ }
924
+ await visit(imported.modulePath);
925
+ }
926
+ };
927
+
928
+ const mirrorFreshImportGraph = async (
929
+ entryPath: string,
930
+ cwd: string,
931
+ mirrorRoot: string
932
+ ): Promise<string> => {
933
+ const scanned = new Set<string>();
934
+ const context: MirrorWalkContext = {
935
+ copied: new Set<string>(),
936
+ cwd,
937
+ linkedPackageNames: new Set<string>(),
938
+ mirrorRoot,
939
+ visitedDirectories: new Set<string>(),
940
+ };
941
+
942
+ const visit = async (modulePath: string): Promise<void> => {
943
+ if (scanned.has(modulePath)) {
944
+ return;
945
+ }
946
+ scanned.add(modulePath);
947
+ await scanAndVisitLocalImports(modulePath, context, visit);
948
+ await mirrorImportedModule(modulePath, context);
949
+ };
950
+
951
+ await visit(entryPath);
952
+ const freshPath = resolveLoadAppMirrorFilePath(entryPath, mirrorRoot);
953
+ if (freshPath.isErr()) {
954
+ throw freshPath.error;
955
+ }
956
+ return freshPath.value;
957
+ };
958
+
959
+ /**
960
+ * Import a module bypassing the ESM cache for the local filesystem import graph.
961
+ *
962
+ * @remarks
963
+ * External packages and built-in modules still resolve normally. Only local
964
+ * filesystem imports are mirrored into the fresh temp root. The mirror tree
965
+ * is retained for the lifetime of the process so that deferred relative
966
+ * `import()`/`require()` calls originating from the loaded module (e.g.
967
+ * inside a trail's `implementation`) can still resolve. If the graph walk itself
968
+ * fails, the partially-written mirror is removed immediately so failed
969
+ * loads do not leak disk space.
970
+ */
971
+ const importWithCacheBust = async (
972
+ absolutePath: string
973
+ ): Promise<Record<string, unknown>> => {
974
+ const url = new URL(absolutePath);
975
+ url.searchParams.set('t', Date.now().toString());
976
+ return (await import(url.href)) as Record<string, unknown>;
977
+ };
978
+
979
+ const prepareMirror = async (
980
+ absolutePath: string,
981
+ cwd: string
982
+ ): Promise<{ mirrorRoot: string; freshPath: string }> => {
983
+ const resolvedCwd = resolve(cwd);
984
+ const mirrorRoot = freshMirrorRootPath(resolvedCwd);
985
+ try {
986
+ const freshPath = await mirrorFreshImportGraph(
987
+ absolutePath,
988
+ resolvedCwd,
989
+ mirrorRoot
990
+ );
991
+ return { freshPath, mirrorRoot };
992
+ } catch (error) {
993
+ removeLoadAppMirrorRootQuietly(mirrorRoot);
994
+ throw error;
995
+ }
996
+ };
997
+
998
+ const importFreshModule = async (
999
+ resolvedModulePath: string,
1000
+ cwd: string
1001
+ ): Promise<Record<string, unknown>> => {
1002
+ const absolutePath = resolvedModulePath;
1003
+ if (URL_SCHEME.test(absolutePath) && !absolutePath.startsWith('/')) {
1004
+ return await importWithCacheBust(absolutePath);
1005
+ }
1006
+
1007
+ const { mirrorRoot, freshPath } = await prepareMirror(absolutePath, cwd);
1008
+ retainMirrorRoot(mirrorRoot);
1009
+ return (await import(pathToFileURL(freshPath).href)) as Record<
26
1010
  string,
27
1011
  unknown
28
1012
  >;
29
- const app = (mod['default'] ?? mod['app']) as Topo | undefined;
1013
+ };
1014
+
1015
+ const resolveLoadedTopo = (
1016
+ effectivePath: string,
1017
+ mod: Record<string, unknown>
1018
+ ): Topo => {
1019
+ const app = (mod['default'] ?? mod['graph'] ?? mod['app']) as
1020
+ | Topo
1021
+ | undefined;
30
1022
  if (!app?.trails) {
31
- throw new Error(
32
- `Could not find a Topo export in "${modulePath}". ` +
33
- "Expected a default or named 'app' export created with topo()."
1023
+ throw new ValidationError(
1024
+ `Could not find a Topo export in "${effectivePath}". ` +
1025
+ "Expected a default, 'graph', or 'app' named export created with topo()."
34
1026
  );
35
1027
  }
36
1028
  return app;
37
1029
  };
1030
+
1031
+ export interface FreshAppLease {
1032
+ readonly app: Topo;
1033
+ readonly mirrorRoot: string;
1034
+ readonly release: () => void;
1035
+ readonly overlays?: readonly TopoGraphOverlayRegistration[] | undefined;
1036
+ }
1037
+
1038
+ export type LoadAppLeaseOptions = LoadAppTrustOptions;
1039
+
1040
+ export interface LoadAppOptions extends LoadAppTrustOptions {
1041
+ readonly fresh?: boolean | undefined;
1042
+ }
1043
+
1044
+ const noopRelease = (): void => undefined;
1045
+
1046
+ const createUrlSchemeLease = async (
1047
+ absolutePath: string,
1048
+ effectivePath: string
1049
+ ): Promise<FreshAppLease> => {
1050
+ const mod = (await importWithCacheBust(absolutePath)) as Record<
1051
+ string,
1052
+ unknown
1053
+ >;
1054
+ return {
1055
+ app: resolveLoadedTopo(effectivePath, mod),
1056
+ mirrorRoot: absolutePath,
1057
+ overlays: resolveTrailsOverlays(mod, effectivePath),
1058
+ release: noopRelease,
1059
+ };
1060
+ };
1061
+
1062
+ const createFilesystemLease = async (
1063
+ absolutePath: string,
1064
+ cwd: string,
1065
+ effectivePath: string
1066
+ ): Promise<FreshAppLease> => {
1067
+ const { mirrorRoot, freshPath } = await prepareMirror(absolutePath, cwd);
1068
+ const release = acquireMirrorLease(mirrorRoot);
1069
+
1070
+ try {
1071
+ const mod = (await import(pathToFileURL(freshPath).href)) as Record<
1072
+ string,
1073
+ unknown
1074
+ >;
1075
+
1076
+ return {
1077
+ app: resolveLoadedTopo(effectivePath, mod),
1078
+ mirrorRoot,
1079
+ overlays: resolveTrailsOverlays(mod, effectivePath),
1080
+ release,
1081
+ };
1082
+ } catch (error) {
1083
+ release();
1084
+ throw error;
1085
+ }
1086
+ };
1087
+
1088
+ export const loadFreshAppLease = async (
1089
+ modulePath: string | undefined,
1090
+ cwd: string,
1091
+ options: LoadAppLeaseOptions = {}
1092
+ ): Promise<FreshAppLease> => {
1093
+ const effectivePath =
1094
+ modulePath === undefined ? findWorkspaceRelativeAppModule(cwd) : modulePath;
1095
+ const absolutePath = resolveLoadAppModulePath(effectivePath, cwd, options);
1096
+
1097
+ return URL_SCHEME.test(absolutePath) && !absolutePath.startsWith('/')
1098
+ ? await createUrlSchemeLease(absolutePath, effectivePath)
1099
+ : await createFilesystemLease(absolutePath, cwd, effectivePath);
1100
+ };
1101
+
1102
+ export const tryLoadFreshAppLease = async (
1103
+ modulePath: string | undefined,
1104
+ cwd: string,
1105
+ options: LoadAppLeaseOptions = {}
1106
+ ): Promise<Result<FreshAppLease, Error>> => {
1107
+ try {
1108
+ return Result.ok(await loadFreshAppLease(modulePath, cwd, options));
1109
+ } catch (error) {
1110
+ return Result.err(toLoadAppError(error));
1111
+ }
1112
+ };
1113
+
1114
+ /**
1115
+ * Load a Topo export from a module path relative to cwd.
1116
+ *
1117
+ * @remarks
1118
+ * By default, `modulePath` must be workspace-relative and stay under `cwd`.
1119
+ * URL-shaped, absolute, and parent-escape paths are rejected. Trusted internal
1120
+ * callers can pass `trustedModulePath: true` to deliberately use the broader
1121
+ * dynamic-import escape hatch.
1122
+ */
1123
+ export const loadApp = async (
1124
+ modulePath: string | undefined,
1125
+ cwd: string,
1126
+ options: LoadAppOptions = {}
1127
+ ): Promise<Topo> => {
1128
+ const effectivePath =
1129
+ modulePath === undefined ? findWorkspaceRelativeAppModule(cwd) : modulePath;
1130
+ const resolvedModulePath = resolveLoadAppModulePath(
1131
+ effectivePath,
1132
+ cwd,
1133
+ options
1134
+ );
1135
+ const mod =
1136
+ options.fresh === true
1137
+ ? await importFreshModule(resolvedModulePath, cwd)
1138
+ : ((await import(
1139
+ URL_SCHEME.test(resolvedModulePath) &&
1140
+ !resolvedModulePath.startsWith('/')
1141
+ ? new URL(resolvedModulePath).href
1142
+ : pathToFileURL(resolvedModulePath).href
1143
+ )) as Record<string, unknown>);
1144
+ return resolveLoadedTopo(effectivePath, mod);
1145
+ };