@spfn/core 0.3.0-beta.10 → 0.3.0-beta.12

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.
@@ -1,9 +1,10 @@
1
1
  import { watch } from 'chokidar';
2
- import { join, relative, sep, dirname, resolve } from 'path';
2
+ import { join, relative, sep, dirname, resolve, isAbsolute } from 'path';
3
3
  import mm from 'micromatch';
4
4
  import { logger } from '@spfn/core/logger';
5
- import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
5
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, statSync, readdirSync } from 'fs';
6
6
  import { createJiti } from 'jiti';
7
+ import { createRequire } from 'module';
7
8
  import { collectContractDocument, writeCurrentDocument, checkContract, formatViolations } from '@spfn/core/contract';
8
9
 
9
10
  // src/codegen/core/orchestrator.ts
@@ -334,70 +335,443 @@ async function createGeneratorsFromConfig(config, cwd) {
334
335
  }
335
336
  return generators2;
336
337
  }
337
- var genLogger = logger.child("@spfn/core:route-map-generator");
338
- function parseRouteFile(filePath) {
339
- const routes = [];
340
- try {
341
- const content = readFileSync(filePath, "utf-8");
342
- const routePattern = /export\s+const\s+(\w+)\s*=\s*route\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/gi;
343
- let match;
344
- while ((match = routePattern.exec(content)) !== null) {
345
- const [, name, method, path] = match;
346
- routes.push({
347
- name,
348
- method: method.toUpperCase(),
349
- path,
350
- file: filePath
351
- });
338
+ var compiler;
339
+ function typescript() {
340
+ compiler ??= createRequire(import.meta.url)("typescript");
341
+ return compiler;
342
+ }
343
+
344
+ // src/codegen/generators/contract-guard.ts
345
+ var ConditionalRegistrationError = class extends Error {
346
+ constructor(message) {
347
+ super(message);
348
+ this.name = "ConditionalRegistrationError";
349
+ }
350
+ };
351
+ function assertUnconditionalRegistration(scan) {
352
+ const compiler2 = typescript();
353
+ const file = compiler2.createSourceFile(
354
+ scan.routerPath,
355
+ scan.source,
356
+ compiler2.ScriptTarget.Latest,
357
+ /* setParentNodes */
358
+ false
359
+ );
360
+ const declarations = topLevelInitialisers(compiler2, file);
361
+ const routes = routesLiteral(compiler2, declarations.get(scan.exportName), declarations, /* @__PURE__ */ new Set());
362
+ if (routes) {
363
+ assertLiteral(compiler2, file, routes, declarations, /* @__PURE__ */ new Set(), scan);
364
+ }
365
+ }
366
+ function topLevelInitialisers(compiler2, file) {
367
+ const found = /* @__PURE__ */ new Map();
368
+ for (const statement of file.statements) {
369
+ if (compiler2.isExportAssignment(statement) && !statement.isExportEquals) {
370
+ found.set("default", statement.expression);
371
+ }
372
+ if (compiler2.isVariableStatement(statement)) {
373
+ collectDeclarations(compiler2, statement, found);
352
374
  }
353
- } catch (error) {
354
- genLogger.warn(`Failed to parse route file: ${filePath}`, error);
355
375
  }
356
- return routes;
376
+ for (const statement of file.statements) {
377
+ collectRenamedExports(compiler2, statement, found);
378
+ }
379
+ return found;
357
380
  }
358
- function parseRouterFile(routerPath) {
359
- const importPaths = [];
360
- const routeNames = [];
361
- try {
362
- const content = readFileSync(routerPath, "utf-8");
363
- const importPattern = /import\s+\{[^}]+\}\s+from\s+['"`](\.[^'"`]+)['"`]/g;
364
- let match;
365
- while ((match = importPattern.exec(content)) !== null) {
366
- const importPath = match[1];
367
- if (importPath.startsWith(".")) {
368
- importPaths.push(importPath);
369
- }
381
+ function collectDeclarations(compiler2, statement, found) {
382
+ for (const declaration of statement.declarationList.declarations) {
383
+ if (compiler2.isIdentifier(declaration.name) && declaration.initializer) {
384
+ found.set(declaration.name.text, declaration.initializer);
370
385
  }
371
- const defineRouterStart = content.indexOf("defineRouter(");
372
- if (defineRouterStart !== -1) {
373
- const braceStart = content.indexOf("{", defineRouterStart);
374
- if (braceStart !== -1) {
375
- let depth = 1;
376
- let braceEnd = braceStart + 1;
377
- while (depth > 0 && braceEnd < content.length) {
378
- if (content[braceEnd] === "{") depth++;
379
- else if (content[braceEnd] === "}") depth--;
380
- braceEnd++;
381
- }
382
- const routerContent = content.slice(braceStart + 1, braceEnd - 1);
383
- const withoutComments = routerContent.replace(/\/\/[^\n]*/g, "");
384
- const namePattern = /^\s*(\w+)\s*[,\n]/gm;
385
- while ((match = namePattern.exec(withoutComments)) !== null) {
386
- routeNames.push(match[1]);
387
- }
388
- }
386
+ }
387
+ }
388
+ function collectRenamedExports(compiler2, statement, found) {
389
+ if (!compiler2.isExportDeclaration(statement) || !statement.exportClause || !compiler2.isNamedExports(statement.exportClause)) {
390
+ return;
391
+ }
392
+ for (const specifier of statement.exportClause.elements) {
393
+ if (specifier.propertyName && !found.has(specifier.name.text)) {
394
+ found.set(specifier.name.text, specifier.propertyName);
395
+ }
396
+ }
397
+ }
398
+ function unwrap(compiler2, expression) {
399
+ if (!expression) {
400
+ return void 0;
401
+ }
402
+ if (compiler2.isParenthesizedExpression(expression) || compiler2.isAsExpression(expression) || compiler2.isSatisfiesExpression(expression) || compiler2.isNonNullExpression(expression) || compiler2.isTypeAssertionExpression(expression)) {
403
+ return unwrap(compiler2, expression.expression);
404
+ }
405
+ return expression;
406
+ }
407
+ function routesLiteral(compiler2, expression, declarations, seen) {
408
+ const node = unwrap(compiler2, expression);
409
+ if (!node) {
410
+ return void 0;
411
+ }
412
+ if (compiler2.isIdentifier(node)) {
413
+ if (seen.has(node.text)) {
414
+ return void 0;
415
+ }
416
+ seen.add(node.text);
417
+ return routesLiteral(compiler2, declarations.get(node.text), declarations, seen);
418
+ }
419
+ if (!compiler2.isCallExpression(node)) {
420
+ return void 0;
421
+ }
422
+ const callee = unwrap(compiler2, node.expression);
423
+ if (callee && compiler2.isIdentifier(callee) && callee.text === "defineRouter") {
424
+ const routes = unwrap(compiler2, node.arguments[0]);
425
+ return routes && compiler2.isObjectLiteralExpression(routes) ? routes : void 0;
426
+ }
427
+ return callee && compiler2.isPropertyAccessExpression(callee) ? routesLiteral(compiler2, callee.expression, declarations, seen) : void 0;
428
+ }
429
+ function assertLiteral(compiler2, file, literal, declarations, seen, scan) {
430
+ for (const property of literal.properties) {
431
+ if (compiler2.isSpreadAssignment(property)) {
432
+ assertUnconditionalSpread(compiler2, file, property.expression, scan);
433
+ continue;
434
+ }
435
+ const nested = routesLiteral(compiler2, mountedRouter(compiler2, property), declarations, seen);
436
+ if (nested) {
437
+ assertLiteral(compiler2, file, nested, declarations, seen, scan);
438
+ }
439
+ }
440
+ }
441
+ function mountedRouter(compiler2, property) {
442
+ if (compiler2.isPropertyAssignment(property)) {
443
+ return property.initializer;
444
+ }
445
+ return compiler2.isShorthandPropertyAssignment(property) ? property.name : void 0;
446
+ }
447
+ function assertUnconditionalSpread(compiler2, file, expression, scan) {
448
+ const condition = conditionKind(compiler2, expression);
449
+ if (!condition) {
450
+ return;
451
+ }
452
+ throw new ConditionalRegistrationError(
453
+ `${scan.routerPath} registers routes conditionally: "...${spreadText(file, expression)}" (${condition}).
454
+
455
+ The ${scan.subject} is generated from the router as it loads, so a route set that depends on a flag or an environment describes whichever way the generator happened to run: a route production registers is left out, and the client that addresses it by name gets a 404.
456
+ Register the route unconditionally and gate its behaviour inside the handler instead.`
457
+ );
458
+ }
459
+ function conditionKind(compiler2, expression) {
460
+ const node = unwrap(compiler2, expression);
461
+ if (!node) {
462
+ return void 0;
463
+ }
464
+ if (compiler2.isConditionalExpression(node)) {
465
+ return "a ternary";
466
+ }
467
+ if (!compiler2.isBinaryExpression(node)) {
468
+ return void 0;
469
+ }
470
+ switch (node.operatorToken.kind) {
471
+ case compiler2.SyntaxKind.AmpersandAmpersandToken:
472
+ return "&&";
473
+ case compiler2.SyntaxKind.BarBarToken:
474
+ return "||";
475
+ case compiler2.SyntaxKind.QuestionQuestionToken:
476
+ return "??";
477
+ default:
478
+ return void 0;
479
+ }
480
+ }
481
+ function spreadText(file, expression) {
482
+ return expression.getText(file).replace(/\s+/g, " ");
483
+ }
484
+ var loadLogger = logger.child("@spfn/core:codegen");
485
+ function pinNodeEnv() {
486
+ if (process.env.NODE_ENV) {
487
+ return;
488
+ }
489
+ process.env.NODE_ENV = "production";
490
+ loadLogger.info('NODE_ENV was unset; pinned to "production" so generated output does not depend on the shell');
491
+ }
492
+ function parseHost(compiler2) {
493
+ return {
494
+ useCaseSensitiveFileNames: compiler2.sys.useCaseSensitiveFileNames,
495
+ readDirectory: () => [],
496
+ fileExists: compiler2.sys.fileExists,
497
+ readFile: compiler2.sys.readFile
498
+ };
499
+ }
500
+ var NO_INPUTS = 18003;
501
+ function targetPath(target, base) {
502
+ return resolve(base, target.endsWith("/*") ? target.slice(0, -2) : target);
503
+ }
504
+ function targetResolves(target, base) {
505
+ const path = targetPath(target, base);
506
+ if (!target.endsWith("/*")) {
507
+ return existsSync(path);
508
+ }
509
+ const stats = statSync(path, { throwIfNoEntry: false });
510
+ return stats?.isDirectory() === true && readdirSync(path).length > 0;
511
+ }
512
+ function chooseTarget(pattern, targets, base) {
513
+ const present = targets.filter((target2) => targetResolves(target2, base));
514
+ const [target] = present.length > 0 ? present : targets;
515
+ if (!target) {
516
+ return void 0;
517
+ }
518
+ if (present.length > 1) {
519
+ loadLogger.warn(
520
+ `tsconfig "paths" maps ${pattern} to ${present.length} targets that could each resolve a module; while the router loads, only the first (${target}) does`
521
+ );
522
+ }
523
+ if (present.length === 0 && targets.length > 1) {
524
+ loadLogger.warn(
525
+ `tsconfig "paths" maps ${pattern} to ${targets.length} targets and none of them exists with anything in it; ${target} is used, and an import through it will name itself as unresolved`
526
+ );
527
+ }
528
+ return { target, others: targets.filter((candidate) => candidate !== target) };
529
+ }
530
+ function toAlias(pattern, targets, base) {
531
+ const choice = chooseTarget(pattern, targets, base);
532
+ if (!choice) {
533
+ return void 0;
534
+ }
535
+ const { target, others } = choice;
536
+ if (!pattern.includes("*")) {
537
+ return { from: pattern, to: resolve(base, target), pattern, target, others };
538
+ }
539
+ if (!pattern.endsWith("/*") || !target.endsWith("/*")) {
540
+ loadLogger.warn(
541
+ `tsconfig "paths" maps ${pattern} to ${target}, which is not a directory prefix mapping; it will not resolve while the router loads`
542
+ );
543
+ return void 0;
544
+ }
545
+ return { from: pattern.slice(0, -1), to: resolve(base, target.slice(0, -2)), pattern, target, others };
546
+ }
547
+ function readCompilerOptions(configPath, cwd) {
548
+ if (!existsSync(configPath)) {
549
+ return void 0;
550
+ }
551
+ const compiler2 = typescript();
552
+ const { config, error } = compiler2.readConfigFile(configPath, compiler2.sys.readFile);
553
+ if (error || !config) {
554
+ loadLogger.warn(`Could not read ${relative(cwd, configPath)}; its path aliases will not resolve`);
555
+ return void 0;
556
+ }
557
+ const parsed = compiler2.parseJsonConfigFileContent(config, parseHost(compiler2), dirname(configPath));
558
+ for (const diagnostic of parsed.errors) {
559
+ if (diagnostic.code !== NO_INPUTS) {
560
+ loadLogger.warn(
561
+ `${relative(cwd, configPath)}: ${compiler2.flattenDiagnosticMessageText(diagnostic.messageText, " ")} \u2014 path aliases it should have declared may be missing while the router loads`
562
+ );
389
563
  }
564
+ }
565
+ return parsed.options;
566
+ }
567
+ function isWithin(root, directory) {
568
+ const step = relative(root, directory);
569
+ return step === "" || !step.startsWith("..") && !isAbsolute(step);
570
+ }
571
+ function searchDirectories(cwd, startDir) {
572
+ const root = resolve(cwd);
573
+ const directories = [];
574
+ for (let directory = resolve(startDir); isWithin(root, directory); directory = dirname(directory)) {
575
+ directories.push(directory);
576
+ if (directory === root) {
577
+ return directories;
578
+ }
579
+ }
580
+ return [root];
581
+ }
582
+ function aliasesOf(paths, base) {
583
+ const aliases = /* @__PURE__ */ new Map();
584
+ for (const [pattern, targets] of Object.entries(paths)) {
585
+ const alias = toAlias(pattern, targets, base);
586
+ if (alias && !aliases.has(alias.from)) {
587
+ aliases.set(alias.from, alias);
588
+ }
589
+ }
590
+ return [...aliases.values()];
591
+ }
592
+ function projectAliases(cwd, startDir) {
593
+ for (const directory of searchDirectories(cwd, startDir)) {
594
+ const options = readCompilerOptions(join(directory, "tsconfig.json"), cwd);
595
+ if (options?.paths) {
596
+ const declaredIn = options.pathsBasePath;
597
+ return aliasesOf(options.paths, options.baseUrl ?? declaredIn ?? directory);
598
+ }
599
+ }
600
+ return [];
601
+ }
602
+ function describeFailure(error, subject, aliases) {
603
+ const message = error instanceof Error ? error.message : String(error);
604
+ const unresolved = /Cannot find module '([^']+)'/.exec(message);
605
+ if (!unresolved) {
606
+ return `${message}
607
+
608
+ The ${subject} is read from the loaded router, so a route module must be importable without side effects. Check that nothing at module scope opens a connection or reads a missing environment value.`;
609
+ }
610
+ return `${message.split("\n")[0]}
611
+
612
+ "${unresolved[1]}" did not resolve while the router was being imported. Imports resolve through Node and through the "paths" of the nearest tsconfig.json that declares them, searching from the router file up to the project root. Check that the specifier is mapped in one of those, and that what it points at exists: a workspace package resolves to a dist/ that has to have been built.` + describePassedOverTargets(unresolved[1], aliases);
613
+ }
614
+ function describePassedOverTargets(specifier, aliases) {
615
+ const alias = aliases.find((entry) => specifier.startsWith(entry.from) || specifier.startsWith(entry.to));
616
+ if (!alias || alias.others.length === 0) {
617
+ return "";
618
+ }
619
+ return `
620
+
621
+ It was resolved through "${alias.target}", the first target of the "paths" entry "${alias.pattern}" that names a directory holding anything. That entry also lists ${alias.others.map((other) => `"${other}"`).join(", ")}, which the router load never tried: one alias per key is all the loader can express, so the whole load goes through a single target.`;
622
+ }
623
+ function loadRouterModule(load) {
624
+ const { cwd, absoluteRouterPath, subject, fail } = load;
625
+ const aliases = projectAliases(cwd, dirname(absoluteRouterPath));
626
+ const jiti = createJiti(cwd, {
627
+ interopDefault: true,
628
+ moduleCache: false,
629
+ alias: Object.fromEntries(aliases.map((alias) => [alias.from, alias.to]))
630
+ });
631
+ try {
632
+ return jiti(absoluteRouterPath);
390
633
  } catch (error) {
391
- genLogger.warn(`Failed to parse router file: ${routerPath}`, error);
634
+ throw fail(
635
+ `Failed to load ${relative(cwd, absoluteRouterPath)}: ${describeFailure(error, subject, aliases)}`
636
+ );
637
+ }
638
+ }
639
+ function isRouter(value) {
640
+ return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
641
+ }
642
+ function resolveRouterExport(module, candidates) {
643
+ for (const exportName of candidates) {
644
+ const candidate = module[exportName];
645
+ if (isRouter(candidate)) {
646
+ return { router: candidate, exportName };
647
+ }
648
+ }
649
+ return void 0;
650
+ }
651
+
652
+ // src/codegen/generators/route-map.ts
653
+ var genLogger = logger.child("@spfn/core:route-map-generator");
654
+ var RouteMapGeneratorError = class extends Error {
655
+ constructor(message) {
656
+ super(message);
657
+ this.name = "RouteMapGeneratorError";
658
+ }
659
+ };
660
+ function isRouteDef(value) {
661
+ return value !== null && typeof value === "object" && "handler" in value;
662
+ }
663
+ var ROUTER_EXPORTS = ["appRouter", "default", "router"];
664
+ function loadRouter(cwd, absoluteRouterPath) {
665
+ const module = loadRouterModule({
666
+ cwd,
667
+ absoluteRouterPath,
668
+ subject: "route map",
669
+ fail: (message) => new RouteMapGeneratorError(message)
670
+ });
671
+ const resolved = resolveRouterExport(module, ROUTER_EXPORTS);
672
+ if (resolved) {
673
+ return resolved;
674
+ }
675
+ throw new RouteMapGeneratorError(
676
+ `No router found in ${relative(cwd, absoluteRouterPath)}. Looked for: ${ROUTER_EXPORTS.join(", ")}. Export the defineRouter() result under one of those names.`
677
+ );
678
+ }
679
+ var HTTP_METHODS = { GET: true, POST: true, PUT: true, PATCH: true, DELETE: true };
680
+ function addRoute(name, routeDef, trail, found) {
681
+ const where = trail.join(".");
682
+ if (!routeDef.method || !routeDef.path) {
683
+ genLogger.warn(
684
+ `Route "${where}" has no method or path and is left out of the map. The RPC client resolves a name to a method and a path, so both are required. A route reaches this state by being registered before .handler() was called \u2014 the server skips it too.`
685
+ );
686
+ return;
687
+ }
688
+ if (!Object.hasOwn(HTTP_METHODS, routeDef.method)) {
689
+ throw new RouteMapGeneratorError(
690
+ `Route "${where}" declares the method "${routeDef.method}", which is not an HttpMethod (${Object.keys(HTTP_METHODS).join(", ")}). The generated map is typed HttpMethod, so naming it would write a file that does not compile.`
691
+ );
692
+ }
693
+ const existing = found.get(name);
694
+ if (existing) {
695
+ throw new RouteMapGeneratorError(
696
+ `Two routes are both named "${name}" (${existing.trail} and ${where}). The RPC client addresses a route by its name alone, and a nested route registers under its own key, so a name must be unique across the whole router.`
697
+ );
698
+ }
699
+ found.set(name, { method: routeDef.method, path: routeDef.path, trail: where });
700
+ }
701
+ function collectPackageNames(router, trail, names) {
702
+ if (router._publishesRouteMap === false) {
703
+ return;
704
+ }
705
+ for (const [name, entry] of Object.entries(router.routes)) {
706
+ if (isRouter(entry)) {
707
+ collectPackageNames(entry, [...trail, name], names);
708
+ } else if (isRouteDef(entry) && !names.has(name)) {
709
+ names.set(name, [...trail, name].join("."));
710
+ }
711
+ }
712
+ for (const [index, packageRouter] of (router._packageRouters ?? []).entries()) {
713
+ collectPackageNames(packageRouter, [...trail, `packages[${index}]`], names);
714
+ }
715
+ }
716
+ function collectRoutes(router, trail, found, packageNames) {
717
+ for (const [name, entry] of Object.entries(router.routes)) {
718
+ if (isRouter(entry)) {
719
+ collectRoutes(entry, [...trail, name], found, packageNames);
720
+ continue;
721
+ }
722
+ if (!isRouteDef(entry)) {
723
+ genLogger.warn(
724
+ `Router entry "${[...trail, name].join(".")}" is neither a route nor a router (got ${typeof entry}) and is left out of the map. \`registerRoutes\` skips it too, so no name the client can call goes unanswered.`
725
+ );
726
+ continue;
727
+ }
728
+ addRoute(name, entry, [...trail, name], found);
729
+ }
730
+ for (const [index, packageRouter] of (router._packageRouters ?? []).entries()) {
731
+ collectPackageNames(packageRouter, [...trail, `packages[${index}]`], packageNames);
732
+ }
733
+ }
734
+ function assertNoPackageCollision(found, packageNames) {
735
+ for (const [name, where] of packageNames) {
736
+ const route = found.get(name);
737
+ if (!route) {
738
+ continue;
739
+ }
740
+ throw new RouteMapGeneratorError(
741
+ `The app route "${name}" (${route.trail}) is also registered by a package router (${where}). The app merges the two maps as { ...routeMap, ...packageRouteMap }, so the package entry wins the name at runtime while the generated types still describe the app's route \u2014 every call would go to the package's path. Rename the app route.`
742
+ );
392
743
  }
393
- return { importPaths, routeNames };
394
744
  }
395
- function generateRouteMapContent(routes) {
745
+ function collectRouteMap(router) {
746
+ const found = /* @__PURE__ */ new Map();
747
+ const packageNames = /* @__PURE__ */ new Map();
748
+ collectRoutes(router, ["router"], found, packageNames);
749
+ assertNoPackageCollision(found, packageNames);
750
+ return found;
751
+ }
752
+ function toObjectKey(name) {
753
+ if (name === "__proto__") {
754
+ return `[${JSON.stringify(name)}]`;
755
+ }
756
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
757
+ }
758
+ var SINGLE_QUOTABLE = /^[\x20-\x26\x28-\x5B\x5D-\x7E]*$/;
759
+ function toStringLiteral(value) {
760
+ if (SINGLE_QUOTABLE.test(value)) {
761
+ return `'${value}'`;
762
+ }
763
+ return JSON.stringify(value).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
764
+ }
765
+ function generateRouteMapContent(routes, nodeEnv) {
396
766
  const lines = [
397
767
  "/**",
398
768
  " * Route Map (Auto-generated)",
399
769
  " *",
400
770
  " * DO NOT EDIT - This file is generated by @spfn/core:route-map generator",
771
+ " *",
772
+ ` * Generated with NODE_ENV=${nodeEnv}. A route registered only under one environment is`,
773
+ " * named here only when the generator ran under it, so this line changing is that",
774
+ " * difference rather than an edit.",
401
775
  " */",
402
776
  "",
403
777
  "import type { HttpMethod } from '@spfn/core/route';",
@@ -410,8 +784,8 @@ function generateRouteMapContent(routes) {
410
784
  "",
411
785
  "export const routeMap: Record<string, RouteInfo> = {"
412
786
  ];
413
- for (const route of routes) {
414
- lines.push(` ${route.name}: { method: '${route.method}', path: '${route.path}' },`);
787
+ for (const [name, route] of routes) {
788
+ lines.push(` ${toObjectKey(name)}: { method: '${route.method}', path: ${toStringLiteral(route.path)} },`);
415
789
  }
416
790
  lines.push("};");
417
791
  lines.push("");
@@ -440,9 +814,11 @@ Usage:
440
814
  }
441
815
  return {
442
816
  name: "@spfn/core:route-map",
817
+ // Unchanged, including the deprecated dirs: what the map is *built* from
818
+ // moved to the loaded router, but what a rebuild should be *triggered* by
819
+ // is still every file a route can live in.
443
820
  watchPatterns: [
444
821
  routerPath,
445
- // Watch route directories derived from router imports
446
822
  "src/server/routes/**/*.ts",
447
823
  ...additionalRouteDirs.map((dir) => `${dir}/**/*.ts`)
448
824
  ],
@@ -456,97 +832,30 @@ Usage:
456
832
  return;
457
833
  }
458
834
  if (debug) {
459
- genLogger.info("Parsing router file", { path: absoluteRouterPath });
460
- }
461
- const { importPaths, routeNames } = parseRouterFile(absoluteRouterPath);
462
- if (debug) {
463
- genLogger.info("Found route imports", { count: importPaths.length, names: routeNames });
464
- }
465
- const routerDir = dirname(absoluteRouterPath);
466
- const allRoutes = [];
467
- for (const importPath of importPaths) {
468
- let resolvedPath = resolve(routerDir, importPath);
469
- if (!resolvedPath.endsWith(".ts")) {
470
- const withTs = resolvedPath + ".ts";
471
- if (existsSync(withTs)) {
472
- resolvedPath = withTs;
473
- } else {
474
- const indexPath = join(resolvedPath, "index.ts");
475
- if (existsSync(indexPath)) {
476
- resolvedPath = indexPath;
477
- } else {
478
- resolvedPath = withTs;
479
- }
480
- }
481
- }
482
- if (existsSync(resolvedPath)) {
483
- const routes = parseRouteFile(resolvedPath);
484
- allRoutes.push(...routes);
485
- if (debug) {
486
- genLogger.info(`Parsed ${routes.length} routes from ${relative(cwd, resolvedPath)}`);
487
- }
488
- }
835
+ genLogger.info("Loading router", { path: absoluteRouterPath });
489
836
  }
490
- const exportedRoutes = allRoutes.filter((r) => routeNames.includes(r.name));
837
+ pinNodeEnv();
838
+ const { router, exportName } = loadRouter(cwd, absoluteRouterPath);
839
+ assertUnconditionalRegistration({
840
+ routerPath,
841
+ source: readFileSync(absoluteRouterPath, "utf-8"),
842
+ exportName,
843
+ subject: "route map"
844
+ });
845
+ const routes = collectRouteMap(router);
491
846
  if (debug) {
492
- genLogger.info(`Found ${exportedRoutes.length} exported routes`);
847
+ genLogger.info(`Found ${routes.size} routes`, { names: [...routes.keys()] });
493
848
  }
494
- const content = generateRouteMapContent(exportedRoutes);
495
849
  const outputDir = dirname(absoluteOutputPath);
496
850
  if (!existsSync(outputDir)) {
497
851
  mkdirSync(outputDir, { recursive: true });
498
852
  }
499
- writeFileSync(absoluteOutputPath, content, "utf-8");
500
- genLogger.info(`Generated route map: ${relative(cwd, absoluteOutputPath)} (${exportedRoutes.length} routes)`);
853
+ const nodeEnv = process.env.NODE_ENV ?? "unset";
854
+ writeFileSync(absoluteOutputPath, generateRouteMapContent(routes, nodeEnv), "utf-8");
855
+ genLogger.info(`Generated route map: ${relative(cwd, absoluteOutputPath)} (${routes.size} routes)`);
501
856
  }
502
857
  };
503
858
  }
504
-
505
- // src/codegen/generators/contract-guard.ts
506
- var ConditionalRegistrationError = class extends Error {
507
- constructor(message) {
508
- super(message);
509
- this.name = "ConditionalRegistrationError";
510
- }
511
- };
512
- function defineRouterBlock(source) {
513
- const start = source.indexOf("defineRouter(");
514
- if (start === -1) {
515
- return void 0;
516
- }
517
- const open = source.indexOf("{", start);
518
- if (open === -1) {
519
- return void 0;
520
- }
521
- let depth = 1;
522
- let cursor = open + 1;
523
- while (depth > 0 && cursor < source.length) {
524
- if (source[cursor] === "{") depth++;
525
- else if (source[cursor] === "}") depth--;
526
- cursor++;
527
- }
528
- return source.slice(open + 1, cursor - 1).replace(/\/\/[^\n]*/g, "");
529
- }
530
- var PLAIN_REFERENCE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*\s*$/;
531
- function assertUnconditionalRegistration(routerPath, source) {
532
- const block = defineRouterBlock(source);
533
- if (!block) {
534
- return;
535
- }
536
- for (const [, expression] of block.matchAll(/\.\.\.\s*([^,\n]+)/g)) {
537
- if (PLAIN_REFERENCE.test(expression)) {
538
- continue;
539
- }
540
- throw new ConditionalRegistrationError(
541
- `${routerPath} registers routes conditionally: "...${expression.trim()}".
542
-
543
- A contract has to describe what production serves. When the route set depends on a flag or an environment, the generated contract describes whichever way the generator happened to run.
544
- Register contracted routes unconditionally, and gate behaviour inside the handler instead.`
545
- );
546
- }
547
- }
548
-
549
- // src/codegen/generators/contract.ts
550
859
  var genLogger2 = logger.child("@spfn/core:contract-generator");
551
860
  var ContractGeneratorError = class extends Error {
552
861
  constructor(message) {
@@ -554,39 +863,22 @@ var ContractGeneratorError = class extends Error {
554
863
  this.name = "ContractGeneratorError";
555
864
  }
556
865
  };
557
- function isRouter(value) {
558
- return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
559
- }
560
- function loadRouter(cwd, absoluteRouterPath, routerExport) {
561
- let module;
562
- try {
563
- const jiti = createJiti(cwd, { interopDefault: true, moduleCache: false });
564
- module = jiti(absoluteRouterPath);
565
- } catch (error) {
566
- const message = error instanceof Error ? error.message : String(error);
567
- throw new ContractGeneratorError(
568
- `Failed to load ${relative(cwd, absoluteRouterPath)}: ${message}
569
-
570
- The contract is read from the loaded router, so a route module must be importable without side effects. Check that nothing at module scope opens a connection or reads a missing environment value.`
571
- );
572
- }
866
+ function loadRouter2(cwd, absoluteRouterPath, routerExport) {
867
+ const module = loadRouterModule({
868
+ cwd,
869
+ absoluteRouterPath,
870
+ subject: "contract",
871
+ fail: (message) => new ContractGeneratorError(message)
872
+ });
573
873
  const candidates = routerExport ? [routerExport] : ["appRouter", "default", "router"];
574
- for (const name of candidates) {
575
- const candidate = module[name];
576
- if (isRouter(candidate)) {
577
- return candidate;
578
- }
874
+ const resolved = resolveRouterExport(module, candidates);
875
+ if (resolved) {
876
+ return resolved;
579
877
  }
580
878
  throw new ContractGeneratorError(
581
879
  `No router found in ${relative(cwd, absoluteRouterPath)}. Looked for: ${candidates.join(", ")}. Set "routerExport" to the export holding the defineRouter() result.`
582
880
  );
583
881
  }
584
- function pinNodeEnv() {
585
- if (!process.env.NODE_ENV) {
586
- process.env.NODE_ENV = "production";
587
- genLogger2.info('NODE_ENV was unset; pinned to "production" so the contract does not depend on the shell');
588
- }
589
- }
590
882
  function createContractGenerator(config) {
591
883
  const {
592
884
  routerPath,
@@ -623,8 +915,13 @@ Usage:
623
915
  );
624
916
  }
625
917
  pinNodeEnv();
626
- assertUnconditionalRegistration(routerPath, readFileSync(absoluteRouterPath, "utf-8"));
627
- const router = loadRouter(cwd, absoluteRouterPath, routerExport);
918
+ const { router, exportName } = loadRouter2(cwd, absoluteRouterPath, routerExport);
919
+ assertUnconditionalRegistration({
920
+ routerPath,
921
+ source: readFileSync(absoluteRouterPath, "utf-8"),
922
+ exportName,
923
+ subject: "contract"
924
+ });
628
925
  const document = collectContractDocument(router);
629
926
  const changed = writeCurrentDocument(contractsDir, document);
630
927
  genLogger2.info(
@@ -660,6 +957,6 @@ var generators = {
660
957
  contract: createContractGenerator
661
958
  };
662
959
 
663
- export { CodegenOrchestrator, ConditionalRegistrationError, ContractGeneratorError, assertUnconditionalRegistration, createGeneratorsFromConfig, defineConfig, defineGenerator, generators, loadCodegenConfig };
960
+ export { CodegenOrchestrator, ConditionalRegistrationError, ContractGeneratorError, RouteMapGeneratorError, assertUnconditionalRegistration, createGeneratorsFromConfig, defineConfig, defineGenerator, generators, loadCodegenConfig };
664
961
  //# sourceMappingURL=index.js.map
665
962
  //# sourceMappingURL=index.js.map