@mindees/compiler 0.1.0 → 0.3.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/README.md CHANGED
@@ -10,6 +10,12 @@ manifest, and a **plugin API**.
10
10
  > is a research track (`compileToNative` throws `NotImplementedError`). APIs may
11
11
  > change before `1.0`.
12
12
 
13
+ ## Install
14
+
15
+ ```bash
16
+ pnpm add -D @mindees/compiler
17
+ ```
18
+
13
19
  ## Why the TypeScript Compiler API?
14
20
 
15
21
  Only TypeScript can **type-check** — the compiler's #1 job. It also does JSX
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { NativeTarget, compileToNative } from "./aot.js";
2
2
  import { CompileOptions, CompileResult, CompileStats, Diagnostic, DiagnosticSeverity, MdcPlugin, SourcePosition } from "./types.js";
3
3
  import { STATIC_MARKER, createFlattenTransformer } from "./flatten.js";
4
- import { RouteEntry, RouteManifest, buildRouteManifest, chunkName, fileToRoute } from "./routes.js";
4
+ import { GenerateRouteModuleOptions, RouteEntry, RouteManifest, buildRouteManifest, chunkName, fileToRoute, generateRouteModule } from "./routes.js";
5
5
  import { compile, compileChecked } from "./transform.js";
6
6
  import { hasErrors, typecheck } from "./typecheck.js";
7
7
  import { Maturity, NotImplementedError, PackageInfo, notImplemented } from "@mindees/core";
@@ -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.1.0";
13
+ declare const VERSION = "0.3.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
@@ -25,5 +25,5 @@ declare const maturity: Maturity;
25
25
  */
26
26
  declare const info: PackageInfo;
27
27
  //#endregion
28
- export { type CompileOptions, type CompileResult, type CompileStats, type Diagnostic, type DiagnosticSeverity, type Maturity, type MdcPlugin, type NativeTarget, NotImplementedError, type PackageInfo, type RouteEntry, type RouteManifest, STATIC_MARKER, type SourcePosition, VERSION, buildRouteManifest, chunkName, compile, compileChecked, compileToNative, createFlattenTransformer, fileToRoute, hasErrors, info, maturity, name, notImplemented, typecheck };
28
+ export { type CompileOptions, type CompileResult, type CompileStats, type Diagnostic, type DiagnosticSeverity, type GenerateRouteModuleOptions, type Maturity, type MdcPlugin, type NativeTarget, NotImplementedError, type PackageInfo, type RouteEntry, type RouteManifest, STATIC_MARKER, type SourcePosition, VERSION, buildRouteManifest, chunkName, compile, compileChecked, compileToNative, createFlattenTransformer, fileToRoute, generateRouteModule, hasErrors, info, maturity, name, notImplemented, typecheck };
29
29
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;AAkCA;AAAA,cAHa,IAAA;;cAGA,OAAA;AAAO;AAQpB;;;;AAAgD;AAR5B,cAQP,QAAA,EAAU,QAAyB;;;;AAOoC;;cAAvE,IAAA,EAAM,WAAiE"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;AAoCA;AAAA,cAHa,IAAA;;cAGA,OAAA;AAAO;AAQpB;;;;AAAgD;AAR5B,cAQP,QAAA,EAAU,QAAyB;;;;AAOoC;;cAAvE,IAAA,EAAM,WAAiE"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { compileToNative } from "./aot.js";
2
2
  import { STATIC_MARKER, createFlattenTransformer } from "./flatten.js";
3
- import { buildRouteManifest, chunkName, fileToRoute } from "./routes.js";
3
+ import { buildRouteManifest, chunkName, fileToRoute, generateRouteModule } from "./routes.js";
4
4
  import { hasErrors, typecheck } from "./typecheck.js";
5
5
  import { compile, compileChecked } from "./transform.js";
6
6
  import { NotImplementedError, notImplemented } from "@mindees/core";
@@ -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.1.0";
11
+ const VERSION = "0.3.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
@@ -27,6 +27,6 @@ const info = Object.freeze({
27
27
  maturity
28
28
  });
29
29
  //#endregion
30
- export { NotImplementedError, STATIC_MARKER, VERSION, buildRouteManifest, chunkName, compile, compileChecked, compileToNative, createFlattenTransformer, fileToRoute, hasErrors, info, maturity, name, notImplemented, typecheck };
30
+ export { NotImplementedError, STATIC_MARKER, VERSION, buildRouteManifest, chunkName, compile, compileChecked, compileToNative, createFlattenTransformer, fileToRoute, generateRouteModule, hasErrors, info, maturity, name, notImplemented, typecheck };
31
31
 
