@mindees/compiler 0.3.0 → 0.5.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.
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ import { Maturity, NotImplementedError, PackageInfo, notImplemented } from "@min
10
10
  /** The npm package name. */
11
11
  declare const name = "@mindees/compiler";
12
12
  /** The package version. All `@mindees/*` packages share one locked version line. */
13
- declare const VERSION = "0.3.0";
13
+ declare const VERSION = "0.5.0";
14
14
  /**
15
15
  * Current maturity. The build-time optimizer — type-check gate, TSX→createElement
16
16
  * transform, tree-flattening, per-route manifest, plugin API — is implemented
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { NotImplementedError, notImplemented } from "@mindees/core";
8
8
  /** The npm package name. */
9
9
  const name = "@mindees/compiler";
10
10
  /** The package version. All `@mindees/*` packages share one locked version line. */
11
- const VERSION = "0.3.0";
11
+ const VERSION = "0.5.0";
12
12
  /**
13
13
  * Current maturity. The build-time optimizer — type-check gate, TSX→createElement
14
14
  * transform, tree-flattening, per-route manifest, plugin API — is implemented
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { Maturity, PackageInfo } from '@mindees/core'\nimport { NotImplementedError, notImplemented } from '@mindees/core'\n\n/** TS → native AOT (research track). */\nexport { compileToNative, type NativeTarget } from './aot'\n/** Tree-flattening optimizer pass. */\nexport { createFlattenTransformer, STATIC_MARKER } from './flatten'\n/** Per-route code-splitting manifest + file-based route codegen. */\nexport {\n buildRouteManifest,\n chunkName,\n fileToRoute,\n type GenerateRouteModuleOptions,\n generateRouteModule,\n type RouteEntry,\n type RouteManifest,\n} from './routes'\n/** Compile pipeline (TSX → optimized JS). */\nexport { compile, compileChecked } from './transform'\n/** The type-check gate. */\nexport { hasErrors, typecheck } from './typecheck'\n/** Shared types. */\nexport type {\n CompileOptions,\n CompileResult,\n CompileStats,\n Diagnostic,\n DiagnosticSeverity,\n MdcPlugin,\n SourcePosition,\n} from './types'\n\n/** The npm package name. */\nexport const name = '@mindees/compiler'\n\n/** The package version. All `@mindees/*` packages share one locked version line. */\nexport const VERSION = '0.3.0'\n\n/**\n * Current maturity. The build-time optimizer — type-check gate, TSX→createElement\n * transform, tree-flattening, per-route manifest, plugin API — is implemented\n * and tested on the TypeScript Compiler API. TS→native AOT is a research track\n * (throws `NotImplementedError`); the working path is TS → optimized JS.\n */\nexport const maturity: Maturity = 'experimental'\n\n/**\n * Static identity + maturity metadata for this package. Frozen so the\n * self-reported identity tooling introspects cannot be mutated at runtime,\n * matching the `readonly` fields of {@link PackageInfo}.\n */\nexport const info: PackageInfo = Object.freeze({ name, version: VERSION, maturity })\n\nexport type { Maturity, PackageInfo }\nexport { NotImplementedError, notImplemented }\n"],"mappings":";;;;;;;;AAiCA,MAAa,OAAO;;AAGpB,MAAa,UAAU;;;;;;;AAQvB,MAAa,WAAqB;;;;;;AAOlC,MAAa,OAAoB,OAAO,OAAO;CAAE;CAAM,SAAS;CAAS;AAAS,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { Maturity, PackageInfo } from '@mindees/core'\nimport { NotImplementedError, notImplemented } from '@mindees/core'\n\n/** TS → native AOT (research track). */\nexport { compileToNative, type NativeTarget } from './aot'\n/** Tree-flattening optimizer pass. */\nexport { createFlattenTransformer, STATIC_MARKER } from './flatten'\n/** Per-route code-splitting manifest + file-based route codegen. */\nexport {\n buildRouteManifest,\n chunkName,\n fileToRoute,\n type GenerateRouteModuleOptions,\n generateRouteModule,\n type RouteEntry,\n type RouteManifest,\n} from './routes'\n/** Compile pipeline (TSX → optimized JS). */\nexport { compile, compileChecked } from './transform'\n/** The type-check gate. */\nexport { hasErrors, typecheck } from './typecheck'\n/** Shared types. */\nexport type {\n CompileOptions,\n CompileResult,\n CompileStats,\n Diagnostic,\n DiagnosticSeverity,\n MdcPlugin,\n SourcePosition,\n} from './types'\n\n/** The npm package name. */\nexport const name = '@mindees/compiler'\n\n/** The package version. All `@mindees/*` packages share one locked version line. */\nexport const VERSION = '0.5.0'\n\n/**\n * Current maturity. The build-time optimizer — type-check gate, TSX→createElement\n * transform, tree-flattening, per-route manifest, plugin API — is implemented\n * and tested on the TypeScript Compiler API. TS→native AOT is a research track\n * (throws `NotImplementedError`); the working path is TS → optimized JS.\n */\nexport const maturity: Maturity = 'experimental'\n\n/**\n * Static identity + maturity metadata for this package. Frozen so the\n * self-reported identity tooling introspects cannot be mutated at runtime,\n * matching the `readonly` fields of {@link PackageInfo}.\n */\nexport const info: PackageInfo = Object.freeze({ name, version: VERSION, maturity })\n\nexport type { Maturity, PackageInfo }\nexport { NotImplementedError, notImplemented }\n"],"mappings":";;;;;;;;AAiCA,MAAa,OAAO;;AAGpB,MAAa,UAAU;;;;;;;AAQvB,MAAa,WAAqB;;;;;;AAOlC,MAAa,OAAoB,OAAO,OAAO;CAAE;CAAM,SAAS;CAAS;AAAS,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","names":[],"sources":["../src/routes.ts"],"mappings":";;AAaA;;;;;;;;;;AAUU;AAAA,UAVO,UAAA;EAca;EAZ5B,SAAA;EAakB;EAXlB,IAAA;EAWQ;EATR,KAAA;EAWQ;EATR,MAAA;EA4Bc;EA1Bd,QAAA;AAAA;;UAIe,aAAA;EACf,MAAA,EAAQ,UAAU;EAuBlB;EArBA,QAAA;AAAA;AAsBQ;AA4CV;;;;AAAsC;AAmBtC;;;AA/DU,iBAHM,WAAA,CAAY,IAAA;EAC1B,SAAA;EACA,MAAA;EACA,QAAA;AAAA;;iBA4Cc,SAAA,CAAU,IAAY;AA0FtC;;;;;;;AAAA,iBAvEgB,kBAAA,CAAmB,KAAA,sBAA2B,aAAa;AAyEjC;AAAA,UA1BzB,0BAAA;;EAEf,UAAA;;EAEA,UAAU;AAAA;;;;;;;;;;;;;;;;;;iBAoBI,mBAAA,CACd,KAAA,qBACA,OAAA,GAAS,0BAA+B"}
1
+ {"version":3,"file":"routes.d.ts","names":[],"sources":["../src/routes.ts"],"mappings":";;AAaA;;;;;;;;;;AAUU;AAAA,UAVO,UAAA;EAca;EAZ5B,SAAA;EAakB;EAXlB,IAAA;EAWQ;EATR,KAAA;EAWQ;EATR,MAAA;EA4Bc;EA1Bd,QAAA;AAAA;;UAIe,aAAA;EACf,MAAA,EAAQ,UAAU;EAuBlB;EArBA,QAAA;AAAA;AAsBQ;AA8CV;;;;AAAsC;AAmBtC;;;AAjEU,iBAHM,WAAA,CAAY,IAAA;EAC1B,SAAA;EACA,MAAA;EACA,QAAA;AAAA;;iBA8Cc,SAAA,CAAU,IAAY;AA6FtC;;;;;;;AAAA,iBA1EgB,kBAAA,CAAmB,KAAA,sBAA2B,aAAa;AA4EjC;AAAA,UA1BzB,0BAAA;;EAEf,UAAA;;EAEA,UAAU;AAAA;;;;;;;;;;;;;;;;;;iBAoBI,mBAAA,CACd,KAAA,qBACA,OAAA,GAAS,0BAA+B"}
package/dist/routes.js CHANGED
@@ -16,7 +16,7 @@ function stripExt(file) {
16
16
  function fileToRoute(file) {
17
17
  const params = [];
18
18
  let catchAll = false;
19
- const segments = stripExt(file).split("/").filter((s) => s.length > 0).filter((s) => !(s.startsWith("(") && s.endsWith(")"))).map((s) => {
19
+ const segments = stripExt(file.replace(/\\/g, "/")).split("/").filter((s) => s.length > 0).filter((s) => !(s.startsWith("(") && s.endsWith(")"))).map((s) => {
20
20
  if (s === "index") return "";
21
21
  const restMatch = s.match(/^\[\.\.\.(.+)\]$/);
22
22
  if (restMatch?.[1]) {
@@ -55,7 +55,8 @@ function buildRouteManifest(files) {
55
55
  let notFound;
56
56
  const byPath = /* @__PURE__ */ new Map();
57
57
  const byChunk = /* @__PURE__ */ new Map();
58
- for (const file of [...files].sort()) {
58
+ const normalized = files.map((f) => f.replace(/\\/g, "/"));
59
+ for (const file of [...normalized].sort()) {
59
60
  if (!ROUTE_FILE.test(file)) continue;
60
61
  const baseName = stripExt(file).split("/").pop() ?? "";
61
62
  if (baseName === "+not-found") {
@@ -103,7 +104,7 @@ function buildRouteManifest(files) {
103
104
  function generateRouteModule(files, options = {}) {
104
105
  const importBase = (options.importBase ?? "./app").replace(/\/+$/, "");
105
106
  const exportName = options.exportName ?? "routes";
106
- const routeFiles = [...files].filter((f) => ROUTE_FILE.test(f)).sort();
107
+ const routeFiles = [...files].map((f) => f.replace(/\\/g, "/")).filter((f) => ROUTE_FILE.test(f)).sort();
107
108
  const imports = routeFiles.map((file, i) => `import * as _route${i} from '${importBase}/${stripExt(file)}'`);
108
109
  const entries = routeFiles.map((file, i) => ` ${JSON.stringify(file)}: _route${i},`);
109
110
  const header = "// AUTO-GENERATED by @mindees/compiler generateRouteModule. Do not edit; regenerate when routes change.\n";
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../src/routes.ts"],"sourcesContent":["/**\n * Per-route code-splitting: build a route manifest from a file tree.\n *\n * MDC maps a routes directory (file-based routing, à la the Quantum Router) to a\n * **manifest** of chunks — one lazily-loadable entry per route — so the bundler\n * can split per route and the runtime can load a route's code on demand. This\n * pass is platform-agnostic: it produces the manifest; wiring it to a specific\n * bundler/runtime is the CLI's job (Phase 5) and the router's job (Phase 6).\n *\n * @module\n */\n\n/** A single route in the manifest. */\nexport interface RouteEntry {\n /** URL path, e.g. `/`, `/about`, `/blog/[slug]`. */\n routePath: string\n /** Source file implementing the route, relative to the routes dir. */\n file: string\n /** Stable chunk name for the split bundle, e.g. `route_blog_slug`. */\n chunk: string\n /** Dynamic param names parsed from the path, e.g. `[\"slug\"]`. */\n params: string[]\n /** True for a catch-all segment (`[...rest]`). */\n catchAll: boolean\n}\n\n/** The route manifest: every route plus a not-found fallback if present. */\nexport interface RouteManifest {\n routes: RouteEntry[]\n /** The `+not-found` route file, if any. */\n notFound?: string\n}\n\nconst ROUTE_FILE = /\\.(tsx|ts|jsx|js)$/\n\n/** Strip the file extension. */\nfunction stripExt(file: string): string {\n return file.replace(ROUTE_FILE, '')\n}\n\n/**\n * Convert a file path (relative, POSIX separators) to a route path + params.\n *\n * Conventions (subset of the Quantum Router, see ROADMAP Phase 6):\n * - `index` → the directory's path (`index.tsx` → `/`).\n * - `[param]` → a dynamic segment (`:param`); collected into `params`.\n * - `[...rest]` → a catch-all segment; sets `catchAll`.\n * - `(group)` → a layout group that does NOT affect the URL (removed).\n */\nexport function fileToRoute(file: string): {\n routePath: string\n params: string[]\n catchAll: boolean\n} {\n const params: string[] = []\n let catchAll = false\n\n const segments = stripExt(file)\n .split('/')\n .filter((s) => s.length > 0)\n // Drop layout groups like `(marketing)`.\n .filter((s) => !(s.startsWith('(') && s.endsWith(')')))\n .map((s) => {\n // index → empty (resolves to parent path)\n if (s === 'index') return ''\n // [...rest] → catch-all\n const restMatch = s.match(/^\\[\\.\\.\\.(.+)\\]$/)\n if (restMatch?.[1]) {\n catchAll = true\n params.push(restMatch[1])\n return `:${restMatch[1]}*`\n }\n // [param] → dynamic\n const paramMatch = s.match(/^\\[(.+)\\]$/)\n if (paramMatch?.[1]) {\n params.push(paramMatch[1])\n return `:${paramMatch[1]}`\n }\n return s\n })\n .filter((s) => s.length > 0)\n\n // A catch-all must terminate the path; `docs/[...rest]/edit` is structurally\n // invalid and would otherwise emit a nonsensical `/docs/:rest*/edit`.\n const catchAllIndex = segments.findIndex((s) => s.endsWith('*'))\n if (catchAllIndex !== -1 && catchAllIndex !== segments.length - 1) {\n throw new Error(\n `Invalid route file \"${file}\": a catch-all segment ([...x]) must be the last segment.`,\n )\n }\n\n const routePath = segments.length === 0 ? '/' : `/${segments.join('/')}`\n return { routePath, params, catchAll }\n}\n\n/** Build a stable chunk name from a route file (filesystem-safe identifier). */\nexport function chunkName(file: string): string {\n const base = stripExt(file)\n .replace(/[/\\\\]/g, '_')\n .replace(/\\[\\.\\.\\.(.+?)\\]/g, 'rest_$1')\n .replace(/\\[(.+?)\\]/g, '$1')\n .replace(/[()]/g, '')\n .replace(/[^a-zA-Z0-9_]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n return `route_${base || 'index'}`\n}\n\n/**\n * Build a {@link RouteManifest} from a list of route files (relative paths,\n * POSIX `/` separators). Routes are sorted for deterministic output.\n *\n * @example\n * buildRouteManifest(['index.tsx', 'about.tsx', 'blog/[slug].tsx', '+not-found.tsx'])\n */\nexport function buildRouteManifest(files: readonly string[]): RouteManifest {\n const routes: RouteEntry[] = []\n let notFound: string | undefined\n // Detect collisions (e.g. `index.tsx` and `(app)/index.tsx` both map to `/`).\n const byPath = new Map<string, string>()\n // Distinct routes must also get distinct chunk names — `chunkName` is lossy\n // (e.g. `blog/[slug]` and `blog/slug` both strip to `route_blog_slug`), so a\n // collision here would silently make two routes share one split bundle.\n const byChunk = new Map<string, string>()\n\n for (const file of [...files].sort()) {\n if (!ROUTE_FILE.test(file)) continue\n const baseName = stripExt(file).split('/').pop() ?? ''\n if (baseName === '+not-found') {\n notFound = file\n continue\n }\n // Skip layout files (`_layout`) and other reserved `_`/`+` prefixed files\n // from the navigable route table (they're handled separately by the router).\n if (baseName.startsWith('_') || baseName.startsWith('+')) continue\n\n const { routePath, params, catchAll } = fileToRoute(file)\n const prior = byPath.get(routePath)\n if (prior !== undefined) {\n throw new Error(\n `Duplicate route path \"${routePath}\": both \"${prior}\" and \"${file}\" map to it.`,\n )\n }\n byPath.set(routePath, file)\n const chunk = chunkName(file)\n const priorChunk = byChunk.get(chunk)\n if (priorChunk !== undefined) {\n throw new Error(\n `Duplicate chunk name \"${chunk}\": both \"${priorChunk}\" and \"${file}\" produce it; ` +\n 'rename one route file so their split bundles do not collide.',\n )\n }\n byChunk.set(chunk, file)\n routes.push({ routePath, file, chunk, params, catchAll })\n }\n\n const manifest: RouteManifest = { routes }\n if (notFound !== undefined) manifest.notFound = notFound\n return manifest\n}\n\n/** Options for {@link generateRouteModule}. */\nexport interface GenerateRouteModuleOptions {\n /** Import-specifier prefix for the route files. Default `'./app'`. */\n importBase?: string\n /** Name of the exported module-map constant. Default `'routes'`. */\n exportName?: string\n}\n\n/**\n * Generate a TypeScript module that statically imports every route file and exposes\n * them as a module map keyed by relative path — exactly the input\n * `@mindees/router`'s `createFileRouter`/`routesFromModules` consume.\n *\n * This is the codegen behind **file-based routing** for bundlers without\n * `import.meta.glob` (e.g. an embedded-engine native bundle): scan the `app/` dir, run\n * this over the file list, write the result (e.g. `routes.gen.ts`), and import the map.\n * Files are sorted for deterministic output. (`_layout`/`+not-found` are intentionally\n * kept — the router applies them via its conventions.)\n *\n * @example\n * generateRouteModule(['index.tsx', 'about.tsx'], { importBase: './app' })\n * // import * as _route0 from './app/about'\n * // import * as _route1 from './app/index'\n * // export const routes = { 'about.tsx': _route0, 'index.tsx': _route1 }\n */\nexport function generateRouteModule(\n files: readonly string[],\n options: GenerateRouteModuleOptions = {},\n): string {\n const importBase = (options.importBase ?? './app').replace(/\\/+$/, '')\n const exportName = options.exportName ?? 'routes'\n const routeFiles = [...files].filter((f) => ROUTE_FILE.test(f)).sort()\n const imports = routeFiles.map(\n (file, i) => `import * as _route${i} from '${importBase}/${stripExt(file)}'`,\n )\n const entries = routeFiles.map((file, i) => ` ${JSON.stringify(file)}: _route${i},`)\n const header =\n '// AUTO-GENERATED by @mindees/compiler generateRouteModule. Do not edit; regenerate when routes change.\\n'\n const body = `export const ${exportName} = {\\n${entries.join('\\n')}\\n}\\n`\n return imports.length > 0 ? `${header}${imports.join('\\n')}\\n\\n${body}` : `${header}${body}`\n}\n"],"mappings":";AAiCA,MAAM,aAAa;;AAGnB,SAAS,SAAS,MAAsB;CACtC,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;;;;;;;;;AAWA,SAAgB,YAAY,MAI1B;CACA,MAAM,SAAmB,CAAC;CAC1B,IAAI,WAAW;CAEf,MAAM,WAAW,SAAS,IAAI,EAC3B,MAAM,GAAG,EACT,QAAQ,MAAM,EAAE,SAAS,CAAC,EAE1B,QAAQ,MAAM,EAAE,EAAE,WAAW,GAAG,K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IAAI,EAAE,MAAM,SAAS,GAAG,SAAS;AACxF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../src/routes.ts"],"sourcesContent":["/**\n * Per-route code-splitting: build a route manifest from a file tree.\n *\n * MDC maps a routes directory (file-based routing, à la the Quantum Router) to a\n * **manifest** of chunks — one lazily-loadable entry per route — so the bundler\n * can split per route and the runtime can load a route's code on demand. This\n * pass is platform-agnostic: it produces the manifest; wiring it to a specific\n * bundler/runtime is the CLI's job (Phase 5) and the router's job (Phase 6).\n *\n * @module\n */\n\n/** A single route in the manifest. */\nexport interface RouteEntry {\n /** URL path, e.g. `/`, `/about`, `/blog/[slug]`. */\n routePath: string\n /** Source file implementing the route, relative to the routes dir. */\n file: string\n /** Stable chunk name for the split bundle, e.g. `route_blog_slug`. */\n chunk: string\n /** Dynamic param names parsed from the path, e.g. `[\"slug\"]`. */\n params: string[]\n /** True for a catch-all segment (`[...rest]`). */\n catchAll: boolean\n}\n\n/** The route manifest: every route plus a not-found fallback if present. */\nexport interface RouteManifest {\n routes: RouteEntry[]\n /** The `+not-found` route file, if any. */\n notFound?: string\n}\n\nconst ROUTE_FILE = /\\.(tsx|ts|jsx|js)$/\n\n/** Strip the file extension. */\nfunction stripExt(file: string): string {\n return file.replace(ROUTE_FILE, '')\n}\n\n/**\n * Convert a file path (relative, POSIX separators) to a route path + params.\n *\n * Conventions (subset of the Quantum Router, see ROADMAP Phase 6):\n * - `index` → the directory's path (`index.tsx` → `/`).\n * - `[param]` → a dynamic segment (`:param`); collected into `params`.\n * - `[...rest]` → a catch-all segment; sets `catchAll`.\n * - `(group)` → a layout group that does NOT affect the URL (removed).\n */\nexport function fileToRoute(file: string): {\n routePath: string\n params: string[]\n catchAll: boolean\n} {\n const params: string[] = []\n let catchAll = false\n\n // Normalize Windows separators: a backslash path (what `path.join` yields on Windows) would\n // otherwise never split into segments, collapsing the whole route to one literal segment.\n const segments = stripExt(file.replace(/\\\\/g, '/'))\n .split('/')\n .filter((s) => s.length > 0)\n // Drop layout groups like `(marketing)`.\n .filter((s) => !(s.startsWith('(') && s.endsWith(')')))\n .map((s) => {\n // index → empty (resolves to parent path)\n if (s === 'index') return ''\n // [...rest] → catch-all\n const restMatch = s.match(/^\\[\\.\\.\\.(.+)\\]$/)\n if (restMatch?.[1]) {\n catchAll = true\n params.push(restMatch[1])\n return `:${restMatch[1]}*`\n }\n // [param] → dynamic\n const paramMatch = s.match(/^\\[(.+)\\]$/)\n if (paramMatch?.[1]) {\n params.push(paramMatch[1])\n return `:${paramMatch[1]}`\n }\n return s\n })\n .filter((s) => s.length > 0)\n\n // A catch-all must terminate the path; `docs/[...rest]/edit` is structurally\n // invalid and would otherwise emit a nonsensical `/docs/:rest*/edit`.\n const catchAllIndex = segments.findIndex((s) => s.endsWith('*'))\n if (catchAllIndex !== -1 && catchAllIndex !== segments.length - 1) {\n throw new Error(\n `Invalid route file \"${file}\": a catch-all segment ([...x]) must be the last segment.`,\n )\n }\n\n const routePath = segments.length === 0 ? '/' : `/${segments.join('/')}`\n return { routePath, params, catchAll }\n}\n\n/** Build a stable chunk name from a route file (filesystem-safe identifier). */\nexport function chunkName(file: string): string {\n const base = stripExt(file)\n .replace(/[/\\\\]/g, '_')\n .replace(/\\[\\.\\.\\.(.+?)\\]/g, 'rest_$1')\n .replace(/\\[(.+?)\\]/g, '$1')\n .replace(/[()]/g, '')\n .replace(/[^a-zA-Z0-9_]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '')\n return `route_${base || 'index'}`\n}\n\n/**\n * Build a {@link RouteManifest} from a list of route files (relative paths,\n * POSIX `/` separators). Routes are sorted for deterministic output.\n *\n * @example\n * buildRouteManifest(['index.tsx', 'about.tsx', 'blog/[slug].tsx', '+not-found.tsx'])\n */\nexport function buildRouteManifest(files: readonly string[]): RouteManifest {\n const routes: RouteEntry[] = []\n let notFound: string | undefined\n // Detect collisions (e.g. `index.tsx` and `(app)/index.tsx` both map to `/`).\n const byPath = new Map<string, string>()\n // Distinct routes must also get distinct chunk names — `chunkName` is lossy\n // (e.g. `blog/[slug]` and `blog/slug` both strip to `route_blog_slug`), so a\n // collision here would silently make two routes share one split bundle.\n const byChunk = new Map<string, string>()\n\n // Normalize separators up front so the manifest's `file` (an `import()` specifier — backslashes\n // are invalid there), chunk names, and route paths are all POSIX, regardless of the host OS.\n const normalized = files.map((f) => f.replace(/\\\\/g, '/'))\n for (const file of [...normalized].sort()) {\n if (!ROUTE_FILE.test(file)) continue\n const baseName = stripExt(file).split('/').pop() ?? ''\n if (baseName === '+not-found') {\n notFound = file\n continue\n }\n // Skip layout files (`_layout`) and other reserved `_`/`+` prefixed files\n // from the navigable route table (they're handled separately by the router).\n if (baseName.startsWith('_') || baseName.startsWith('+')) continue\n\n const { routePath, params, catchAll } = fileToRoute(file)\n const prior = byPath.get(routePath)\n if (prior !== undefined) {\n throw new Error(\n `Duplicate route path \"${routePath}\": both \"${prior}\" and \"${file}\" map to it.`,\n )\n }\n byPath.set(routePath, file)\n const chunk = chunkName(file)\n const priorChunk = byChunk.get(chunk)\n if (priorChunk !== undefined) {\n throw new Error(\n `Duplicate chunk name \"${chunk}\": both \"${priorChunk}\" and \"${file}\" produce it; ` +\n 'rename one route file so their split bundles do not collide.',\n )\n }\n byChunk.set(chunk, file)\n routes.push({ routePath, file, chunk, params, catchAll })\n }\n\n const manifest: RouteManifest = { routes }\n if (notFound !== undefined) manifest.notFound = notFound\n return manifest\n}\n\n/** Options for {@link generateRouteModule}. */\nexport interface GenerateRouteModuleOptions {\n /** Import-specifier prefix for the route files. Default `'./app'`. */\n importBase?: string\n /** Name of the exported module-map constant. Default `'routes'`. */\n exportName?: string\n}\n\n/**\n * Generate a TypeScript module that statically imports every route file and exposes\n * them as a module map keyed by relative path — exactly the input\n * `@mindees/router`'s `createFileRouter`/`routesFromModules` consume.\n *\n * This is the codegen behind **file-based routing** for bundlers without\n * `import.meta.glob` (e.g. an embedded-engine native bundle): scan the `app/` dir, run\n * this over the file list, write the result (e.g. `routes.gen.ts`), and import the map.\n * Files are sorted for deterministic output. (`_layout`/`+not-found` are intentionally\n * kept — the router applies them via its conventions.)\n *\n * @example\n * generateRouteModule(['index.tsx', 'about.tsx'], { importBase: './app' })\n * // import * as _route0 from './app/about'\n * // import * as _route1 from './app/index'\n * // export const routes = { 'about.tsx': _route0, 'index.tsx': _route1 }\n */\nexport function generateRouteModule(\n files: readonly string[],\n options: GenerateRouteModuleOptions = {},\n): string {\n const importBase = (options.importBase ?? './app').replace(/\\/+$/, '')\n const exportName = options.exportName ?? 'routes'\n // Normalize separators: backslashes are invalid in import specifiers, and the map keys must be\n // the POSIX paths `routesFromModules` matches against.\n const routeFiles = [...files]\n .map((f) => f.replace(/\\\\/g, '/'))\n .filter((f) => ROUTE_FILE.test(f))\n .sort()\n const imports = routeFiles.map(\n (file, i) => `import * as _route${i} from '${importBase}/${stripExt(file)}'`,\n )\n const entries = routeFiles.map((file, i) => ` ${JSON.stringify(file)}: _route${i},`)\n const header =\n '// AUTO-GENERATED by @mindees/compiler generateRouteModule. Do not edit; regenerate when routes change.\\n'\n const body = `export const ${exportName} = {\\n${entries.join('\\n')}\\n}\\n`\n return imports.length > 0 ? `${header}${imports.join('\\n')}\\n\\n${body}` : `${header}${body}`\n}\n"],"mappings":";AAiCA,MAAM,aAAa;;AAGnB,SAAS,SAAS,MAAsB;CACtC,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;;;;;;;;;AAWA,SAAgB,YAAY,MAI1B;CACA,MAAM,SAAmB,CAAC;CAC1B,IAAI,WAAW;CAIf,MAAM,WAAW,SAAS,KAAK,QAAQ,OAAO,GAAG,CAAC,EAC/C,MAAM,GAAG,EACT,QAAQ,MAAM,EAAE,SAAS,CAAC,EAE1B,QAAQ,MAAM,EAAE,EAAE,WAAW,GAAG,KAAK,EAAE,SAAS,GAAG,EAAE,EACrD,KAAK,MAAM;EAEV,IAAI,MAAM,SAAS,OAAO;EAE1B,MAAM,YAAY,EAAE,MAAM,kBAAkB;EAC5C,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EAAE,MAAM,SAAS,GAAG,SAAS;AACxF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindees/compiler",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "MindeesNative Compiler (MDC) — build-time optimizer: type-check gate, TSX→createElement transform, tree-flattening, per-route code-splitting, and a plugin API. TS→native AOT is a research track.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "type": "module",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "typescript": "6.0.3",
27
- "@mindees/core": "0.3.0"
27
+ "@mindees/core": "0.5.0"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "tsdown",