@octane-xplat/build 0.0.0-stage → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/add-worker.js +66 -0
  4. package/dist/build-worker.js +276 -0
  5. package/dist/compatibility-check.js +153 -0
  6. package/dist/compatibility-data/compatibility.js +106 -0
  7. package/dist/compatibility-data/compatibility.json +305 -0
  8. package/dist/compatibility.js +229 -0
  9. package/dist/css-layers.js +63 -0
  10. package/dist/css-platform.js +230 -0
  11. package/dist/css-platform.types.d.ts +11 -0
  12. package/dist/dev-inspector.web.js +125 -0
  13. package/dist/dev-log-client.web.js +79 -0
  14. package/dist/dev-log-server.js +13 -0
  15. package/dist/doctor-checks.js +317 -0
  16. package/dist/doctor-tool.js +27 -0
  17. package/dist/env.js +3 -0
  18. package/dist/fmt-plan.js +149 -0
  19. package/dist/fonts-worker.js +31 -0
  20. package/dist/fonts.js +614 -0
  21. package/dist/inline-stylesheets.js +37 -0
  22. package/dist/linux/config.js +43 -0
  23. package/dist/linux/host/bridge-selftest.linux.js +255 -0
  24. package/dist/linux/host/gjs-host.js +1412 -0
  25. package/dist/linux/package.js +176 -0
  26. package/dist/linux-gtk/vite.d.ts +23 -0
  27. package/dist/linux-gtk/vite.js +194 -0
  28. package/dist/macos/config.js +141 -0
  29. package/dist/macos/doctor-checks.js +58 -0
  30. package/dist/macos/executables.js +39 -0
  31. package/dist/macos/jsc-host/runtime.js +134 -0
  32. package/dist/macos/native.js +287 -0
  33. package/dist/macos/runtime-package.js +30 -0
  34. package/dist/macos/tab-item.js +62 -0
  35. package/dist/macos/vite.d.ts +21 -0
  36. package/dist/macos/vite.js +111 -0
  37. package/dist/markdown.js +11 -0
  38. package/dist/mason-engine.js +20 -0
  39. package/dist/mcp/contracts/actions.js +133 -0
  40. package/dist/mcp/dev-bridge.js +363 -0
  41. package/dist/mcp/dev-socket.js +161 -0
  42. package/dist/mcp/dev-stack.js +134 -0
  43. package/dist/mcp/inspection/dom.web.js +46 -0
  44. package/dist/native-regex.js +123 -0
  45. package/dist/package-manager.js +106 -0
  46. package/dist/package-root.js +48 -0
  47. package/dist/patches.js +356 -0
  48. package/dist/route-config.js +53 -0
  49. package/dist/route-data.js +42 -0
  50. package/dist/route-generator.js +514 -0
  51. package/dist/route-path.js +29 -0
  52. package/dist/route-source.js +67 -0
  53. package/dist/targets.js +38 -0
  54. package/dist/tsconfig-envs.js +287 -0
  55. package/dist/tsrx-leaf.js +57 -0
  56. package/dist/typecheck-globals/macos.d.ts +21 -0
  57. package/dist/typecheck-globals/native.d.ts +26 -0
  58. package/dist/ui/src/markdown/markdown-ast.js +33 -0
  59. package/dist/ui/src/markdown/markdown-character-references.js +79 -0
  60. package/dist/ui/src/markdown/markdown-parse.js +1930 -0
  61. package/dist/ui/src/markdown/markdown-plugins.js +564 -0
  62. package/dist/ui/src/markdown/markdown-url.js +17 -0
  63. package/dist/updates-worker.js +34 -0
  64. package/dist/upgrade-worker.js +63 -0
  65. package/dist/vite.d.ts +85 -0
  66. package/dist/vite.js +628 -0
  67. package/dist/workshop-worker.js +181 -0
  68. package/package.json +72 -5