32
32
  //# sourceMappingURL=index.js.map
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. */\nexport {\n buildRouteManifest,\n chunkName,\n fileToRoute,\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.1.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":";;;;;;;;AA+BA,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.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"}
package/dist/routes.d.ts CHANGED
@@ -53,6 +53,31 @@ declare function chunkName(file: string): string;
53
53
  * buildRouteManifest(['index.tsx', 'about.tsx', 'blog/[slug].tsx', '+not-found.tsx'])
54
54
  */
55
55
  declare function buildRouteManifest(files: readonly string[]): RouteManifest;
56
+ /** Options for {@link generateRouteModule}. */
57
+ interface GenerateRouteModuleOptions {
58
+ /** Import-specifier prefix for the route files. Default `'./app'`. */
59
+ importBase?: string;
60
+ /** Name of the exported module-map constant. Default `'routes'`. */
61
+ exportName?: string;
62
+ }
63
+ /**
64
+ * Generate a TypeScript module that statically imports every route file and exposes
65
+ * them as a module map keyed by relative path — exactly the input
66
+ * `@mindees/router`'s `createFileRouter`/`routesFromModules` consume.
67
+ *
68
+ * This is the codegen behind **file-based routing** for bundlers without
69
+ * `import.meta.glob` (e.g. an embedded-engine native bundle): scan the `app/` dir, run
70
+ * this over the file list, write the result (e.g. `routes.gen.ts`), and import the map.
71
+ * Files are sorted for deterministic output. (`_layout`/`+not-found` are intentionally
72
+ * kept — the router applies them via its conventions.)
73
+ *
74
+ * @example
75
+ * generateRouteModule(['index.tsx', 'about.tsx'], { importBase: './app' })
76
+ * // import * as _route0 from './app/about'
77
+ * // import * as _route1 from './app/index'
78
+ * // export const routes = { 'about.tsx': _route0, 'index.tsx': _route1 }
79
+ */
80
+ declare function generateRouteModule(files: readonly string[], options?: GenerateRouteModuleOptions): string;
56
81
  //#endregion
57
- export { RouteEntry, RouteManifest, buildRouteManifest, chunkName, fileToRoute };
82
+ export { GenerateRouteModuleOptions, RouteEntry, RouteManifest, buildRouteManifest, chunkName, fileToRoute, generateRouteModule };
58
83
  //# sourceMappingURL=routes.d.ts.map
@@ -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;;;;;;;;iBAmBtB,kBAAA,CAAmB,KAAA,sBAA2B,aAAa"}
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"}
package/dist/routes.js CHANGED
@@ -83,7 +83,34 @@ function buildRouteManifest(files) {
83
83
  if (notFound !== void 0) manifest.notFound = notFound;
84
84
  return manifest;
85
85
  }
86
+ /**
87
+ * Generate a TypeScript module that statically imports every route file and exposes
88
+ * them as a module map keyed by relative path — exactly the input
89
+ * `@mindees/router`'s `createFileRouter`/`routesFromModules` consume.
90
+ *
91
+ * This is the codegen behind **file-based routing** for bundlers without
92
+ * `import.meta.glob` (e.g. an embedded-engine native bundle): scan the `app/` dir, run
93
+ * this over the file list, write the result (e.g. `routes.gen.ts`), and import the map.
94
+ * Files are sorted for deterministic output. (`_layout`/`+not-found` are intentionally
95
+ * kept — the router applies them via its conventions.)
96
+ *
97
+ * @example
98
+ * generateRouteModule(['index.tsx', 'about.tsx'], { importBase: './app' })
99
+ * // import * as _route0 from './app/about'
100
+ * // import * as _route1 from './app/index'
101
+ * // export const routes = { 'about.tsx': _route0, 'index.tsx': _route1 }
102
+ */
103
+ function generateRouteModule(files, options = {}) {
104
+ const importBase = (options.importBase ?? "./app").replace(/\/+$/, "");
105
+ const exportName = options.exportName ?? "routes";
106
+ const routeFiles = [...files].filter((f) => ROUTE_FILE.test(f)).sort();
107
+ const imports = routeFiles.map((file, i) => `import * as _route${i} from '${importBase}/${stripExt(file)}'`);
108
+ const entries = routeFiles.map((file, i) => ` ${JSON.stringify(file)}: _route${i},`);
109
+ const header = "// AUTO-GENERATED by @mindees/compiler generateRouteModule. Do not edit; regenerate when routes change.\n";
110
+ const body = `export const ${exportName} = {\n${entries.join("\n")}\n}\n`;
111
+ return imports.length > 0 ? `${header}${imports.join("\n")}\n\n${body}` : `${header}${body}`;
112
+ }
86
113
  //#endregion
87
- export { buildRouteManifest, chunkName, fileToRoute };
114
+ export { buildRouteManifest, chunkName, fileToRoute, generateRouteModule };
88
115
 
89
116
  //# sourceMappingURL=routes.js.map
@@ -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"],"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,KAAK,EAAE,SAAS,GAAG,EAAE,EACrD,KAAK,MAAM;EAEV,IAAI,MAAM,SAAS,OAAO;EAE1B,MAAM,YAAY,EAAE,MAAM,kBAAkB;EAC5C,IAAI,YAAY,IAAI;GAClB,WAAW;GACX,OAAO,KAAK,UAAU,EAAE;GACxB,OAAO,IAAI,UAAU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A,GACZ,MAAM,IAAI,MACR,yBAAyB,UAAU,WAAW,MAAM,SAAS,KAAK,aACpE;EAEF,OAAO,IAAI,WAAW,IAAI;EAC1B,MAAM,QAAQ,UAAU,IAAI;EAC5B,MAAM,aAAa,QAAQ,IAAI,KAAK;EACpC,IAAI,eAAe,KAAA,GACjB,MAAM,IAAI,MACR,yBAAyB,MAAM,WAAW,WAAW,SAAS,KAAK,2EAErE;EAEF,QAAQ,IAAI,OAAO,IAAI;EACvB,OAAO,KAAK;GAAE;GAAW;GAAM;GAAO;GAAQ;EAAS,CAAC;CAC1D;CAEA,MAAM,WAA0B,EAAE,OAAO;CACzC,IAAI,aAAa,KAAA,GAAW,SAAS,WAAW;CAChD,OAAO;AACT"}
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,KAAK,EAAE,SAAS,GAAG,EAAE,EACrD,KAAK,MAAM;EAEV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+1 @@
1
- {"version":3,"file":"transform.d.ts","names":[],"sources":["../src/transform.ts"],"mappings":";;;AAqCoF;AAoDpF;;;;;;;AApDoF,iBAApE,OAAA,CAAQ,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa;;AAoDO;;;iBAA3E,cAAA,CAAe,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa"}
1
+ {"version":3,"file":"transform.d.ts","names":[],"sources":["../src/transform.ts"],"mappings":";;;AA8FoF;AAuDpF;;;;;;;AAvDoF,iBAApE,OAAA,CAAQ,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa;;AAuDO;;;iBAA3E,cAAA,CAAe,MAAA,UAAgB,OAAA,GAAS,cAAA,GAAsB,aAAa"}
package/dist/transform.js CHANGED
@@ -13,7 +13,7 @@ import ts from "typescript";
13
13
  *
14
14
  * @module
15
15
  */
16
- /** Compiler options for emit (JSX classic → createElement/Fragment). */
16
+ /** Compiler options for emit (JSX → `createElement`/`Fragment`, which the optimizer matches). */
17
17
  function emitOptions(sourceMap) {
18
18
  return {
19
19
  jsx: ts.JsxEmit.React,
@@ -24,6 +24,35 @@ function emitOptions(sourceMap) {
24
24
  sourceMap
25
25
  };
26
26
  }
27
+ /** Runtime names the JSX desugar references; injected from `@mindees/core` if unbound. */
28
+ const RUNTIME_NAMES = ["createElement", "Fragment"];
29
+ /**
30
+ * Ensure the JSX runtime is in scope. Idiomatic components use **automatic JSX** and import
31
+ * nothing, but we emit classic `createElement(...)`/`Fragment` (so the tree-flatten optimizer
32
+ * can match them) — which would be unbound at runtime. This transformer prepends
33
+ * `import { createElement, Fragment } from '@mindees/core'` for any runtime name that is
34
+ * referenced but not already imported, so emitted modules run. Runs LAST (after flatten/plugins),
35
+ * so names the optimizer removed don't get a needless import.
36
+ */
37
+ function createRuntimeImportTransformer(tsmod) {
38
+ return (context) => (sourceFile) => {
39
+ const imported = /* @__PURE__ */ new Set();
40
+ for (const stmt of sourceFile.statements) if (tsmod.isImportDeclaration(stmt) && tsmod.isStringLiteral(stmt.moduleSpecifier) && stmt.moduleSpecifier.text === "@mindees/core") {
41
+ const named = stmt.importClause?.namedBindings;
42
+ if (named && tsmod.isNamedImports(named)) for (const el of named.elements) imported.add((el.propertyName ?? el.name).text);
43
+ }
44
+ const referenced = /* @__PURE__ */ new Set();
45
+ const visit = (node) => {
46
+ if (tsmod.isIdentifier(node) && RUNTIME_NAMES.includes(node.text)) referenced.add(node.text);
47
+ tsmod.forEachChild(node, visit);
48
+ };
49
+ visit(sourceFile);
50
+ const missing = RUNTIME_NAMES.filter((n) => referenced.has(n) && !imported.has(n));
51
+ if (missing.length === 0) return sourceFile;
52
+ const importDecl = tsmod.factory.createImportDeclaration(void 0, tsmod.factory.createImportClause(false, void 0, tsmod.factory.createNamedImports(missing.map((n) => tsmod.factory.createImportSpecifier(false, void 0, tsmod.factory.createIdentifier(n))))), tsmod.factory.createStringLiteral("@mindees/core"));
53
+ return context.factory.updateSourceFile(sourceFile, [importDecl, ...sourceFile.statements]);
54
+ };
55
+ }
27
56
  /**
28
57
  * Compile a single TSX/TS module to JavaScript.
29
58
  *
@@ -45,6 +74,7 @@ function compile(source, options = {}) {
45
74
  stats = flattener.stats;
46
75
  }
47
76
  for (const plugin of plugins) after.push(plugin.transformer(ts));
77
+ after.push(createRuntimeImportTransformer(ts));
48
78
  const output = ts.transpileModule(source, {
49
79
  compilerOptions: emitOptions(sourceMap),
50
80
  fileName,
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","names":[],"sources":["../src/transform.ts"],"sourcesContent":["/**\n * The MDC transform/compile pipeline.\n *\n * `compile()` lowers TSX → `createElement(...)` (matching `@mindees/core`'s\n * factory), runs the built-in optimizer passes (tree-flattening) plus any user\n * plugins, and emits JavaScript + a source map. It does **not** type-check\n * (that's {@link typecheck}); `compileChecked()` runs the gate first and refuses\n * to emit on `error` diagnostics.\n *\n * @module\n */\n\nimport ts from 'typescript'\nimport { createFlattenTransformer } from './flatten'\nimport { hasErrors, typecheck } from './typecheck'\nimport type { CompileOptions, CompileResult, CompileStats } from './types'\n\n/** Compiler options for emit (JSX classic → createElement/Fragment). */\nfunction emitOptions(sourceMap: boolean): ts.CompilerOptions {\n return {\n jsx: ts.JsxEmit.React,\n jsxFactory: 'createElement',\n jsxFragmentFactory: 'Fragment',\n target: ts.ScriptTarget.ES2023,\n module: ts.ModuleKind.ESNext,\n sourceMap,\n }\n}\n\n/**\n * Compile a single TSX/TS module to JavaScript.\n *\n * Pipeline: JSX desugar → tree-flatten (optional) → user plugins → emit.\n * Returns emitted code, an optional source map, any (transpile-level)\n * diagnostics, and optimizer stats. Use {@link compileChecked} to gate on the\n * full type checker.\n */\nexport function compile(source: string, options: CompileOptions = {}): CompileResult {\n const { fileName = 'module.tsx', sourceMap = true, flatten = true, plugins = [] } = options\n\n // IMPORTANT: our optimizer + plugins operate on the desugared\n // `createElement(...)` call form, but `transpileModule` runs `before`\n // transformers on the *pre-desugar* JSX AST. JSX is lowered during the\n // `after` phase, so flatten/plugins must run there to see the calls.\n const after: ts.TransformerFactory<ts.SourceFile>[] = []\n let stats: CompileStats = { flattenedNodes: 0, totalElements: 0 }\n\n if (flatten) {\n const flattener = createFlattenTransformer(ts)\n after.push(flattener.factory)\n stats = flattener.stats // live object, updated during emit\n }\n\n for (const plugin of plugins) {\n after.push(plugin.transformer(ts) as ts.TransformerFactory<ts.SourceFile>)\n }\n\n const output = ts.transpileModule(source, {\n compilerOptions: emitOptions(sourceMap),\n fileName,\n reportDiagnostics: true,\n transformers: { after },\n })\n\n // transpileModule only surfaces a few syntactic diagnostics; semantic ones\n // come from the type-check gate. Map each to our structured form.\n const diagnostics = (output.diagnostics ?? []).map((d) => {\n const message = ts.flattenDiagnosticMessageText(d.messageText, '\\n')\n return {\n severity:\n d.category === ts.DiagnosticCategory.Error ? ('error' as const) : ('warning' as const),\n code: `TS${d.code}`,\n message,\n }\n })\n\n const result: CompileResult = {\n code: output.outputText,\n diagnostics,\n stats,\n }\n if (sourceMap && output.sourceMapText) result.map = output.sourceMapText\n return result\n}\n\n/**\n * Type-check then compile. If the gate finds any `error` diagnostic, returns it\n * WITHOUT emitting code (`code: ''`) — the build must not ship type errors.\n */\nexport function compileChecked(source: string, options: CompileOptions = {}): CompileResult {\n const fileName = options.fileName ?? 'module.tsx'\n const diagnostics = typecheck(source, fileName)\n if (hasErrors(diagnostics)) {\n return { code: '', diagnostics, stats: { flattenedNodes: 0, totalElements: 0 } }\n }\n const compiled = compile(source, options)\n // Surface any type-check warnings alongside the compile result.\n return { ...compiled, diagnostics: [...diagnostics, ...compiled.diagnostics] }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAS,YAAY,WAAwC;CAC3D,OAAO;EACL,KAAK,GAAG,QAAQ;EAChB,YAAY;EACZ,oBAAoB;EACpB,QAAQ,GAAG,aAAa;EACxB,QAAQ,GAAG,WAAW;EACtB;CACF;AACF;;;;;;;;;AAUA,SAAgB,QAAQ,QAAgB,UAA0B,CAAC,GAAkB;CACnF,MAAM,EAAE,WAAW,cAAc,YAAY,MAAM,UAAU,MAAM,UAAU,CAAC,MAAM;CAMpF,MAAM,QAAgD,CAAC;CACvD,IAAI,QAAsB;EAAE,gBAAgB;EAAG,eAAe;CAAE;CAEhE,IAAI,SAAS;EACX,MAAM,YAAY,yBAAyB,EAAE;EAC7C,MAAM,KAAK,UAAU,OAAO;EAC5B,QAAQ,UAAU;CACpB;CAEA,KAAK,MAAM,UAAU,SACnB,MAAM,KAAK,OAAO,YAAY,EAAE,CAAyC;CAG3E,MAAM,SAAS,GAAG,gBAAgB,QAAQ;EACxC,iBAAiB,YAAY,SAAS;EACtC;EACA,mBAAmB;EACnB,cAAc,EAAE,MAAM;CACxB,CAAC;CAID,MAAM,eAAe,OAAO,eAAe,CAAC,GAAG,KAAK,MAAM;EACxD,MAAM,UAAU,GAAG,6BAA6B,EAAE,aAAa,IAAI;EACnE,OAAO;GACL,UACE,EAAE,aAAa,GAAG,mBAAmB,QAAS,UAAqB;GACrE,MAAM,KAAK,EAAE;GACb;EACF;CACF,CAAC;CAED,MAAM,SAAwB;EAC5B,MAAM,OAAO;EACb;EACA;CACF;CACA,IAAI,aAAa,OAAO,eAAe,OAAO,MAAM,OAAO;CAC3D,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,QAAgB,UAA0B,CAAC,GAAkB;CAE1F,MAAM,cAAc,UAAU,QADb,QAAQ,YAAY,YACS;CAC9C,IAAI,UAAU,WAAW,GACvB,OAAO;EAAE,MAAM;EAAI;EAAa,OAAO;GAAE,gBAAgB;GAAG,eAAe;EAAE;CAAE;CAEjF,MAAM,WAAW,QAAQ,QAAQ,OAAO;CAExC,OAAO;EAAE,GAAG;EAAU,aAAa,CAAC,GAAG,aAAa,GAAG,SAAS,WAAW;CAAE;AAC/E"}
1
+ {"version":3,"file":"transform.js","names":[],"sources":["../src/transform.ts"],"sourcesContent":["/**\n * The MDC transform/compile pipeline.\n *\n * `compile()` lowers TSX → `createElement(...)` (matching `@mindees/core`'s\n * factory), runs the built-in optimizer passes (tree-flattening) plus any user\n * plugins, and emits JavaScript + a source map. It does **not** type-check\n * (that's {@link typecheck}); `compileChecked()` runs the gate first and refuses\n * to emit on `error` diagnostics.\n *\n * @module\n */\n\nimport ts from 'typescript'\nimport { createFlattenTransformer } from './flatten'\nimport { hasErrors, typecheck } from './typecheck'\nimport type { CompileOptions, CompileResult, CompileStats } from './types'\n\n/** Compiler options for emit (JSX → `createElement`/`Fragment`, which the optimizer matches). */\nfunction emitOptions(sourceMap: boolean): ts.CompilerOptions {\n return {\n jsx: ts.JsxEmit.React,\n jsxFactory: 'createElement',\n jsxFragmentFactory: 'Fragment',\n target: ts.ScriptTarget.ES2023,\n module: ts.ModuleKind.ESNext,\n sourceMap,\n }\n}\n\n/** Runtime names the JSX desugar references; injected from `@mindees/core` if unbound. */\nconst RUNTIME_NAMES = ['createElement', 'Fragment'] as const\n\n/**\n * Ensure the JSX runtime is in scope. Idiomatic components use **automatic JSX** and import\n * nothing, but we emit classic `createElement(...)`/`Fragment` (so the tree-flatten optimizer\n * can match them) — which would be unbound at runtime. This transformer prepends\n * `import { createElement, Fragment } from '@mindees/core'` for any runtime name that is\n * referenced but not already imported, so emitted modules run. Runs LAST (after flatten/plugins),\n * so names the optimizer removed don't get a needless import.\n */\nfunction createRuntimeImportTransformer(tsmod: typeof ts): ts.TransformerFactory<ts.SourceFile> {\n return (context) => (sourceFile) => {\n const imported = new Set<string>()\n for (const stmt of sourceFile.statements) {\n if (\n tsmod.isImportDeclaration(stmt) &&\n tsmod.isStringLiteral(stmt.moduleSpecifier) &&\n stmt.moduleSpecifier.text === '@mindees/core'\n ) {\n const named = stmt.importClause?.namedBindings\n if (named && tsmod.isNamedImports(named)) {\n for (const el of named.elements) imported.add((el.propertyName ?? el.name).text)\n }\n }\n }\n const referenced = new Set<string>()\n const visit = (node: ts.Node): void => {\n if (tsmod.isIdentifier(node) && (RUNTIME_NAMES as readonly string[]).includes(node.text)) {\n referenced.add(node.text)\n }\n tsmod.forEachChild(node, visit)\n }\n visit(sourceFile)\n const missing = RUNTIME_NAMES.filter((n) => referenced.has(n) && !imported.has(n))\n if (missing.length === 0) return sourceFile\n const importDecl = tsmod.factory.createImportDeclaration(\n undefined,\n tsmod.factory.createImportClause(\n false,\n undefined,\n tsmod.factory.createNamedImports(\n missing.map((n) =>\n tsmod.factory.createImportSpecifier(\n false,\n undefined,\n tsmod.factory.createIdentifier(n),\n ),\n ),\n ),\n ),\n tsmod.factory.createStringLiteral('@mindees/core'),\n )\n return context.factory.updateSourceFile(sourceFile, [importDecl, ...sourceFile.statements])\n }\n}\n\n/**\n * Compile a single TSX/TS module to JavaScript.\n *\n * Pipeline: JSX desugar → tree-flatten (optional) → user plugins → emit.\n * Returns emitted code, an optional source map, any (transpile-level)\n * diagnostics, and optimizer stats. Use {@link compileChecked} to gate on the\n * full type checker.\n */\nexport function compile(source: string, options: CompileOptions = {}): CompileResult {\n const { fileName = 'module.tsx', sourceMap = true, flatten = true, plugins = [] } = options\n\n // IMPORTANT: our optimizer + plugins operate on the desugared\n // `createElement(...)` call form, but `transpileModule` runs `before`\n // transformers on the *pre-desugar* JSX AST. JSX is lowered during the\n // `after` phase, so flatten/plugins must run there to see the calls.\n const after: ts.TransformerFactory<ts.SourceFile>[] = []\n let stats: CompileStats = { flattenedNodes: 0, totalElements: 0 }\n\n if (flatten) {\n const flattener = createFlattenTransformer(ts)\n after.push(flattener.factory)\n stats = flattener.stats // live object, updated during emit\n }\n\n for (const plugin of plugins) {\n after.push(plugin.transformer(ts) as ts.TransformerFactory<ts.SourceFile>)\n }\n\n // LAST: bind the JSX runtime (automatic-JSX components import nothing) so output runs.\n after.push(createRuntimeImportTransformer(ts))\n\n const output = ts.transpileModule(source, {\n compilerOptions: emitOptions(sourceMap),\n fileName,\n reportDiagnostics: true,\n transformers: { after },\n })\n\n // transpileModule only surfaces a few syntactic diagnostics; semantic ones\n // come from the type-check gate. Map each to our structured form.\n const diagnostics = (output.diagnostics ?? []).map((d) => {\n const message = ts.flattenDiagnosticMessageText(d.messageText, '\\n')\n return {\n severity:\n d.category === ts.DiagnosticCategory.Error ? ('error' as const) : ('warning' as const),\n code: `TS${d.code}`,\n message,\n }\n })\n\n const result: CompileResult = {\n code: output.outputText,\n diagnostics,\n stats,\n }\n if (sourceMap && output.sourceMapText) result.map = output.sourceMapText\n return result\n}\n\n/**\n * Type-check then compile. If the gate finds any `error` diagnostic, returns it\n * WITHOUT emitting code (`code: ''`) — the build must not ship type errors.\n */\nexport function compileChecked(source: string, options: CompileOptions = {}): CompileResult {\n const fileName = options.fileName ?? 'module.tsx'\n const diagnostics = typecheck(source, fileName)\n if (hasErrors(diagnostics)) {\n return { code: '', diagnostics, stats: { flattenedNodes: 0, totalElements: 0 } }\n }\n const compiled = compile(source, options)\n // Surface any type-check warnings alongside the compile result.\n return { ...compiled, diagnostics: [...diagnostics, ...compiled.diagnostics] }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,S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{"version":3,"file":"typecheck.d.ts","names":[],"sources":["../src/typecheck.ts"],"mappings":";;;;;;AAiK4D;;;;iBAvD5C,SAAA,CAAU,MAAA,UAAgB,QAAA,YAA0B,UAAU;;iBAuD9D,SAAA,CAAU,WAAkC,WAAZ,UAAU"}
1
+ {"version":3,"file":"typecheck.d.ts","names":[],"sources":["../src/typecheck.ts"],"mappings":";;;;;;AA6L4D;;;;iBAvD5C,SAAA,CAAU,MAAA,UAAgB,QAAA,YAA0B,UAAU;;iBAuD9D,SAAA,CAAU,WAAkC,WAAZ,UAAU"}
package/dist/typecheck.js CHANGED
@@ -12,11 +12,37 @@ import ts from "typescript";
12
12
  *
13
13
  * @module
14
14
  */
15
- /** Synthetic ambient module that gives the single-module gate a JSX environment. */
15
+ /**
16
+ * Synthetic ambient JSX environment for the single-module gate. The framework ships
17
+ * **automatic JSX** (`jsxImportSource: '@mindees/core'`), so the gate must type-check
18
+ * idiomatic components that import NOTHING — JSX resolves through the runtime module's
19
+ * `JSX` namespace. We declare that runtime module ambiently (production + dev) so the gate
20
+ * finds it under `noResolve`, and keep a global `JSX` namespace as a backstop.
21
+ */
16
22
  const JSX_LIB_FILE = "__mindees_jsx__.d.ts";
17
23
  const JSX_LIB_SOURCE = `declare namespace JSX {
18
24
  interface IntrinsicElements { [name: string]: Record<string, unknown> }
19
25
  type Element = unknown
26
+ interface ElementChildrenAttribute { children: object }
27
+ }
28
+ declare module '@mindees/core/jsx-runtime' {
29
+ export namespace JSX {
30
+ interface IntrinsicElements { [name: string]: Record<string, unknown> }
31
+ type Element = unknown
32
+ interface ElementChildrenAttribute { children: object }
33
+ }
34
+ export const jsx: (...args: unknown[]) => unknown
35
+ export const jsxs: (...args: unknown[]) => unknown
36
+ export const Fragment: unknown
37
+ }
38
+ declare module '@mindees/core/jsx-dev-runtime' {
39
+ export namespace JSX {
40
+ interface IntrinsicElements { [name: string]: Record<string, unknown> }
41
+ type Element = unknown
42
+ interface ElementChildrenAttribute { children: object }
43
+ }
44
+ export const jsxDEV: (...args: unknown[]) => unknown
45
+ export const Fragment: unknown
20
46
  }
21
47
  `;
22
48
  /**
@@ -36,9 +62,8 @@ function defaultOptions() {
36
62
  target: ts.ScriptTarget.ES2023,
37
63
  module: ts.ModuleKind.ESNext,
38
64
  moduleResolution: ts.ModuleResolutionKind.Bundler,
39
- jsx: ts.JsxEmit.React,
40
- jsxFactory: "createElement",
41
- jsxFragmentFactory: "Fragment",
65
+ jsx: ts.JsxEmit.ReactJSX,
66
+ jsxImportSource: "@mindees/core",
42
67
  noEmit: true,
43
68
  skipLibCheck: true,
44
69
  noResolve: true,
@@ -1 +1 @@
1
- {"version":3,"file":"typecheck.js","names":[],"sources":["../src/typecheck.ts"],"sourcesContent":["/**\n * The MDC type-check gate.\n *\n * Runs the TypeScript checker over a single in-memory module and reports\n * structured {@link Diagnostic}s. This is the compiler's correctness gate: a\n * build with any `error`-severity diagnostic must not ship.\n *\n * It uses an in-memory `CompilerHost` so no files touch disk; lib `.d.ts` files\n * are read from the real `typescript` install so global types resolve.\n *\n * @module\n */\n\nimport ts from 'typescript'\nimport type { Diagnostic } from './types'\n\n/** Synthetic ambient module that gives the single-module gate a JSX environment. */\nconst JSX_LIB_FILE = '__mindees_jsx__.d.ts'\nconst JSX_LIB_SOURCE = `declare namespace JSX {\n interface IntrinsicElements { [name: string]: Record<string, unknown> }\n type Element = unknown\n}\n`\n\n/**\n * Module-resolution diagnostic codes the single-module gate cannot meaningfully\n * judge (it type-checks ONE module with `noResolve`, so every import is\n * \"unresolved\"). Cross-module resolution is the project-graph type-check's job.\n * - TS2307: Cannot find module '…'.\n * - TS2792: Cannot find module … (did you mean to set 'moduleResolution'?).\n */\nconst UNRESOLVED_IMPORT_CODES = new Set([2307, 2792])\n\n/** Default compiler options for the gate: strict, modern, JSX-aware. */\nfunction defaultOptions(): ts.CompilerOptions {\n return {\n strict: true,\n noUncheckedIndexedAccess: true,\n exactOptionalPropertyTypes: true,\n target: ts.ScriptTarget.ES2023,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n jsx: ts.JsxEmit.React,\n jsxFactory: 'createElement',\n jsxFragmentFactory: 'Fragment',\n noEmit: true,\n skipLibCheck: true,\n // Type-check a single module in isolation; imports are not resolved here\n // (unresolved-import diagnostics are filtered — see UNRESOLVED_IMPORT_CODES).\n noResolve: true,\n types: [],\n }\n}\n\nfunction toSeverity(category: ts.DiagnosticCategory): 'error' | 'warning' | null {\n if (category === ts.DiagnosticCategory.Error) return 'error'\n if (category === ts.DiagnosticCategory.Warning) return 'warning'\n return null\n}\n\n/**\n * Map a file extension to its `ScriptKind`. `ts.createSourceFile` does NOT infer\n * this — omitting it would mis-parse files — so we map it explicitly (not via\n * any TypeScript-internal helper). A `.ts` file thus rejects JSX, while `.tsx`\n * accepts it.\n */\nfunction scriptKindForFile(fileName: string): ts.ScriptKind {\n const lower = fileName.toLowerCase()\n if (lower.endsWith('.tsx')) return ts.ScriptKind.TSX\n if (lower.endsWith('.jsx')) return ts.ScriptKind.JSX\n if (lower.endsWith('.js') || lower.endsWith('.mjs') || lower.endsWith('.cjs')) {\n return ts.ScriptKind.JS\n }\n if (lower.endsWith('.json')) return ts.ScriptKind.JSON\n return ts.ScriptKind.TS\n}\n\n/** Convert a TypeScript diagnostic to our structured form. */\nfunction convert(diag: ts.Diagnostic): Diagnostic | null {\n // The single-module gate doesn't resolve imports; drop unresolved-import noise.\n if (UNRESOLVED_IMPORT_CODES.has(diag.code)) return null\n const severity = toSeverity(diag.category)\n if (!severity) return null\n const message = ts.flattenDiagnosticMessageText(diag.messageText, '\\n')\n const out: Diagnostic = {\n severity,\n code: `TS${diag.code}`,\n message,\n }\n if (diag.file) {\n out.file = diag.file.fileName\n if (diag.start !== undefined) {\n const { line, character } = diag.file.getLineAndCharacterOfPosition(diag.start)\n out.position = { line: line + 1, column: character + 1 }\n }\n }\n return out\n}\n\n/**\n * Type-check a single module's source and return its diagnostics.\n *\n * @param source - The module source (`.tsx` is assumed unless `fileName` says otherwise).\n * @param fileName - Logical file name. Default `\"module.tsx\"`.\n * @returns All `error`/`warning` diagnostics (semantic + syntactic). Empty = clean.\n */\nexport function typecheck(source: string, fileName = 'module.tsx'): Diagnostic[] {\n const options = defaultOptions()\n const sourceFile = ts.createSourceFile(\n fileName,\n source,\n ts.ScriptTarget.ES2023,\n true,\n scriptKindForFile(fileName),\n )\n // A synthetic ambient JSX lib so intrinsic elements (`<view>`, `<text>`, …)\n // type-check without each module declaring JSX.IntrinsicElements.\n const jsxLib = ts.createSourceFile(\n JSX_LIB_FILE,\n JSX_LIB_SOURCE,\n ts.ScriptTarget.ES2023,\n true,\n ts.ScriptKind.TS,\n )\n\n const defaultHost = ts.createCompilerHost(options)\n const host: ts.CompilerHost = {\n ...defaultHost,\n getSourceFile: (name, languageVersion, onError, shouldCreate) => {\n if (name === fileName) return sourceFile\n if (name === JSX_LIB_FILE) return jsxLib\n return defaultHost.getSourceFile(name, languageVersion, onError, shouldCreate)\n },\n writeFile: () => {\n /* noEmit */\n },\n fileExists: (name) =>\n name === fileName || name === JSX_LIB_FILE || defaultHost.fileExists(name),\n readFile: (name) =>\n name === fileName\n ? source\n : name === JSX_LIB_FILE\n ? JSX_LIB_SOURCE\n : defaultHost.readFile(name),\n }\n\n const program = ts.createProgram([JSX_LIB_FILE, fileName], options, host)\n const diagnostics = [\n ...program.getSyntacticDiagnostics(sourceFile),\n ...program.getSemanticDiagnostics(sourceFile),\n ]\n\n const out: Diagnostic[] = []\n for (const d of diagnostics) {\n const converted = convert(d)\n if (converted) out.push(converted)\n }\n return out\n}\n\n/** True if any diagnostic is an `error` (i.e. the build must fail). */\nexport function hasErrors(diagnostics: readonly Diagnostic[]): boolean {\n return diagnostics.some((d) => d.severity === 'error')\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAM,eAAe;AACrB,MAAM,iBAAiB;;;;;;;;;;;;AAavB,MAAM,0BAA0B,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC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AY;GAAE;EACzD;CACF;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,UAAU,QAAgB,WAAW,cAA4B;CAC/E,MAAM,UAAU,eAAe;CAC/B,MAAM,aAAa,GAAG,iBACpB,UACA,QACA,GAAG,aAAa,QAChB,MACA,kBAAkB,QAAQ,CAC5B;CAGA,MAAM,SAAS,GAAG,iBAChB,cACA,gBACA,GAAG,aAAa,QAChB,MACA,GAAG,WAAW,EAChB;CAEA,MAAM,cAAc,GAAG,mBAAmB,OAAO;CACjD,MAAM,OAAwB;EAC5B,GAAG;EACH,gBAAgB,MAAM,iBAAiB,SAAS,iBAAiB;GAC/D,IAAI,SAAS,UAAU,OAAO;GAC9B,IAAI,SAAS,cAAc,OAAO;GAClC,OAAO,YAAY,cAAc,MAAM,iBAAiB,SAAS,YAAY;EAC/E;EACA,iBAAiB,CAEjB;EACA,aAAa,SACX,SAAS,YAAY,SAAS,gBAAgB,YAAY,WAAW,IAAI;EAC3E,WAAW,SACT,SAAS,WACL,SACA,SAAS,eACP,iBACA,YAAY,SAAS,IAAI;CACnC;CAEA,MAAM,UAAU,GAAG,cAAc,CAAC,cAAc,QAAQ,GAAG,SAAS,IAAI;CACxE,MAAM,cAAc,CAClB,GAAG,QAAQ,wBAAwB,UAAU,GAC7C,GAAG,QAAQ,uBAAuB,UAAU,CAC9C;CAEA,MAAM,MAAoB,CAAC;CAC3B,KAAK,MAAM,KAAK,aAAa;EAC3B,MAAM,YAAY,QAAQ,CAAC;EAC3B,IAAI,WAAW,IAAI,KAAK,SAAS;CACnC;CACA,OAAO;AACT;;AAGA,SAAgB,UAAU,aAA6C;CACrE,OAAO,YAAY,MAAM,MAAM,EAAE,aAAa,OAAO;AACvD"}
1
+ {"version":3,"file":"typecheck.js","names":[],"sources":["../src/typecheck.ts"],"sourcesContent":["/**\n * The MDC type-check gate.\n *\n * Runs the TypeScript checker over a single in-memory module and reports\n * structured {@link Diagnostic}s. This is the compiler's correctness gate: a\n * build with any `error`-severity diagnostic must not ship.\n *\n * It uses an in-memory `CompilerHost` so no files touch disk; lib `.d.ts` files\n * are read from the real `typescript` install so global types resolve.\n *\n * @module\n */\n\nimport ts from 'typescript'\nimport type { Diagnostic } from './types'\n\n/**\n * Synthetic ambient JSX environment for the single-module gate. The framework ships\n * **automatic JSX** (`jsxImportSource: '@mindees/core'`), so the gate must type-check\n * idiomatic components that import NOTHING — JSX resolves through the runtime module's\n * `JSX` namespace. We declare that runtime module ambiently (production + dev) so the gate\n * finds it under `noResolve`, and keep a global `JSX` namespace as a backstop.\n */\nconst JSX_LIB_FILE = '__mindees_jsx__.d.ts'\nconst JSX_LIB_SOURCE = `declare namespace JSX {\n interface IntrinsicElements { [name: string]: Record<string, unknown> }\n type Element = unknown\n interface ElementChildrenAttribute { children: object }\n}\ndeclare module '@mindees/core/jsx-runtime' {\n export namespace JSX {\n interface IntrinsicElements { [name: string]: Record<string, unknown> }\n type Element = unknown\n interface ElementChildrenAttribute { children: object }\n }\n export const jsx: (...args: unknown[]) => unknown\n export const jsxs: (...args: unknown[]) => unknown\n export const Fragment: unknown\n}\ndeclare module '@mindees/core/jsx-dev-runtime' {\n export namespace JSX {\n interface IntrinsicElements { [name: string]: Record<string, unknown> }\n type Element = unknown\n interface ElementChildrenAttribute { children: object }\n }\n export const jsxDEV: (...args: unknown[]) => unknown\n export const Fragment: unknown\n}\n`\n\n/**\n * Module-resolution diagnostic codes the single-module gate cannot meaningfully\n * judge (it type-checks ONE module with `noResolve`, so every import is\n * \"unresolved\"). Cross-module resolution is the project-graph type-check's job.\n * - TS2307: Cannot find module '…'.\n * - TS2792: Cannot find module … (did you mean to set 'moduleResolution'?).\n */\nconst UNRESOLVED_IMPORT_CODES = new Set([2307, 2792])\n\n/** Default compiler options for the gate: strict, modern, JSX-aware. */\nfunction defaultOptions(): ts.CompilerOptions {\n return {\n strict: true,\n noUncheckedIndexedAccess: true,\n exactOptionalPropertyTypes: true,\n target: ts.ScriptTarget.ES2023,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n // Automatic JSX — the framework's shipped runtime. Idiomatic components import\n // nothing; JSX resolves through `@mindees/core/jsx-runtime`'s `JSX` namespace\n // (declared ambiently in JSX_LIB_SOURCE so the gate finds it under noResolve).\n jsx: ts.JsxEmit.ReactJSX,\n jsxImportSource: '@mindees/core',\n noEmit: true,\n skipLibCheck: true,\n // Type-check a single module in isolation; imports are not resolved here\n // (unresolved-import diagnostics are filtered — see UNRESOLVED_IMPORT_CODES).\n noResolve: true,\n types: [],\n }\n}\n\nfunction toSeverity(category: ts.DiagnosticCategory): 'error' | 'warning' | null {\n if (category === ts.DiagnosticCategory.Error) return 'error'\n if (category === ts.DiagnosticCategory.Warning) return 'warning'\n return null\n}\n\n/**\n * Map a file extension to its `ScriptKind`. `ts.createSourceFile` does NOT infer\n * this — omitting it would mis-parse files — so we map it explicitly (not via\n * any TypeScript-internal helper). A `.ts` file thus rejects JSX, while `.tsx`\n * accepts it.\n */\nfunction scriptKindForFile(fileName: string): ts.ScriptKind {\n const lower = fileName.toLowerCase()\n if (lower.endsWith('.tsx')) return ts.ScriptKind.TSX\n if (lower.endsWith('.jsx')) return ts.ScriptKind.JSX\n if (lower.endsWith('.js') || lower.endsWith('.mjs') || lower.endsWith('.cjs')) {\n return ts.ScriptKind.JS\n }\n if (lower.endsWith('.json')) return ts.ScriptKind.JSON\n return ts.ScriptKind.TS\n}\n\n/** Convert a TypeScript diagnostic to our structured form. */\nfunction convert(diag: ts.Diagnostic): Diagnostic | null {\n // The single-module gate doesn't resolve imports; drop unresolved-import noise.\n if (UNRESOLVED_IMPORT_CODES.has(diag.code)) return null\n const severity = toSeverity(diag.category)\n if (!severity) return null\n const message = ts.flattenDiagnosticMessageText(diag.messageText, '\\n')\n const out: Diagnostic = {\n severity,\n code: `TS${diag.code}`,\n message,\n }\n if (diag.file) {\n out.file = diag.file.fileName\n if (diag.start !== undefined) {\n const { line, character } = diag.file.getLineAndCharacterOfPosition(diag.start)\n out.position = { line: line + 1, column: character + 1 }\n }\n }\n return out\n}\n\n/**\n * Type-check a single module's source and return its diagnostics.\n *\n * @param source - The module source (`.tsx` is assumed unless `fileName` says otherwise).\n * @param fileName - Logical file name. Default `\"module.tsx\"`.\n * @returns All `error`/`warning` diagnostics (semantic + syntactic). Empty = clean.\n */\nexport function typecheck(source: string, fileName = 'module.tsx'): Diagnostic[] {\n const options = defaultOptions()\n const sourceFile = ts.createSourceFile(\n fileName,\n source,\n ts.ScriptTarget.ES2023,\n true,\n scriptKindForFile(fileName),\n )\n // A synthetic ambient JSX lib so intrinsic elements (`<view>`, `<text>`, …)\n // type-check without each module declaring JSX.IntrinsicElements.\n const jsxLib = ts.createSourceFile(\n JSX_LIB_FILE,\n JSX_LIB_SOURCE,\n ts.ScriptTarget.ES2023,\n true,\n ts.ScriptKind.TS,\n )\n\n const defaultHost = ts.createCompilerHost(options)\n const host: ts.CompilerHost = {\n ...defaultHost,\n getSourceFile: (name, languageVersion, onError, shouldCreate) => {\n if (name === fileName) return sourceFile\n if (name === JSX_LIB_FILE) return jsxLib\n return defaultHost.getSourceFile(name, languageVersion, onError, shouldCreate)\n },\n writeFile: () => {\n /* noEmit */\n },\n fileExists: (name) =>\n name === fileName || name === JSX_LIB_FILE || defaultHost.fileExists(name),\n readFile: (name) =>\n name === fileName\n ? source\n : name === JSX_LIB_FILE\n ? JSX_LIB_SOURCE\n : defaultHost.readFile(name),\n }\n\n const program = ts.createProgram([JSX_LIB_FILE, fileName], options, host)\n const diagnostics = [\n ...program.getSyntacticDiagnostics(sourceFile),\n ...program.getSemanticDiagnostics(sourceFile),\n ]\n\n const out: Diagnostic[] = []\n for (const d of diagnostics) {\n const converted = convert(d)\n if (converted) out.push(converted)\n }\n return out\n}\n\n/** True if any diagnostic is an `error` (i.e. the build must fail). */\nexport function hasErrors(diagnostics: readonly Diagnostic[]): boolean {\n return diagnostics.some((d) => d.severity === 'error')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAu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@mindees/compiler",
3
- "version": "0.1.0",
3
+ "version": "0.3.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.1.0"
27
+ "@mindees/core": "0.3.0"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "tsdown",