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

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 (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
@@ -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
+ }
@@ -1,95 +1,111 @@
1
- import { readFileSync } from "node:fs";
2
- import { parse, type CallExpression, type ObjectExpression, type ObjectProperty } from "yuku-parser";
3
- import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
4
- import { walkAST } from "../shared/utils/ast-walk.ts";
5
-
6
- /**
7
- * Statically scans a server entry file and returns all `pagesDir` string
8
- * literal values found inside `furin({ pagesDir: "..." })` call expressions.
9
- *
10
- * Dynamic paths (template literals, variables) are silently ignored.
11
- * Returns an empty array when nothing is detected.
12
- */
13
- export function scanFurinInstances(serverEntryPath: string): string[] {
14
- const code = readFileSync(serverEntryPath, "utf8");
15
- const lang = detectLangFromPath(serverEntryPath);
16
-
17
- // Declaration files contain no runtime code — skip parsing.
18
- if (lang === "dts") {
19
- return [];
20
- }
21
-
22
- const { program, diagnostics } = parse(code, { sourceType: "module", lang });
23
- const firstError = diagnostics.find((d) => d.severity === "error");
24
- if (firstError) {
25
- console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
26
- return [];
27
- }
28
-
29
- const results: string[] = [];
30
- walkAST(program, (node) => {
31
- if (node.type === "CallExpression") {
32
- checkFurinCall(node as unknown as CallExpression, results);
33
- }
34
- });
35
- return results;
36
- }
37
-
38
- /** Checks whether `node` is a `furin({ pagesDir: "..." })` call and, if so, pushes the value. */
39
- function checkFurinCall(node: CallExpression, out: string[]): void {
40
- const isFurinCall = node.callee.type === "Identifier" && node.callee.name === "furin";
41
-
42
- if (!isFurinCall || node.arguments.length === 0) {
43
- return;
44
- }
45
-
46
- // Unwrap TS expression wrappers like `furin({...} as Config)` or
47
- // `furin({...} satisfies Options)` so we still see the ObjectExpression.
48
- const firstArgNode = node.arguments[0];
49
- if (!firstArgNode) {
50
- return;
51
- }
52
- const firstArg = unwrapTSExpression(firstArgNode);
53
- if (!isObjectExpressionNode(firstArg)) {
54
- return;
55
- }
56
-
57
- const pagesDir = extractStringProperty(firstArg, "pagesDir");
58
- if (pagesDir !== null) {
59
- out.push(pagesDir);
60
- }
61
- }
62
-
63
- function isObjectExpressionNode(node: { type: string }): node is ObjectExpression {
64
- return node.type === "ObjectExpression";
65
- }
66
-
67
- function extractStringProperty(obj: ObjectExpression, propName: string): string | null {
68
- for (const prop of obj.properties) {
69
- if (prop.type !== "Property") {
70
- continue;
71
- }
72
- const value = getStringPropertyValue(prop, propName);
73
-
74
- if (value !== undefined) {
75
- return value;
76
- }
77
- }
78
- return null;
79
- }
80
-
81
- function getStringPropertyValue(prop: ObjectProperty, propName: string): string | null | undefined {
82
- const keyMatches =
83
- (prop.key.type === "Identifier" && prop.key.name === propName) ||
84
- (prop.key.type === "Literal" && prop.key.value === propName);
85
-
86
- if (!keyMatches) {
87
- return undefined;
88
- }
89
-
90
- // Only accept string literals — ignore template literals, identifiers, etc.
91
- if (prop.value.type === "Literal" && typeof prop.value.value === "string") {
92
- return prop.value.value;
93
- }
94
- return null; // dynamic path — silently skip
95
- }
1
+ import { readFileSync } from "node:fs";
2
+ import { parse, type CallExpression, type ObjectExpression, type ObjectProperty } from "yuku-parser";
3
+ import { normalizePrefix } from "../server/instance.ts";
4
+ import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
5
+ import { walkAST } from "../shared/utils/ast-walk.ts";
6
+
7
+ export interface ScannedFurinInstance {
8
+ pagesDir: string;
9
+ /** Normalized mount prefix (`""` when absent). */
10
+ prefix: string;
11
+ }
12
+
13
+ /**
14
+ * Statically scans a server entry file and returns the `pagesDir` (and
15
+ * optional `prefix`) string literals found inside `furin({ pagesDir: "..." })`
16
+ * call expressions.
17
+ *
18
+ * Dynamic values (template literals, variables) are silently ignored.
19
+ * Returns an empty array when nothing is detected.
20
+ */
21
+ export function scanFurinInstances(serverEntryPath: string): ScannedFurinInstance[] {
22
+ const code = readFileSync(serverEntryPath, "utf8");
23
+ const lang = detectLangFromPath(serverEntryPath);
24
+
25
+ // Declaration files contain no runtime code — skip parsing.
26
+ if (lang === "dts") {
27
+ return [];
28
+ }
29
+
30
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
31
+ const firstError = diagnostics.find((d) => d.severity === "error");
32
+ if (firstError) {
33
+ console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
34
+ return [];
35
+ }
36
+
37
+ const results: ScannedFurinInstance[] = [];
38
+ walkAST(program, (node) => {
39
+ if (node.type === "CallExpression") {
40
+ checkFurinCall(node as unknown as CallExpression, results);
41
+ }
42
+ });
43
+ return results;
44
+ }
45
+
46
+ /** Checks whether `node` is a `furin({ pagesDir: "..." })` call and, if so, pushes the value. */
47
+ function checkFurinCall(node: CallExpression, out: ScannedFurinInstance[]): void {
48
+ const isFurinCall = node.callee.type === "Identifier" && node.callee.name === "furin";
49
+
50
+ if (!isFurinCall || node.arguments.length === 0) {
51
+ return;
52
+ }
53
+
54
+ // Unwrap TS expression wrappers like `furin({...} as Config)` or
55
+ // `furin({...} satisfies Options)` so we still see the ObjectExpression.
56
+ const firstArgNode = node.arguments[0];
57
+ if (!firstArgNode) {
58
+ return;
59
+ }
60
+ const firstArg = unwrapTSExpression(firstArgNode);
61
+ if (!isObjectExpressionNode(firstArg)) {
62
+ return;
63
+ }
64
+
65
+ const pagesDir = extractStringProperty(firstArg, "pagesDir");
66
+ if (pagesDir !== null) {
67
+ const prefix = extractStringProperty(firstArg, "prefix");
68
+ out.push({ pagesDir, prefix: normalizeScannedPrefix(prefix) });
69
+ }
70
+ }
71
+
72
+ // Delegates to the runtime's normalizePrefix so a literal that would make
73
+ // `furin()` throw at startup fails at build time too, with the same message —
74
+ // silently "fixing" it here would build assets the runtime never serves.
75
+ function normalizeScannedPrefix(prefix: string | null): string {
76
+ return normalizePrefix(prefix ?? undefined);
77
+ }
78
+
79
+ function isObjectExpressionNode(node: { type: string }): node is ObjectExpression {
80
+ return node.type === "ObjectExpression";
81
+ }
82
+
83
+ function extractStringProperty(obj: ObjectExpression, propName: string): string | null {
84
+ for (const prop of obj.properties) {
85
+ if (prop.type !== "Property") {
86
+ continue;
87
+ }
88
+ const value = getStringPropertyValue(prop, propName);
89
+
90
+ if (value !== undefined) {
91
+ return value;
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+
97
+ function getStringPropertyValue(prop: ObjectProperty, propName: string): string | null | undefined {
98
+ const keyMatches =
99
+ (prop.key.type === "Identifier" && prop.key.name === propName) ||
100
+ (prop.key.type === "Literal" && prop.key.value === propName);
101
+
102
+ if (!keyMatches) {
103
+ return undefined;
104
+ }
105
+
106
+ // Only accept string literals — ignore template literals, identifiers, etc.
107
+ if (prop.value.type === "Literal" && typeof prop.value.value === "string") {
108
+ return prop.value.value;
109
+ }
110
+ return null; // dynamic path — silently skip
111
+ }
@@ -1,36 +1,30 @@
1
- import { writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
4
- import { ensureDir } from "./shared";
5
-
6
- /**
7
- * Generates `server.ts` — an intermediate entry used to produce `server.js`.
8
- *
9
- * Equivalent to `_compile-entry.ts` but for disk (non-binary) production builds:
10
- * 1. Statically imports every page module so Bun bundles them into server.js
11
- * 2. Sets production mode and registers everything in a single CompileContext
12
- * 3. Imports server.ts to boot the app
13
- *
14
- * This file is intermediate: `adapter/bun.ts` runs `Bun.build()` on it to produce
15
- * the self-contained `server.js` bundle, then deletes this file.
16
- */
17
- export function generateServerRoutesEntry(options: BuildEntryOptions): string {
18
- const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } =
19
- options;
20
- ensureDir(outDir);
21
- const source = buildEntrySource({
22
- buildId,
23
- headerComment: "// Auto-generated by furin build — do not edit",
24
- rootPath,
25
- routes,
26
- serverEntry,
27
- rootConventions,
28
- routeMetadata,
29
- ssgCache,
30
- });
31
-
32
- // Named "server.ts" so Bun.build() outputs "server.js"
33
- const entryPath = join(outDir, "server.ts");
34
- writeFileSync(entryPath, source);
35
- return entryPath;
36
- }
1
+ import { writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
4
+ import { ensureDir } from "./shared";
5
+
6
+ /**
7
+ * Generates `server.ts` — an intermediate entry used to produce `server.js`.
8
+ *
9
+ * Equivalent to `_compile-entry.ts` but for disk (non-binary) production builds:
10
+ * 1. Statically imports every page module of every app so Bun bundles them
11
+ * 2. Sets production mode and registers one CompileContext PER APP
12
+ * 3. Imports server.ts to boot the composed app
13
+ *
14
+ * This file is intermediate: `adapter/bun.ts` runs `Bun.build()` on it to produce
15
+ * the self-contained `server.js` bundle, then deletes this file.
16
+ */
17
+ export function generateServerRoutesEntry(options: BuildEntryOptions): string {
18
+ const { apps, outDir, serverEntry } = options;
19
+ ensureDir(outDir);
20
+ const source = buildEntrySource({
21
+ apps: apps.map(({ embed: _embed, ...context }) => context),
22
+ headerComment: "// Auto-generated by furin build — do not edit",
23
+ serverEntry,
24
+ });
25
+
26
+ // Named "server.ts" so Bun.build() outputs "server.js"
27
+ const entryPath = join(outDir, "server.ts");
28
+ writeFileSync(entryPath, source);
29
+ return entryPath;
30
+ }