@@ -0,0 +1,514 @@
1
+ import { mdToDoc } from "./markdown.js";
2
+ import { assertRouteDataJson } from "./route-data.js";
3
+ import { loadRoutingConfig } from "./route-config.js";
4
+ import { routeSourceMetadata } from "./route-source.js";
5
+ import { EXT, PRESENT, SUFFIX, routeFor } from "./route-path.js";
6
+ import { isTsrxContract } from "./tsrx-leaf.js";
7
+ import { installedToolPackageRoot } from "./package-root.js";
8
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
9
+ import { createRequire } from "node:module";
10
+ import { basename, join, relative, sep } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { routeParamName } from "@octane-xplat/lib/route-pattern";
13
+ // ../cli/src/route-generator.ts
14
+ var LOADER_FILE = /\.loader\.(ts|mts|cts|js|mjs|cjs)$/;
15
+ var LOADER_EXTS = [
16
+ "ts",
17
+ "mts",
18
+ "cts",
19
+ "js",
20
+ "mjs",
21
+ "cjs"
22
+ ];
23
+ function walk(dir, out = []) {
24
+ for (const name of readdirSync(dir).sort()) {
25
+ const full = join(dir, name);
26
+ if (statSync(full).isDirectory()) walk(full, out);
27
+ else if (EXT.test(name) || name.endsWith(".md")) out.push(full);
28
+ }
29
+ return out;
30
+ }
31
+ /** Vite from the consuming app — same createRequire dance as vite.mjs:
32
+ * under pnpm's isolated linker a bare import here misses the app's copy. */
33
+ function appVite(cwd) {
34
+ const root = installedToolPackageRoot(cwd, "vite");
35
+ const req = createRequire(join(root ?? cwd, "package.json"));
36
+ return import(pathToFileURL(realpathSync(req.resolve("vite"))).href);
37
+ }
38
+ /** Runs each baked route's `.loader.ts` under vite ssrLoadModule (Node —
39
+ * no DOM or native globals, app config not loaded) and returns the
40
+ * name → serialized-result map. */
41
+ async function bakeRouteData(cwd, loaders, onSource) {
42
+ const server = await (await appVite(cwd)).createServer({
43
+ root: cwd,
44
+ configFile: false,
45
+ logLevel: "silent",
46
+ server: { middlewareMode: true },
47
+ appType: "custom"
48
+ });
49
+ try {
50
+ const data = Object.create(null);
51
+ for (const [name, file] of loaders) {
52
+ onSource?.(relative(cwd, file));
53
+ const mod = await server.ssrLoadModule(file);
54
+ const loader = mod?.loader ?? mod?.default;
55
+ if (typeof loader !== "function") throw new Error(`baked route '${name}' — ${relative(cwd, file)} must export a 'loader' function`);
56
+ const value = await loader({});
57
+ assertRouteDataJson(value, name, relative(cwd, file));
58
+ data[name] = value;
59
+ onSource?.(void 0);
60
+ }
61
+ return data;
62
+ } finally {
63
+ await server.close();
64
+ }
65
+ }
66
+ /** Generates routes.gen.types.ts + platform manifest glue for a route dir.
67
+ * Returns the route count; false when no dir was given. A missing or empty
68
+ * dir still emits a valid (empty) gen — apps with only programmatic routes
69
+ * can import the stub types.
70
+ *
71
+ * `opts.bake` (default true): execute `dataMode: 'baked'` routes' sibling
72
+ * `.loader.ts` modules and emit `<out>.data.ts`. Callers that only need
73
+ * the types (typecheck) pass false — an existing data module is left
74
+ * alone, a missing one gets an empty stub so imports resolve. */
75
+ async function planRoutes(cwd, dir, out, opts = {}) {
76
+ opts.signal?.throwIfAborted();
77
+ const outputs = /* @__PURE__ */ new Map();
78
+ const warn = opts.onWarn ?? (() => {});
79
+ const emit = (file, source) => outputs.set(file, source);
80
+ const config = loadRoutingConfig(cwd);
81
+ dir = dir ?? config?.directory ?? ["app", "src/app"].find((path) => existsSync(join(cwd, path))) ?? (config ? "src/app" : void 0);
82
+ if (!dir) return {
83
+ count: false,
84
+ outputs
85
+ };
86
+ out = out ?? config?.out;
87
+ const bake = opts.bake !== false;
88
+ const base = (out ?? join(dir, "..", "routes.gen")).replace(/\.ts$/, "");
89
+ const outputDirectory = join(cwd, base, "..");
90
+ const moduleRef = (file) => {
91
+ const value = relative(outputDirectory, file).split(sep).join("/");
92
+ return value.startsWith(".") ? value : "./" + value;
93
+ };
94
+ const exportType = (ref) => `typeof import(${JSON.stringify(moduleRef(join(cwd, ref.module)))})[${JSON.stringify(ref.export)}]`;
95
+ const contextType = config?.context ? `RouteRootContext<${exportType(config.context)}>` : "Record<string, unknown>";
96
+ const seen = /* @__PURE__ */ new Map();
97
+ const variants = /* @__PURE__ */ new Map();
98
+ const routePaths = [];
99
+ const contractPaths = [];
100
+ const layoutDirs = /* @__PURE__ */ new Set();
101
+ const files = existsSync(join(cwd, dir)) ? walk(join(cwd, dir)).filter((file) => /\.(tsx|tsrx|md)$/.test(file) && !file.startsWith(join(cwd, base) + ".")) : [];
102
+ for (const file of files) {
103
+ const routePath = relative(join(cwd, dir), file).split(sep).join("/");
104
+ if (file.endsWith(".tsrx") && isTsrxContract(readFileSync(file, "utf8"), file)) {
105
+ contractPaths.push(routePath);
106
+ continue;
107
+ }
108
+ if (LOADER_FILE.test(routePath)) continue;
109
+ const isMd = routePath.endsWith(".md");
110
+ if (/\.(tsrx|tsx)$/.test(routePath)) routePaths.push(routePath);
111
+ if (routePath.replace(isMd ? /\.md$/ : EXT, "").split("/").pop().replace(SUFFIX, "").replace(PRESENT, "") === "_layout" && !isMd) {
112
+ layoutDirs.add(routePath.split("/").slice(0, -1).join("/"));
113
+ continue;
114
+ }
115
+ const r = routeFor(routePath, isMd ? /\.md$/ : EXT);
116
+ if (!r) continue;
117
+ r.file = routePath;
118
+ if (isMd) {
119
+ r.dataMode = "baked";
120
+ r.md = true;
121
+ if (r.params.length) {
122
+ warn(`markdown route '${routePath}' declares a param — .md files bake one document; for param'd content use a [param] route + .loader.ts that bakes a table`);
123
+ continue;
124
+ }
125
+ } else {
126
+ opts.onSource?.(relative(cwd, file));
127
+ Object.assign(r, routeSourceMetadata(readFileSync(file, "utf8"), relative(cwd, file)));
128
+ opts.onSource?.(void 0);
129
+ }
130
+ if (!r.md) {
131
+ const leaves = variants.get(r.name) ?? [];
132
+ leaves.push({ ...r });
133
+ variants.set(r.name, leaves);
134
+ }
135
+ const prev = seen.get(r.name);
136
+ if (!prev) seen.set(r.name, r);
137
+ else if (r.md && !prev.md) warn(`route '${r.name}' has both a component file and ${r.file} — keeping the component`);
138
+ else if (prev.md && !r.md) {
139
+ warn(`route '${r.name}' has both ${prev.file} and a component file — keeping the component`);
140
+ seen.set(r.name, r);
141
+ } else if (r.dataMode && prev.dataMode && prev.dataMode !== r.dataMode) warn(`route '${r.name}' declares dataMode '${prev.dataMode}' and '${r.dataMode}' in different leaves — keeping '${prev.dataMode}'`);
142
+ else if (r.dataMode && !prev.dataMode) prev.dataMode = r.dataMode;
143
+ if (prev) {
144
+ prev.loader ||= r.loader;
145
+ prev.guard ||= r.guard;
146
+ prev.head ||= r.head;
147
+ prev.errorBoundary ||= r.errorBoundary;
148
+ }
149
+ }
150
+ const list = [...seen.values()].sort((a, b) => a.name.localeCompare(b.name));
151
+ const patternNames = /* @__PURE__ */ new Map();
152
+ for (const route of list) {
153
+ const shape = route.segments.map((segment) => routeParamName(segment) ? segment.startsWith("*") ? "*" : segment.endsWith("?") ? ":?" : ":" : segment).join("/");
154
+ const previous = patternNames.get(shape);
155
+ if (previous && previous.name !== route.name) throw new Error(`route/incompatible-platform-params: ${previous.file} and ${route.file} describe the same URL pattern with different parameter names; use the same bracket names across platform variants`);
156
+ patternNames.set(shape, route);
157
+ }
158
+ const union = list.length ? list.map((r) => `\n\t| '${r.name}'`).join("") : "never";
159
+ const paramField = (s) => {
160
+ if (s.startsWith("*")) return `'${s.slice(1) || "*"}'?: string`;
161
+ const name = s.slice(1);
162
+ return s.endsWith("?") ? `${name.slice(0, -1)}?: string` : `${name}: string`;
163
+ };
164
+ const params = list.map((r) => `\t'${r.name}': { ${r.segments.filter((s) => s.startsWith(":") || s.startsWith("*")).map(paramField).join("; ")} }`);
165
+ const presents = list.filter((r) => r.presentation).map((r) => `\t'${r.name}': '${r.presentation}'`);
166
+ const stemFor = (rel) => {
167
+ const parts = rel.replace(EXT, "").split("/");
168
+ let base = parts[parts.length - 1];
169
+ const sm = SUFFIX.exec(base);
170
+ if (sm) base = base.slice(0, base.length - sm[0].length);
171
+ const pm = PRESENT.exec(base);
172
+ if (pm) base = base.slice(0, base.length - pm[0].length);
173
+ parts[parts.length - 1] = base;
174
+ return parts.join("/");
175
+ };
176
+ const loaderFiles = /* @__PURE__ */ new Map();
177
+ const mdRoutes = [];
178
+ for (const r of list) {
179
+ if (r.dataMode !== "baked") continue;
180
+ if (r.md) {
181
+ mdRoutes.push(r);
182
+ continue;
183
+ }
184
+ const stem = stemFor(r.file);
185
+ for (const ext of LOADER_EXTS) {
186
+ const candidate = join(cwd, dir, `${stem}.loader.${ext}`);
187
+ if (existsSync(candidate)) {
188
+ loaderFiles.set(r.name, candidate);
189
+ break;
190
+ }
191
+ }
192
+ if (!loaderFiles.has(r.name)) throw new Error(`baked route '${r.name}' (${r.file}) has no loader sibling — expected ${dir}/${stem}.loader.{${LOADER_EXTS.join(",")}}`);
193
+ }
194
+ const targets = [
195
+ "web",
196
+ "ios",
197
+ "android",
198
+ "mobile",
199
+ "macos",
200
+ "windows",
201
+ "linux"
202
+ ];
203
+ const platforms = new Map(list.map((r) => [r.name, targets.filter((target) => r.md || (variants.get(r.name) ?? []).some((leaf) => {
204
+ const suffix = /\.(web|mobile|ios|android|macos|windows|linux)\.(tsx|tsrx)$/.exec(leaf.file)?.[1];
205
+ return !suffix || suffix === target || suffix === "web" && target === "linux" || suffix === "mobile" && (target === "ios" || target === "android");
206
+ }))]));
207
+ const contractEntries = list.map((r) => {
208
+ const path = "/" + r.segments.join("/");
209
+ const module = r.md ? "{ dataMode: 'baked' }" : `typeof import(${JSON.stringify(moduleRef(join(cwd, dir, r.file)))})`;
210
+ const baked = r.md ? "import('@octane-xplat/ui/markdown').MdDoc" : r.dataMode === "baked" ? `RouteBakedLoaderData<typeof import(${JSON.stringify(moduleRef(loaderFiles.get(r.name)))})>` : "unknown";
211
+ const platformOnly = platforms.get(r.name).length !== targets.length;
212
+ return `\t${JSON.stringify(path)}: FileRouteContract<${JSON.stringify(path)}, ${module}, RootContext${r.dataMode === "baked" ? `, ${baked}` : ""}>${platformOnly ? " & { readonly platformOnly: true }" : ""}`;
213
+ });
214
+ const availability = list.map((r) => {
215
+ const available = platforms.get(r.name);
216
+ return `\t${JSON.stringify("/" + r.segments.join("/"))}: ${available.map((target) => JSON.stringify(target)).join(" | ")}`;
217
+ });
218
+ const variantChecks = list.flatMap((r) => (variants.get(r.name) ?? []).filter((leaf) => leaf.file !== r.file).map((leaf) => {
219
+ const path = "/" + r.segments.join("/");
220
+ const mod = `typeof import(${JSON.stringify(moduleRef(join(cwd, dir, leaf.file)))})`;
221
+ const baked = r.dataMode === "baked" ? `, RouteBakedLoaderData<typeof import(${JSON.stringify(moduleRef(loaderFiles.get(r.name)))})>` : "";
222
+ const contract = `FileRouteContract<${JSON.stringify(path)}, ${mod}, RootContext${baked}>`;
223
+ return `\t// ${JSON.stringify(path)}: ${r.file} ↔ ${leaf.file}\n\tCheckRouteVariant<FileRouteContracts[${JSON.stringify(path)}], ${contract}>,\n\tCheckRouteVariant<${contract}, FileRouteContracts[${JSON.stringify(path)}]>,`;
224
+ }));
225
+ const exportChecks = [...variants.values()].flatMap((leaves) => leaves.flatMap((leaf) => [
226
+ ["loader", "loader"],
227
+ ["beforeLoad", "guard"],
228
+ ["group", "group"],
229
+ ["validateSearch", "validateSearch"],
230
+ ["head", "head"],
231
+ ["ErrorBoundary", "errorBoundary"]
232
+ ].filter(([, flag]) => leaf[flag]).map(([field]) => `\t// ${leaf.file}: ${field}\n\tCheckRouteExport<${JSON.stringify(field)}, typeof import(${JSON.stringify(moduleRef(join(cwd, dir, leaf.file)))})[${JSON.stringify(field)}]${field === "validateSearch" ? `, import('@octane-xplat/ui/routing/core').RouteSearchValidationCheck<typeof import(${JSON.stringify(moduleRef(join(cwd, dir, leaf.file)))})[${JSON.stringify(field)}]>` : ""}>,`)));
233
+ const src = `// Generated by \`xplat routes\` — do not edit. Re-run after
234
+ // touching the route dir (add/remove/rename route files).
235
+ import type { ContractsOf, FileRouteContract, RouteBakedLoaderData, FileRouteGuardArgs, FileRouteLoaderArgs, RouteScreenProps, RouteRootContext, MergeRouteContracts } from '@octane-xplat/ui/routing/core'
236
+
237
+ export type RootContext = ${contextType}
238
+ export interface FileRouteContracts {
239
+ ${contractEntries.join("\n")}
240
+ }
241
+ export interface FileRouteAvailability {
242
+ ${availability.join("\n")}
243
+ }
244
+ export type FileRouteContractsFor<Platform extends ${targets.map((target) => JSON.stringify(target)).join(" | ")}> = Pick<FileRouteContracts, {
245
+ [Path in keyof FileRouteContracts]: Platform extends FileRouteAvailability[Path] ? Path : never
246
+ }[keyof FileRouteContracts]>
247
+ // Check both directions: every selected leaf must preserve the public contract.
248
+ ${variantChecks.length ? "type CheckRouteVariant<Expected, Actual extends Omit<Expected, 'platformOnly'>> = Actual" : ""}
249
+ export type RouteVariantChecks = [
250
+ ${variantChecks.join("\n")}
251
+ ]
252
+ ${exportChecks.length ? `type RouteExportShapes = {
253
+ group: import('@octane-xplat/ui/routing/core').RouteGroup<any, any> | undefined
254
+ loader: ((...args: never[]) => unknown) | undefined
255
+ beforeLoad: ((...args: never[]) => import('@octane-xplat/ui/routing/core').RouteGuardResult | Promise<import('@octane-xplat/ui/routing/core').RouteGuardResult>) | undefined
256
+ validateSearch: (((...args: never[]) => import('@octane-xplat/ui/routing/core').RouteSearchRecord | Promise<import('@octane-xplat/ui/routing/core').RouteSearchRecord>) & { readonly '~standard'?: never }) | import('@octane-xplat/ui/routing/core').RouteSearchSchema<unknown, import('@octane-xplat/ui/routing/core').RouteSearchRecord> | undefined
257
+ head: import('@octane-xplat/ui/routing/core').RouteHeadExport<any, any, any, any> | undefined
258
+ ErrorBoundary: ((...args: never[]) => unknown) | undefined
259
+ }
260
+ type CheckRouteExport<Field extends keyof RouteExportShapes, Value extends RouteExportShapes[Field], SearchCheck extends true = true> = Value` : ""}
261
+ export type RouteExportChecks = [
262
+ ${exportChecks.join("\n")}
263
+ ]
264
+ export type RouteContracts = MergeRouteContracts<[FileRouteContracts${(config?.manifests ?? []).map((ref) => `, ContractsOf<${exportType(ref)}>`).join("")}]>
265
+ export type RouteContractsFor<Platform extends ${targets.map((target) => JSON.stringify(target)).join(" | ")}> = MergeRouteContracts<[FileRouteContractsFor<Platform>${(config?.manifests ?? []).map((ref) => `, ContractsOf<${exportType(ref)}>`).join("")}]>
266
+ export type RouteProps<Path extends keyof FileRouteContracts> = RouteScreenProps<FileRouteContracts[Path]>
267
+ export type RouteHeadArgs<Path extends keyof FileRouteContracts> = RouteProps<Path>
268
+ ${list.filter((r) => !r.md).map((r) => {
269
+ const path = "/" + r.segments.join("/");
270
+ const mod = `typeof import(${JSON.stringify(moduleRef(join(cwd, dir, r.file)))})`;
271
+ return `type Guard_${list.indexOf(r)} = FileRouteGuardArgs<${JSON.stringify(path)}, ${mod}, RootContext>\ntype Loader_${list.indexOf(r)} = FileRouteLoaderArgs<${JSON.stringify(path)}, ${mod}, RootContext>`;
272
+ }).join("\n")}
273
+ export interface RouteGuardInputs {
274
+ ${list.filter((r) => !r.md).map((r) => `\t${JSON.stringify("/" + r.segments.join("/"))}: Guard_${list.indexOf(r)}`).join("\n")}
275
+ }
276
+ export interface RouteLoaderInputs {
277
+ ${list.filter((r) => !r.md).map((r) => `\t${JSON.stringify("/" + r.segments.join("/"))}: Loader_${list.indexOf(r)}`).join("\n")}
278
+ }
279
+
280
+ export type RouteGuardArgs<Path extends keyof RouteGuardInputs> = RouteGuardInputs[Path]
281
+ export type RouteLoaderArgs<Path extends keyof RouteLoaderInputs> = RouteLoaderInputs[Path]
282
+
283
+ export type RouteName =${union}
284
+
285
+ export interface RouteParams {
286
+ ${params.length ? params.join("\n") : " // no param routes"}
287
+ }
288
+
289
+ export interface RoutePresentations {
290
+ ${presents.length ? presents.join("\n") : " // no declared presentation defaults"}
291
+ }
292
+ `;
293
+ emit(join(cwd, base + ".contracts.ts"), src);
294
+ const contractsRef = "./" + basename(base) + ".contracts";
295
+ const registration = `// Generated by \`xplat routes\` — do not edit.
296
+ // Application registration. Import .contracts for isolated/local type use.
297
+ import type {} from '@octane-xplat/ui'
298
+ import type { RouteContracts } from ${JSON.stringify(contractsRef)}
299
+ export type * from ${JSON.stringify(contractsRef)}
300
+ ${config?.transitions ? `import type { TransitionNames } from '@octane-xplat/ui/routing/core'\ntype CustomTransitions = { [Key in TransitionNames<${exportType(config.transitions)}>]: unknown }\n` : ""}
301
+
302
+ // A module-local symbol keeps separately generated catalogs from overwriting
303
+ // each other's ambient contribution. This declaration has no runtime value.
304
+ declare const registration: unique symbol
305
+
306
+ // File and configured programmatic contracts share the same destination union.
307
+ declare module '@octane-xplat/ui' {
308
+ interface AppRouteContracts {
309
+ [registration]: RouteContracts
310
+ }
311
+ interface AppRouteStacks {
312
+ ${(config?.stacks ?? []).map((stack) => `\t\t${JSON.stringify(stack)}: unknown`).join("\n")}
313
+ }
314
+ ${config?.transitions ? `\tinterface AppRouteTransitions extends CustomTransitions {}\n` : ""}}
315
+ `;
316
+ emit(join(cwd, base + ".types.ts"), registration);
317
+ const needsBake = loaderFiles.size > 0 || mdRoutes.length > 0;
318
+ const dataFile = join(cwd, base + ".data.ts");
319
+ const dataSrc = (data) => `// Generated by \`xplat routes\` — baked loader results.
320
+ // Re-run \`xplat routes\` (or dev/build) after touching *.loader.* or .md routes.
321
+ export const bakedRouteData: Record<string, unknown> = JSON.parse(${JSON.stringify(JSON.stringify(data))})
322
+ `;
323
+ if (needsBake && bake) {
324
+ const data = Object.create(null);
325
+ for (const r of mdRoutes) {
326
+ opts.onSource?.(join(dir, r.file));
327
+ const value = mdToDoc(readFileSync(join(cwd, dir, r.file), "utf8"));
328
+ assertRouteDataJson(value, r.name, `${dir}/${r.file}`);
329
+ data[r.name] = value;
330
+ opts.onSource?.(void 0);
331
+ }
332
+ if (loaderFiles.size) Object.assign(data, await bakeRouteData(cwd, loaderFiles, opts.onSource));
333
+ emit(dataFile, dataSrc(data));
334
+ } else if (!needsBake || !existsSync(dataFile)) emit(dataFile, dataSrc({}));
335
+ const chainDirs = (name) => {
336
+ const segs = name.split("/");
337
+ const dirs = layoutDirs.has("") ? [""] : [];
338
+ for (let i = 1; i < segs.length; i++) {
339
+ const d = segs.slice(0, i).join("/");
340
+ if (layoutDirs.has(d)) dirs.push(d);
341
+ }
342
+ return dirs;
343
+ };
344
+ const manifestJson = {
345
+ version: 1,
346
+ layouts: [...layoutDirs].sort(),
347
+ screens: list.map((r) => r.name).sort(),
348
+ routes: list.map((r) => ({
349
+ name: r.name,
350
+ platforms: platforms.get(r.name),
351
+ path: r.name === "index" ? "" : r.name,
352
+ params: r.params,
353
+ ...r.presentation ? { presentation: r.presentation } : {},
354
+ ...r.transition ? { transition: r.transition } : {},
355
+ ...r.dataMode ? { dataMode: r.dataMode } : {},
356
+ layouts: chainDirs(r.name),
357
+ source: `${dir}/${r.file}`,
358
+ loader: !!(r.loader || r.group || r.md || loaderFiles.has(r.name)),
359
+ guard: !!(r.guard || r.group),
360
+ head: !!r.head,
361
+ errorBoundary: !!r.errorBoundary
362
+ }))
363
+ };
364
+ emit(join(cwd, base + ".manifest.json"), JSON.stringify(manifestJson, null, " ") + "\n");
365
+ const outDir = join(cwd, base, "..");
366
+ const rel = relative(outDir, join(cwd, dir)).split(sep).join("/");
367
+ const globDir = rel.startsWith(".") ? rel : "./" + rel;
368
+ const baseName = basename(base);
369
+ const typesRef = `export type { RouteName, RouteParams, RoutePresentations } from './${baseName}.contracts'`;
370
+ const platformSuffix = /\.(web|mobile|ios|android|macos|windows|linux)\.(tsrx|tsx)$/;
371
+ const globLiteral = (path) => path.replace(/[\\*?{}()!@+[\]]/g, "\\$&");
372
+ const exactExclusions = (...preferences) => {
373
+ const candidates = routePaths.map((path) => {
374
+ const suffix = platformSuffix.exec(path)?.[1];
375
+ const rank = suffix ? preferences.indexOf(suffix) : preferences.length;
376
+ const route = routeFor(path);
377
+ return {
378
+ path,
379
+ rank,
380
+ identity: route ? "route:" + route.name : "layout:" + path.split("/").slice(0, -1).join("/")
381
+ };
382
+ }).filter((file) => file.rank !== -1);
383
+ const best = /* @__PURE__ */ new Map();
384
+ for (const file of candidates) best.set(file.identity, Math.min(best.get(file.identity) ?? Infinity, file.rank));
385
+ return [...contractPaths.map((path) => `\t\t'!${globDir}/${globLiteral(path)}'`), ...candidates.filter((file) => file.rank > best.get(file.identity)).map((file) => `\t\t'!${globDir}/${globLiteral(file.path)}'`)];
386
+ };
387
+ const mdGlue = mdRoutes.length ? `const markdownRoutes = sealGeneratedRouteCatalog<FileRouteContracts>(defineRoutes({
388
+ routes: [
389
+ ${mdRoutes.map((s) => `\t\t{ path: ${JSON.stringify(s.name)}, screen: MarkdownScreen, dataMode: 'baked', source: ${JSON.stringify(`${dir}/${s.file}`)} },`).join("\n")}
390
+ ],
391
+ baked: bakedRouteData,
392
+ }))
393
+ ` : "";
394
+ const manifestReferences = config?.manifests ?? [];
395
+ const manifestImports = manifestReferences.map((ref, i) => `import { ${ref.export} as configured${i} } from ${JSON.stringify(moduleRef(join(cwd, ref.module)))}`).join("\n");
396
+ const catalogParts = [
397
+ "fileRoutes",
398
+ ...mdRoutes.length ? ["markdownRoutes"] : [],
399
+ ...manifestReferences.map((_, i) => `configured${i}`)
400
+ ];
401
+ const shared = (prelude, globs, prefer, target) => `// Generated by \`xplat routes\` — do not edit.
402
+ // Reusable definitions: importing this module does not install a default router.
403
+ ${prelude}import { deriveLazyRouteManifest, defineRoutes, mergeRouteManifests, sealGeneratedRouteCatalog } from '@octane-xplat/ui/routing/core'
404
+ import { bakedRouteData } from './${baseName}.data'
405
+ import type { RouteCatalog } from '@octane-xplat/ui/routing/core'
406
+ import type { RouteContractsFor, FileRouteContractsFor } from './${baseName}.contracts'
407
+ type RouteContracts = RouteContractsFor<${JSON.stringify(target)}>
408
+ type FileRouteContracts = FileRouteContractsFor<${JSON.stringify(target)}>
409
+ ${mdRoutes.length ? "import { MarkdownScreen } from '@octane-xplat/ui/markdown'\n" : ""}${manifestImports}
410
+ ${typesRef}
411
+
412
+ const files = import.meta.glob(
413
+ [
414
+ '${globDir}/**/*.{tsrx,tsx}',
415
+ '!${globDir}/**/_layout{,+push,+modal,+fade}{,.*}.{tsrx,tsx}',
416
+ ${globs}
417
+ ],
418
+ )
419
+ const layouts = import.meta.glob(
420
+ [
421
+ '${globDir}/**/_layout{,+push,+modal,+fade}{,.*}.{tsrx,tsx}',
422
+ ${globs}
423
+ ],
424
+ { eager: true },
425
+ )
426
+
427
+ const fileDefinitions = deriveLazyRouteManifest(files, ${prefer}, ${JSON.stringify(globDir)}, layouts, bakedRouteData)
428
+ const fileRoutes = sealGeneratedRouteCatalog<FileRouteContracts>(fileDefinitions, ${JSON.stringify(list.filter((route) => !route.md).map((route) => ({
429
+ name: route.name,
430
+ segments: route.segments,
431
+ params: route.params,
432
+ file: `${dir}/${route.file}`,
433
+ platforms: platforms.get(route.name)
434
+ })))})
435
+ ${mdGlue}
436
+ export const routes = mergeRouteManifests(${catalogParts.join(", ")}) as RouteCatalog<RouteContracts>
437
+ export const screens = routes.screens
438
+ `;
439
+ const writePlatform = (path, source) => {
440
+ const catalogPath = path.replace(/\.([^.]+)\.ts$/, ".catalog.$1.ts");
441
+ emit(catalogPath, source);
442
+ const catalogRef = "./" + catalogPath.split(sep).pop().replace(/\.ts$/, "");
443
+ emit(path, `// Generated by \`xplat routes\` — do not edit.
444
+ import { configureRouter } from '@octane-xplat/ui/routing'
445
+ import type {} from './${baseName}.types'
446
+ import { routes } from ${JSON.stringify(catalogRef)}
447
+ ${config?.context ? `import { ${config.context.export} as routeContext } from ${JSON.stringify(moduleRef(join(cwd, config.context.module)))}\n` : ""}${config?.transitions ? `import { ${config.transitions.export} as routeTransitions } from ${JSON.stringify(moduleRef(join(cwd, config.transitions.module)))}\n` : ""}export * from ${JSON.stringify(catalogRef)}
448
+ configureRouter({
449
+ catalog: routes,
450
+ ${config?.context ? " context: routeContext,\n" : ""}${config?.transitions ? " transitions: routeTransitions,\n" : ""}${config?.stacks?.length ? `\tstacks: ${JSON.stringify(config.stacks)},\n` : ""}${[
451
+ "base",
452
+ "allowedOrigins",
453
+ "allowedSchemes"
454
+ ].filter((key) => config?.[key] !== void 0).map((key) => `\t${key}: ${JSON.stringify(config[key])},\n`).join("")}})
455
+ // import.meta.env.DEV is statically false in production builds — the
456
+ // router dev-actions chunk is never emitted. The cast keeps this file
457
+ // typechecking without vite/client ambient types.
458
+ if ((import.meta as unknown as { env: { DEV: boolean } }).env.DEV) {
459
+ \tvoid import('@octane-xplat/ui/routing/dev').then(({ registerRouterDevActions }) => registerRouterDevActions())
460
+ }
461
+ `);
462
+ };
463
+ writePlatform(join(cwd, base + ".web.ts"), shared("", [
464
+ `\t\t'!${globDir}/**/*.mobile.{tsrx,tsx}'`,
465
+ `\t\t'!${globDir}/**/*.ios.{tsrx,tsx}'`,
466
+ `\t\t'!${globDir}/**/*.android.{tsrx,tsx}'`,
467
+ `\t\t'!${globDir}/**/*.macos.{tsrx,tsx}'`,
468
+ `\t\t'!${globDir}/**/*.windows.{tsrx,tsx}'`,
469
+ `\t\t'!${globDir}/**/*.linux.{tsrx,tsx}'`,
470
+ ...exactExclusions("web")
471
+ ].join(",\n"), `['web']`, "web"));
472
+ for (const target of [
473
+ "ios",
474
+ "android",
475
+ "mobile",
476
+ "linux"
477
+ ]) {
478
+ const preferences = target === "linux" ? ["linux", "web"] : target === "mobile" ? ["mobile"] : [target, "mobile"];
479
+ const excluded = [
480
+ "web",
481
+ "ios",
482
+ "android",
483
+ "mobile",
484
+ "macos",
485
+ "windows",
486
+ "linux"
487
+ ].filter((suffix) => !preferences.includes(suffix));
488
+ writePlatform(join(cwd, base + "." + target + ".ts"), shared("", [...excluded.map((suffix) => `\t\t'!${globDir}/**/*.${suffix}.{tsrx,tsx}'`), ...exactExclusions(...preferences)].join(",\n"), JSON.stringify(preferences), target));
489
+ }
490
+ writePlatform(join(cwd, base + ".macos.ts"), shared("", [
491
+ `\t\t'!${globDir}/**/*.web.{tsrx,tsx}'`,
492
+ `\t\t'!${globDir}/**/*.ios.{tsrx,tsx}'`,
493
+ `\t\t'!${globDir}/**/*.android.{tsrx,tsx}'`,
494
+ `\t\t'!${globDir}/**/*.mobile.{tsrx,tsx}'`,
495
+ `\t\t'!${globDir}/**/*.windows.{tsrx,tsx}'`,
496
+ `\t\t'!${globDir}/**/*.linux.{tsrx,tsx}'`,
497
+ ...exactExclusions("macos")
498
+ ].join(",\n"), `['macos']`, "macos"));
499
+ writePlatform(join(cwd, base + ".windows.ts"), shared("", [
500
+ `\t\t'!${globDir}/**/*.web.{tsrx,tsx}'`,
501
+ `\t\t'!${globDir}/**/*.ios.{tsrx,tsx}'`,
502
+ `\t\t'!${globDir}/**/*.android.{tsrx,tsx}'`,
503
+ `\t\t'!${globDir}/**/*.mobile.{tsrx,tsx}'`,
504
+ `\t\t'!${globDir}/**/*.macos.{tsrx,tsx}'`,
505
+ `\t\t'!${globDir}/**/*.linux.{tsrx,tsx}'`,
506
+ ...exactExclusions("windows")
507
+ ].join(",\n"), `['windows']`, "windows"));
508
+ opts.signal?.throwIfAborted();
509
+ return {
510
+ count: list.length,
511
+ outputs
512
+ };
513
+ }
514
+ export { planRoutes };
@@ -0,0 +1,29 @@
1
+ import { sep } from "node:path";
2
+ import { normalizeRouteSegment, routeParamName } from "@octane-xplat/lib/route-pattern";
3
+ // ../cli/src/route-path.ts
4
+ var EXT = /\.(tsrx|tsx|ts|mts|cts|js|mjs|cjs|jsx)$/;
5
+ var SUFFIX = /\.(web|mobile|ios|android|macos|windows|linux)$/;
6
+ var PRESENT = /\+(modal|fade|push)$/;
7
+ function routeFor(rel, extRe = EXT) {
8
+ rel = rel.split(sep).join("/").replace(extRe, "");
9
+ const parts = rel.split("/");
10
+ let base = parts[parts.length - 1];
11
+ const sm = SUFFIX.exec(base);
12
+ if (sm) base = base.slice(0, base.length - sm[0].length);
13
+ const pm = PRESENT.exec(base);
14
+ const presentation = pm ? pm[1] === "fade" ? "push" : pm[1] : void 0;
15
+ const transition = pm?.[1] === "fade" ? "fade" : void 0;
16
+ if (pm) base = base.slice(0, base.length - pm[0].length);
17
+ if (base === "_layout") return null;
18
+ const segs = parts.slice(0, -1).concat(base);
19
+ if (segs[segs.length - 1] === "index") segs.pop();
20
+ const segments = segs.map(normalizeRouteSegment);
21
+ return {
22
+ name: segments.join("/") || "index",
23
+ segments,
24
+ params: segments.flatMap((s) => routeParamName(s) ?? []),
25
+ presentation,
26
+ transition
27
+ };
28
+ }
29
+ export { EXT, PRESENT, SUFFIX, routeFor };
@@ -0,0 +1,67 @@
1
+ import { parseModule } from "@tsrx/core";
2
+ // ../cli/src/route-source.ts
3
+ /** Inspect source, never imports/effects. Type-only exports and comments do not
4
+ * advertise runtime capabilities. Static build mode must be locally knowable. */
5
+ function routeSourceMetadata(source, file) {
6
+ return routeAstMetadata(parseModule(source, file), file);
7
+ }
8
+ function routeAstMetadata(ast, file) {
9
+ const bindings = /* @__PURE__ */ new Map();
10
+ const exported = /* @__PURE__ */ new Map();
11
+ const declare = (node, isExported) => {
12
+ if (!node || node.declare) return;
13
+ if (node.type === "VariableDeclaration") {
14
+ const names = (pattern) => {
15
+ if (pattern.type === "Identifier") return [pattern.name];
16
+ if (pattern.type === "ObjectPattern") return pattern.properties.flatMap((property) => names(property.value ?? property.argument));
17
+ if (pattern.type === "ArrayPattern") return pattern.elements.filter(Boolean).flatMap(names);
18
+ if (pattern.type === "AssignmentPattern") return names(pattern.left);
19
+ if (pattern.type === "RestElement") return names(pattern.argument);
20
+ return [];
21
+ };
22
+ for (const entry of node.declarations) for (const name of names(entry.id)) {
23
+ bindings.set(name, { value: entry.id.type === "Identifier" && node.kind === "const" ? entry.init : void 0 });
24
+ if (isExported) exported.set(name, name);
25
+ }
26
+ } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
27
+ if (isExported && node.id) exported.set(node.id.name, node.id.name);
28
+ }
29
+ };
30
+ for (const node of ast.body) {
31
+ if (node.type === "ExportAllDeclaration" && node.exportKind !== "type") throw new Error(`route/source-exports: ${file}: use explicit named exports instead of export * so route capabilities can be discovered without executing modules`);
32
+ if (node.type !== "ExportNamedDeclaration") {
33
+ declare(node, false);
34
+ continue;
35
+ }
36
+ if (node.exportKind === "type") continue;
37
+ declare(node.declaration, true);
38
+ for (const specifier of node.specifiers ?? []) if (specifier.exportKind !== "type") exported.set(specifier.exported.name ?? specifier.exported.value, node.source ? void 0 : specifier.local.name);
39
+ }
40
+ const result = {};
41
+ for (const [name, flag] of [
42
+ ["loader", "loader"],
43
+ ["beforeLoad", "guard"],
44
+ ["group", "group"],
45
+ ["validateSearch", "validateSearch"],
46
+ ["head", "head"],
47
+ ["ErrorBoundary", "errorBoundary"]
48
+ ]) if (exported.has(name)) result[flag] = true;
49
+ if (exported.has("dataMode")) {
50
+ let value = bindings.get(exported.get("dataMode"))?.value;
51
+ const visited = /* @__PURE__ */ new Set();
52
+ while (value) if ([
53
+ "TSAsExpression",
54
+ "TSSatisfiesExpression",
55
+ "TSTypeAssertion",
56
+ "ParenthesizedExpression"
57
+ ].includes(value.type)) value = value.expression;
58
+ else if (value.type === "Identifier" && !visited.has(value.name)) {
59
+ visited.add(value.name);
60
+ value = bindings.get(value.name)?.value;
61
+ } else break;
62
+ if (value?.type !== "Literal" || !["baked", "live"].includes(value.value)) throw new Error(`route/invalid-data-mode: ${file}: dataMode must resolve to a local const literal 'baked' or 'live'; declare it in the route module instead of computing or importing it`);
63
+ result.dataMode = value.value;
64
+ }
65
+ return result;
66
+ }
67
+ export { routeSourceMetadata };
@@ -0,0 +1,38 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import "node:child_process";
3
+ // ../cli/src/targets.ts
4
+ var readJson = (file) => {
5
+ try {
6
+ return JSON.parse(readFileSync(file, "utf8"));
7
+ } catch {
8
+ return null;
9
+ }
10
+ };
11
+ var hasNative = (cwd) => existsSync(`${cwd}/nativescript.config.ts`);
12
+ /** The opt-in macOS AppKit or WKWebView target currently used by apps/macos. */
13
+ var hasMacOS = (cwd) => readJson(`${cwd}/package.json`)?.xplat?.targets?.macos?.runtime === "appkit-node-api";
14
+ /** The declared Linux runtime: 'webkitgtk' (webview host, apps/linux) or
15
+ * 'gtk' (native GTK4/GJS renderer). Any other value is not a linux target. */
16
+ var linuxRuntime = (cwd) => {
17
+ const runtime = readJson(`${cwd}/package.json`)?.xplat?.targets?.linux?.runtime;
18
+ return runtime === "webkitgtk" || runtime === "gtk" ? runtime : null;
19
+ };
20
+ var hasLinux = (cwd) => linuxRuntime(cwd) !== null;
21
+ /** NativeScript platforms the app declares via its runtime devDeps —
22
+ * `@nativescript/ios`/`@nativescript/android`/`@nativescript/windows`.
23
+ * `nativescript.config.ts` alone doesn't say which platforms an app targets. */
24
+ function nsPlatforms(cwd) {
25
+ const manifest = readJson(`${cwd}/package.json`) ?? {};
26
+ const declared = {
27
+ ...manifest.dependencies,
28
+ ...manifest.devDependencies
29
+ };
30
+ return [
31
+ "ios",
32
+ "android",
33
+ "windows"
34
+ ].filter((platform) => typeof declared[`@nativescript/${platform}`] === "string");
35
+ }
36
+ /** Windows desktop target — the WinUI 3 host driven by `ns run windows`. */
37
+ var hasWindows = (cwd) => hasNative(cwd) && nsPlatforms(cwd).includes("windows");
38
+ export { hasLinux, hasMacOS, hasNative, hasWindows, linuxRuntime, nsPlatforms };