@teyik0/furin 0.2.0-alpha.2 → 0.2.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/bun.d.ts +3 -0
  4. package/dist/adapter/static.d.ts +3 -0
  5. package/dist/build/client.d.ts +25 -0
  6. package/dist/build/compile-entry.d.ts +9 -0
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +38 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +24 -0
  11. package/dist/build/index.d.ts +8 -0
  12. package/dist/build/index.js +8106 -0
  13. package/dist/build/route-types.d.ts +23 -0
  14. package/dist/build/scan-server.d.ts +8 -0
  15. package/dist/build/server-routes-entry.d.ts +13 -0
  16. package/dist/build/server-routes-entry.ts +36 -0
  17. package/dist/build/shared.d.ts +12 -0
  18. package/dist/build/ssg-cache.d.ts +4 -0
  19. package/dist/build/types.d.ts +80 -0
  20. package/dist/cli/config.d.ts +9 -0
  21. package/dist/cli/index.d.ts +2 -0
  22. package/dist/cli/index.js +8097 -0
  23. package/dist/client/boundaries.d.ts +117 -0
  24. package/dist/client/default-screens.d.ts +17 -0
  25. package/dist/client/link.d.ts +22 -0
  26. package/dist/client/link.js +4244 -0
  27. package/dist/client/router/boundary-tree.d.ts +26 -0
  28. package/dist/client/router/context.d.ts +8 -0
  29. package/dist/client/router/history.d.ts +9 -0
  30. package/dist/client/router/index.d.ts +11 -0
  31. package/dist/client/router/link-utils.d.ts +53 -0
  32. package/dist/client/router/navigation.d.ts +10 -0
  33. package/dist/client/router/provider.d.ts +4 -0
  34. package/dist/client/router/search/index.d.ts +18 -0
  35. package/dist/client/router/search-store.d.ts +21 -0
  36. package/dist/client/router/spa-response.d.ts +58 -0
  37. package/dist/client/router/types.d.ts +292 -0
  38. package/dist/client/server-error.d.ts +12 -0
  39. package/dist/client/sync.d.ts +25 -0
  40. package/dist/client.d.ts +243 -0
  41. package/dist/client.js +140 -0
  42. package/dist/config.d.ts +57 -0
  43. package/dist/config.js +29 -0
  44. package/dist/env.d.ts +50 -0
  45. package/dist/furin.d.ts +77 -0
  46. package/dist/furin.js +8693 -0
  47. package/dist/plugin/index.d.ts +20 -0
  48. package/dist/plugin/index.js +1500 -0
  49. package/dist/plugin/transform-client.d.ts +10 -0
  50. package/dist/server/auto-invalidate/index.d.ts +4 -0
  51. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  52. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  53. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  54. package/dist/server/auto-invalidate/types.d.ts +12 -0
  55. package/dist/server/cache/dev-loader.d.ts +28 -0
  56. package/dist/server/cache/index.d.ts +10 -0
  57. package/dist/server/cache/invalidation.d.ts +12 -0
  58. package/dist/server/cache/isr-ssg.d.ts +26 -0
  59. package/dist/server/cache/isr.d.ts +6 -0
  60. package/dist/server/cache/registry.d.ts +5 -0
  61. package/dist/server/cache/route-cache.d.ts +26 -0
  62. package/dist/server/cache/ssg.d.ts +5 -0
  63. package/dist/server/context-logger.d.ts +28 -0
  64. package/dist/server/dev-inspector.d.ts +89 -0
  65. package/dist/server/dev-page-plugin.d.ts +112 -0
  66. package/dist/server/internal.d.ts +35 -0
  67. package/dist/server/internal.js +17 -0
  68. package/dist/server/lang-detect.d.ts +5 -0
  69. package/dist/server/render/assemble.d.ts +49 -0
  70. package/dist/server/render/element.d.ts +24 -0
  71. package/dist/server/render/index.d.ts +7 -0
  72. package/dist/server/render/index.ts +22 -0
  73. package/dist/server/render/isr.d.ts +4 -0
  74. package/dist/server/render/loaders.d.ts +64 -0
  75. package/dist/server/render/not-found.d.ts +6 -0
  76. package/dist/server/render/shell.d.ts +39 -0
  77. package/dist/server/render/shell.ts +202 -0
  78. package/dist/server/render/ssg.d.ts +9 -0
  79. package/dist/server/render/ssr.d.ts +108 -0
  80. package/dist/server/render/template.d.ts +6 -0
  81. package/dist/server/router/discovery.d.ts +16 -0
  82. package/dist/server/router/hmr.d.ts +65 -0
  83. package/dist/server/router/index.d.ts +6 -0
  84. package/dist/server/router/index.js +27 -0
  85. package/dist/server/router/index.ts +28 -0
  86. package/dist/server/router/patterns.d.ts +40 -0
  87. package/dist/server/router/plugin.d.ts +21 -0
  88. package/dist/server/router/schemas.d.ts +59 -0
  89. package/dist/server/router/types.d.ts +60 -0
  90. package/dist/server/runtime-env.d.ts +3 -0
  91. package/dist/server/runtime-env.js +10 -0
  92. package/dist/server/sync/config.d.ts +6 -0
  93. package/dist/server/sync/index.d.ts +4 -0
  94. package/dist/server/sync/plugin.d.ts +369 -0
  95. package/dist/server/sync/stream.d.ts +47 -0
  96. package/dist/shared/await.d.ts +67 -0
  97. package/dist/shared/deferred-ndjson.d.ts +32 -0
  98. package/dist/shared/digest.d.ts +16 -0
  99. package/dist/shared/error.d.ts +37 -0
  100. package/dist/shared/not-found.d.ts +19 -0
  101. package/dist/shared/search-params.d.ts +17 -0
  102. package/dist/shared/utils/ast-walk.d.ts +18 -0
  103. package/dist/shared/utils/index.d.ts +13 -0
  104. package/package.json +5 -5
  105. package/src/adapter/README.md +13 -13
  106. package/src/build/client.ts +152 -152
  107. package/src/build/compile-entry.ts +109 -109
  108. package/src/build/entry-template.ts +156 -156
  109. package/src/build/hydrate.ts +340 -337
  110. package/src/build/index.ts +152 -152
  111. package/src/build/route-types.ts +145 -145
  112. package/src/build/scan-server.ts +95 -95
  113. package/src/build/server-routes-entry.ts +36 -36
  114. package/src/build/shared.ts +80 -79
  115. package/src/build/ssg-cache.ts +32 -32
  116. package/src/build/types.ts +89 -89
  117. package/src/client/router/link-utils.ts +184 -177
  118. package/src/client/router/provider.tsx +804 -759
  119. package/src/client/router/types.ts +276 -271
  120. package/src/client/sync.ts +98 -0
  121. package/src/client.ts +369 -355
  122. package/src/furin.ts +465 -444
  123. package/src/server/auto-invalidate/runtime.ts +134 -133
  124. package/src/server/dev-page-plugin.ts +454 -449
  125. package/src/server/render/assemble.ts +160 -133
  126. package/src/server/render/isr.ts +323 -317
  127. package/src/server/render/ssr.ts +585 -583
  128. package/src/server/router/plugin.ts +384 -384
  129. package/src/server/sync/config.ts +29 -0
  130. package/src/server/sync/index.ts +14 -0
  131. package/src/server/sync/plugin.ts +108 -0
  132. package/src/server/sync/stream.ts +144 -0
@@ -1,152 +1,152 @@
1
- import { existsSync, writeFileSync } from "node:fs";
2
- import { join, relative, resolve } from "node:path";
3
- import { buildBunTarget } from "../adapter/bun";
4
- import { buildStaticTarget } from "../adapter/static";
5
- import { BUILD_TARGETS, type BuildTarget, type FurinPlugin } from "../config";
6
- import { scanPages } from "../server/router/index.ts";
7
- import { scanFurinInstances } from "./scan-server";
8
- import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
- import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
10
-
11
- // biome-ignore lint/performance/noBarrelFile: intentional — build/index.ts is the public build API entry
12
- export { buildClient } from "./client";
13
- export { writeDevFiles } from "./hydrate";
14
- export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
15
- export { buildSSGCacheSnapshot, type SSGCacheSnapshot } from "./ssg-cache";
16
- export type {
17
- BuildAppOptions,
18
- BuildAppResult,
19
- BuildClientOptions,
20
- BuildManifest,
21
- BuildRouteManifestEntry,
22
- TargetBuildManifest,
23
- } from "./types";
24
-
25
- const IMPLEMENTED_TARGETS = ["bun", "static"] as const satisfies BuildTarget[];
26
- export const BUILD_OUTPUT_DIR = ".furin/build";
27
-
28
- function resolvePagesDirFromServer(serverEntry: string | null, rootDir: string): string | null {
29
- if (!serverEntry) {
30
- return null;
31
- }
32
- const detected = scanFurinInstances(serverEntry);
33
- if (detected.length === 0) {
34
- return null;
35
- }
36
- // Use the first detected pagesDir relative to rootDir
37
- return resolve(rootDir, detected[0] as string);
38
- }
39
-
40
- export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult> {
41
- const rootDir = resolve(options.rootDir ?? process.cwd());
42
- const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
43
- const serverEntry = (() => {
44
- // Static-only builds don't need a server entry point
45
- if (options.target === "static") {
46
- return null;
47
- }
48
- if (options.serverEntry) {
49
- const resolved = resolve(rootDir, options.serverEntry);
50
- if (existsSync(resolved)) {
51
- return resolved;
52
- }
53
- }
54
- const entry = resolve(rootDir, "src/server.ts");
55
- if (!existsSync(entry)) {
56
- throw new Error("[furin] Entrypoint server.ts not found");
57
- }
58
- return entry;
59
- })();
60
-
61
- // Register user plugins as runtime module loaders BEFORE scanPages.
62
- //
63
- // scanPages() calls import() on every page file, which triggers all their
64
- // static imports (e.g. ".mdx" files). If the loader is not yet registered
65
- // at that point, Bun caches the raw/unprocessed result — and that cached
66
- // value is reused for every subsequent import(), including prerenderSSG().
67
- //
68
- // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
69
- // doesn't exist in the runtime context) are skipped silently — they only
70
- // affect the Bun.build() client bundle, not server-side rendering.
71
- for (const plugin of options.plugins ?? []) {
72
- const { buildOnly, ...runtimePlugin } = plugin as FurinPlugin;
73
- if (buildOnly) {
74
- continue;
75
- }
76
- try {
77
- Bun.plugin(runtimePlugin);
78
- } catch (err) {
79
- console.debug("[furin] Skipped plugin at runtime:", err);
80
- }
81
- }
82
-
83
- // Priority: explicit config > auto-detected from server entry > default
84
- const rawPagesDir =
85
- options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
86
- const pagesDir = resolve(rootDir, rawPagesDir);
87
-
88
- const requestedTargets =
89
- options.target === "all"
90
- ? [...IMPLEMENTED_TARGETS]
91
- : [options.target].map((target) => {
92
- if (!(BUILD_TARGETS as readonly string[]).includes(target)) {
93
- throw new Error(`[furin] Unsupported build target "${target}"`);
94
- }
95
- return target as BuildTarget;
96
- });
97
-
98
- // scanPages throws if root.tsx is missing, so root is always defined here.
99
- const { root, routes } = await scanPages(pagesDir);
100
-
101
- ensureDir(buildRoot);
102
-
103
- const manifest: BuildManifest = {
104
- version: 1,
105
- generatedAt: new Date().toISOString(),
106
- rootDir: toPosixPath(rootDir),
107
- pagesDir: toPosixPath(relative(rootDir, pagesDir)),
108
- rootPath: toPosixPath(relative(rootDir, root.path)),
109
- serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null,
110
- routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
111
- targets: {},
112
- };
113
-
114
- for (const target of requestedTargets) {
115
- switch (target) {
116
- case "bun":
117
- manifest.targets.bun = await buildBunTarget(
118
- routes,
119
- rootDir,
120
- buildRoot,
121
- root,
122
- serverEntry,
123
- options
124
- );
125
- break;
126
- case "static":
127
- manifest.targets.static = await buildStaticTarget(
128
- routes,
129
- rootDir,
130
- buildRoot,
131
- root,
132
- options
133
- );
134
- break;
135
- case "node":
136
- case "vercel":
137
- case "cloudflare":
138
- throw new Error(
139
- `[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`
140
- );
141
- default:
142
- throw new Error(`[furin] Unsupported build target "${target}"`);
143
- }
144
- }
145
-
146
- writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
147
-
148
- return {
149
- manifest,
150
- targets: manifest.targets,
151
- };
152
- }
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve } from "node:path";
3
+ import { buildBunTarget } from "../adapter/bun";
4
+ import { buildStaticTarget } from "../adapter/static";
5
+ import { BUILD_TARGETS, type BuildTarget, type FurinPlugin } from "../config";
6
+ import { scanPages } from "../server/router/index.ts";
7
+ import { scanFurinInstances } from "./scan-server";
8
+ import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
+ import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
10
+
11
+ // biome-ignore lint/performance/noBarrelFile: intentional — build/index.ts is the public build API entry
12
+ export { buildClient } from "./client";
13
+ export { writeDevFiles } from "./hydrate";
14
+ export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
15
+ export { buildSSGCacheSnapshot, type SSGCacheSnapshot } from "./ssg-cache";
16
+ export type {
17
+ BuildAppOptions,
18
+ BuildAppResult,
19
+ BuildClientOptions,
20
+ BuildManifest,
21
+ BuildRouteManifestEntry,
22
+ TargetBuildManifest,
23
+ } from "./types";
24
+
25
+ const IMPLEMENTED_TARGETS = ["bun", "static"] as const satisfies BuildTarget[];
26
+ export const BUILD_OUTPUT_DIR = ".furin/build";
27
+
28
+ function resolvePagesDirFromServer(serverEntry: string | null, rootDir: string): string | null {
29
+ if (!serverEntry) {
30
+ return null;
31
+ }
32
+ const detected = scanFurinInstances(serverEntry);
33
+ if (detected.length === 0) {
34
+ return null;
35
+ }
36
+ // Use the first detected pagesDir relative to rootDir
37
+ return resolve(rootDir, detected[0] as string);
38
+ }
39
+
40
+ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult> {
41
+ const rootDir = resolve(options.rootDir ?? process.cwd());
42
+ const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
43
+ const serverEntry = (() => {
44
+ // Static-only builds don't need a server entry point
45
+ if (options.target === "static") {
46
+ return null;
47
+ }
48
+ if (options.serverEntry) {
49
+ const resolved = resolve(rootDir, options.serverEntry);
50
+ if (existsSync(resolved)) {
51
+ return resolved;
52
+ }
53
+ }
54
+ const entry = resolve(rootDir, "src/server.ts");
55
+ if (!existsSync(entry)) {
56
+ throw new Error("[furin] Entrypoint server.ts not found");
57
+ }
58
+ return entry;
59
+ })();
60
+
61
+ // Register user plugins as runtime module loaders BEFORE scanPages.
62
+ //
63
+ // scanPages() calls import() on every page file, which triggers all their
64
+ // static imports (e.g. ".mdx" files). If the loader is not yet registered
65
+ // at that point, Bun caches the raw/unprocessed result — and that cached
66
+ // value is reused for every subsequent import(), including prerenderSSG().
67
+ //
68
+ // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
69
+ // doesn't exist in the runtime context) are skipped silently — they only
70
+ // affect the Bun.build() client bundle, not server-side rendering.
71
+ for (const plugin of options.plugins ?? []) {
72
+ const { buildOnly, ...runtimePlugin } = plugin as FurinPlugin;
73
+ if (buildOnly) {
74
+ continue;
75
+ }
76
+ try {
77
+ Bun.plugin(runtimePlugin);
78
+ } catch (err) {
79
+ console.debug("[furin] Skipped plugin at runtime:", err);
80
+ }
81
+ }
82
+
83
+ // Priority: explicit config > auto-detected from server entry > default
84
+ const rawPagesDir =
85
+ options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
86
+ const pagesDir = resolve(rootDir, rawPagesDir);
87
+
88
+ const requestedTargets =
89
+ options.target === "all"
90
+ ? [...IMPLEMENTED_TARGETS]
91
+ : [options.target].map((target) => {
92
+ if (!(BUILD_TARGETS as readonly string[]).includes(target)) {
93
+ throw new Error(`[furin] Unsupported build target "${target}"`);
94
+ }
95
+ return target as BuildTarget;
96
+ });
97
+
98
+ // scanPages throws if root.tsx is missing, so root is always defined here.
99
+ const { root, routes } = await scanPages(pagesDir);
100
+
101
+ ensureDir(buildRoot);
102
+
103
+ const manifest: BuildManifest = {
104
+ version: 1,
105
+ generatedAt: new Date().toISOString(),
106
+ rootDir: toPosixPath(rootDir),
107
+ pagesDir: toPosixPath(relative(rootDir, pagesDir)),
108
+ rootPath: toPosixPath(relative(rootDir, root.path)),
109
+ serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null,
110
+ routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
111
+ targets: {},
112
+ };
113
+
114
+ for (const target of requestedTargets) {
115
+ switch (target) {
116
+ case "bun":
117
+ manifest.targets.bun = await buildBunTarget(
118
+ routes,
119
+ rootDir,
120
+ buildRoot,
121
+ root,
122
+ serverEntry,
123
+ options
124
+ );
125
+ break;
126
+ case "static":
127
+ manifest.targets.static = await buildStaticTarget(
128
+ routes,
129
+ rootDir,
130
+ buildRoot,
131
+ root,
132
+ options
133
+ );
134
+ break;
135
+ case "node":
136
+ case "vercel":
137
+ case "cloudflare":
138
+ throw new Error(
139
+ `[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`
140
+ );
141
+ default:
142
+ throw new Error(`[furin] Unsupported build target "${target}"`);
143
+ }
144
+ }
145
+
146
+ writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
147
+
148
+ return {
149
+ manifest,
150
+ targets: manifest.targets,
151
+ };
152
+ }
@@ -1,145 +1,145 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { mergeRouteSchemas, type ResolvedRoute } from "../server/router/index.ts";
4
-
5
- /** @internal Exported for unit testing only. */
6
- export function patternToTypeString(pattern: string): string {
7
- // biome-ignore lint/suspicious/noTemplateCurlyInString: intentional — generates TS template literal syntax
8
- const t = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
9
- return t.includes("${") ? `\`${t}\`` : `"${t}"`;
10
- }
11
-
12
- /**
13
- * Converts a runtime TypeBox/JSON Schema object to a TypeScript type string.
14
- * Handles the common cases found in Elysia query schemas (string, number, boolean,
15
- * optional fields, nullable via anyOf).
16
- *
17
- * @internal Exported for unit testing only.
18
- */
19
- export function schemaToTypeString(schema: unknown): string {
20
- return schemaToTypeStringWithDefaults(schema, true);
21
- }
22
-
23
- function schemaToTypeStringWithDefaults(schema: unknown, defaultsAreRequired: boolean): string {
24
- if (!schema || typeof schema !== "object") {
25
- return "unknown";
26
- }
27
- const s = schema as Record<string, unknown>;
28
- if (s.anyOf && Array.isArray(s.anyOf)) {
29
- const parts: string[] = [];
30
- for (const item of s.anyOf as unknown[]) {
31
- const t = schemaToTypeStringWithDefaults(item, defaultsAreRequired);
32
- if (t !== "null") parts.push(t);
33
- }
34
- return parts.join(" | ") || "unknown";
35
- }
36
- switch (s.type) {
37
- case "string":
38
- return "string";
39
- case "number":
40
- case "integer":
41
- return "number";
42
- case "boolean":
43
- return "boolean";
44
- case "null":
45
- return "null";
46
- case "array": {
47
- const inner = schemaToTypeStringWithDefaults(s.items, defaultsAreRequired);
48
- return inner.includes("|") || inner.includes("&") ? `(${inner})[]` : `${inner}[]`;
49
- }
50
- case "object": {
51
- if (!s.properties || typeof s.properties !== "object") {
52
- return "Record<string, unknown>";
53
- }
54
- const required = new Set<string>(Array.isArray(s.required) ? (s.required as string[]) : []);
55
- const props = Object.entries(s.properties as Record<string, unknown>)
56
- .map(([k, v]) => {
57
- const isPresent =
58
- required.has(k) || (defaultsAreRequired && hasNonNullSchemaDefault(v));
59
- return `${k}${isPresent ? "" : "?"}: ${schemaToTypeStringWithDefaults(v, defaultsAreRequired)}`;
60
- })
61
- .join("; ");
62
- return `{ ${props} }`;
63
- }
64
- default:
65
- return "unknown";
66
- }
67
- }
68
-
69
- /** @internal Exported for unit testing only. */
70
- export function schemaToInputTypeString(schema: unknown): string {
71
- return schemaToTypeStringWithDefaults(schema, false);
72
- }
73
-
74
- function hasNonNullSchemaDefault(schema: unknown): boolean {
75
- if (!schema || typeof schema !== "object") {
76
- return false;
77
- }
78
- const s = schema as Record<string, unknown>;
79
- return (
80
- "default" in s &&
81
- s.default != null
82
- );
83
- }
84
-
85
- function tagKeyToPropertyName(tag: string): string {
86
- return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
87
- }
88
-
89
- function tagToStringLiteral(tag: string): string {
90
- // Use JSON.stringify for robust escaping of control chars, unicode
91
- // separators, backslashes and quotes, then convert double quotes to single.
92
- const json = JSON.stringify(tag);
93
- // json is double-quoted; convert to single-quoted literal by escaping
94
- // any contained single quotes and swapping the outer quotes.
95
- return `'${json.slice(1, -1).replaceAll("'", "\\'")}'`;
96
- }
97
-
98
- /**
99
- * Generates furin-env.d.ts at the project root — augments RouteManifest
100
- * in furin/link so that <Link to="..."> has type-safe autocompletion and
101
- * <Link search={...}> is typed per-route from the route's query schema.
102
- *
103
- * Written to the project root (like Next.js's next-env.d.ts) so it is
104
- * committed to git and always available in CI without a build step.
105
- */
106
- /** @internal Exported for unit testing only. */
107
- export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): void {
108
- const sortedRoutes = [...routes].sort((a, b) => a.pattern.localeCompare(b.pattern));
109
- const entries = sortedRoutes.map((r) => {
110
- const typeKey = patternToTypeString(r.pattern);
111
- const isDynamic = typeKey.startsWith("`");
112
- const querySchema = mergeRouteSchemas(r.routeChain ?? [], "query");
113
- const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
114
- const searchInputType = querySchema ? schemaToInputTypeString(querySchema) : "never";
115
- return isDynamic
116
- ? ` [key: ${typeKey}]: { search?: ${searchType}; searchInput?: ${searchInputType} }`
117
- : ` ${typeKey}: { search?: ${searchType}; searchInput?: ${searchInputType} }`;
118
- });
119
- const routeManifestEntries = entries.join(";\n");
120
-
121
- const sortedTags = [...new Set(routes.flatMap((route) => route.tags ?? []))].sort();
122
- const tagBlock =
123
- sortedTags.length > 0
124
- ? `\n\ndeclare module "@teyik0/furin" {\n interface FurinCacheTags {\n${sortedTags
125
- .map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`)
126
- .join("\n")}\n }\n}`
127
- : "";
128
-
129
- const content = `// Auto-generated by Furin. Do not edit manually.
130
- /// <reference types="@teyik0/furin/env" />
131
- import "@teyik0/furin/link";
132
-
133
- declare module "@teyik0/furin/link" {
134
- interface RouteManifest {
135
- ${routeManifestEntries};
136
- }
137
- }${tagBlock}
138
- `;
139
-
140
- const typesPath = join(projectRoot, "furin-env.d.ts");
141
- const existing = existsSync(typesPath) ? readFileSync(typesPath, "utf8") : "";
142
- if (content !== existing) {
143
- writeFileSync(typesPath, content);
144
- }
145
- }
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { mergeRouteSchemas, type ResolvedRoute } from "../server/router/index.ts";
4
+
5
+ /** @internal Exported for unit testing only. */
6
+ export function patternToTypeString(pattern: string): string {
7
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: intentional — generates TS template literal syntax
8
+ const t = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
9
+ return t.includes("${") ? `\`${t}\`` : `"${t}"`;
10
+ }
11
+
12
+ /**
13
+ * Converts a runtime TypeBox/JSON Schema object to a TypeScript type string.
14
+ * Handles the common cases found in Elysia query schemas (string, number, boolean,
15
+ * optional fields, nullable via anyOf).
16
+ *
17
+ * @internal Exported for unit testing only.
18
+ */
19
+ export function schemaToTypeString(schema: unknown): string {
20
+ return schemaToTypeStringWithDefaults(schema, true);
21
+ }
22
+
23
+ function schemaToTypeStringWithDefaults(schema: unknown, defaultsAreRequired: boolean): string {
24
+ if (!schema || typeof schema !== "object") {
25
+ return "unknown";
26
+ }
27
+ const s = schema as Record<string, unknown>;
28
+ if (s.anyOf && Array.isArray(s.anyOf)) {
29
+ const parts: string[] = [];
30
+ for (const item of s.anyOf as unknown[]) {
31
+ const t = schemaToTypeStringWithDefaults(item, defaultsAreRequired);
32
+ if (t !== "null") parts.push(t);
33
+ }
34
+ return parts.join(" | ") || "unknown";
35
+ }
36
+ switch (s.type) {
37
+ case "string":
38
+ return "string";
39
+ case "number":
40
+ case "integer":
41
+ return "number";
42
+ case "boolean":
43
+ return "boolean";
44
+ case "null":
45
+ return "null";
46
+ case "array": {
47
+ const inner = schemaToTypeStringWithDefaults(s.items, defaultsAreRequired);
48
+ return inner.includes("|") || inner.includes("&") ? `(${inner})[]` : `${inner}[]`;
49
+ }
50
+ case "object": {
51
+ if (!s.properties || typeof s.properties !== "object") {
52
+ return "Record<string, unknown>";
53
+ }
54
+ const required = new Set<string>(Array.isArray(s.required) ? (s.required as string[]) : []);
55
+ const props = Object.entries(s.properties as Record<string, unknown>)
56
+ .map(([k, v]) => {
57
+ const isPresent =
58
+ required.has(k) || (defaultsAreRequired && hasNonNullSchemaDefault(v));
59
+ return `${k}${isPresent ? "" : "?"}: ${schemaToTypeStringWithDefaults(v, defaultsAreRequired)}`;
60
+ })
61
+ .join("; ");
62
+ return `{ ${props} }`;
63
+ }
64
+ default:
65
+ return "unknown";
66
+ }
67
+ }
68
+
69
+ /** @internal Exported for unit testing only. */
70
+ export function schemaToInputTypeString(schema: unknown): string {
71
+ return schemaToTypeStringWithDefaults(schema, false);
72
+ }
73
+
74
+ function hasNonNullSchemaDefault(schema: unknown): boolean {
75
+ if (!schema || typeof schema !== "object") {
76
+ return false;
77
+ }
78
+ const s = schema as Record<string, unknown>;
79
+ return (
80
+ "default" in s &&
81
+ s.default != null
82
+ );
83
+ }
84
+
85
+ function tagKeyToPropertyName(tag: string): string {
86
+ return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
87
+ }
88
+
89
+ function tagToStringLiteral(tag: string): string {
90
+ // Use JSON.stringify for robust escaping of control chars, unicode
91
+ // separators, backslashes and quotes, then convert double quotes to single.
92
+ const json = JSON.stringify(tag);
93
+ // json is double-quoted; convert to single-quoted literal by escaping
94
+ // any contained single quotes and swapping the outer quotes.
95
+ return `'${json.slice(1, -1).replaceAll("'", "\\'")}'`;
96
+ }
97
+
98
+ /**
99
+ * Generates furin-env.d.ts at the project root — augments RouteManifest
100
+ * in furin/link so that <Link to="..."> has type-safe autocompletion and
101
+ * <Link search={...}> is typed per-route from the route's query schema.
102
+ *
103
+ * Written to the project root (like Next.js's next-env.d.ts) so it is
104
+ * committed to git and always available in CI without a build step.
105
+ */
106
+ /** @internal Exported for unit testing only. */
107
+ export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): void {
108
+ const sortedRoutes = [...routes].sort((a, b) => a.pattern.localeCompare(b.pattern));
109
+ const entries = sortedRoutes.map((r) => {
110
+ const typeKey = patternToTypeString(r.pattern);
111
+ const isDynamic = typeKey.startsWith("`");
112
+ const querySchema = mergeRouteSchemas(r.routeChain ?? [], "query");
113
+ const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
114
+ const searchInputType = querySchema ? schemaToInputTypeString(querySchema) : "never";
115
+ return isDynamic
116
+ ? ` [key: ${typeKey}]: { search?: ${searchType}; searchInput?: ${searchInputType} }`
117
+ : ` ${typeKey}: { search?: ${searchType}; searchInput?: ${searchInputType} }`;
118
+ });
119
+ const routeManifestEntries = entries.join(";\n");
120
+
121
+ const sortedTags = [...new Set(routes.flatMap((route) => route.tags ?? []))].sort();
122
+ const tagBlock =
123
+ sortedTags.length > 0
124
+ ? `\n\ndeclare module "@teyik0/furin" {\n interface FurinCacheTags {\n${sortedTags
125
+ .map((tag) => ` ${tagKeyToPropertyName(tag)}: ${tagToStringLiteral(tag)};`)
126
+ .join("\n")}\n }\n}`
127
+ : "";
128
+
129
+ const content = `// Auto-generated by Furin. Do not edit manually.
130
+ /// <reference types="@teyik0/furin/env" />
131
+ import "@teyik0/furin/link";
132
+
133
+ declare module "@teyik0/furin/link" {
134
+ interface RouteManifest {
135
+ ${routeManifestEntries};
136
+ }
137
+ }${tagBlock}
138
+ `;
139
+
140
+ const typesPath = join(projectRoot, "furin-env.d.ts");
141
+ const existing = existsSync(typesPath) ? readFileSync(typesPath, "utf8") : "";
142
+ if (content !== existing) {
143
+ writeFileSync(typesPath, content);
144
+ }
145
+ }