@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.15

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 (69) hide show
  1. package/README.md +14 -232
  2. package/dist/auto-invalidate/index.d.ts +4 -0
  3. package/dist/auto-invalidate/plugin.d.ts +38 -0
  4. package/dist/auto-invalidate/registry.d.ts +9 -0
  5. package/dist/auto-invalidate/runtime.d.ts +9 -0
  6. package/dist/auto-invalidate/types.d.ts +12 -0
  7. package/dist/await.d.ts +67 -0
  8. package/dist/build/index.js +2095 -185
  9. package/dist/cli/index.js +2070 -182
  10. package/dist/client.d.ts +51 -4
  11. package/dist/client.js +65 -1
  12. package/dist/deferred-ndjson.d.ts +32 -0
  13. package/dist/error.d.ts +14 -0
  14. package/dist/furin.d.ts +8 -0
  15. package/dist/furin.js +2927 -319
  16. package/dist/lang-detect.d.ts +5 -0
  17. package/dist/link.d.ts +1 -0
  18. package/dist/link.js +1453 -95
  19. package/dist/plugin/index.js +96 -25
  20. package/dist/plugin/transform-client.d.ts +2 -1
  21. package/dist/render/assemble.d.ts +32 -0
  22. package/dist/render/cache.d.ts +7 -0
  23. package/dist/render/element.d.ts +17 -1
  24. package/dist/render/index.d.ts +10 -1
  25. package/dist/render/index.ts +250 -44
  26. package/dist/render/loaders.d.ts +46 -3
  27. package/dist/render/shell.d.ts +16 -6
  28. package/dist/render/shell.ts +27 -12
  29. package/dist/router-provider.d.ts +86 -18
  30. package/dist/router.d.ts +66 -0
  31. package/dist/router.js +2909 -374
  32. package/dist/router.ts +586 -54
  33. package/dist/server-error.d.ts +12 -0
  34. package/dist/utils.d.ts +7 -0
  35. package/package.json +8 -7
  36. package/src/adapter/bun.ts +3 -3
  37. package/src/adapter/static.ts +73 -31
  38. package/src/auto-invalidate/index.ts +10 -0
  39. package/src/auto-invalidate/plugin.ts +25 -0
  40. package/src/auto-invalidate/registry.ts +60 -0
  41. package/src/auto-invalidate/runtime.ts +133 -0
  42. package/src/auto-invalidate/types.ts +16 -0
  43. package/src/await.tsx +175 -0
  44. package/src/build/client.ts +4 -8
  45. package/src/build/hydrate.ts +67 -1
  46. package/src/build/route-types.ts +29 -3
  47. package/src/build/scan-server.ts +6 -23
  48. package/src/client.ts +80 -3
  49. package/src/deferred-ndjson.ts +212 -0
  50. package/src/dev-page-plugin.ts +2 -0
  51. package/src/error.ts +18 -1
  52. package/src/furin.ts +19 -2
  53. package/src/lang-detect.ts +46 -0
  54. package/src/link.tsx +16 -3
  55. package/src/plugin/index.ts +7 -8
  56. package/src/plugin/transform-client.ts +108 -39
  57. package/src/render/assemble.ts +67 -0
  58. package/src/render/boundaries.tsx +23 -5
  59. package/src/render/cache.ts +14 -0
  60. package/src/render/default-screens.tsx +4 -11
  61. package/src/render/dev-cache.ts +5 -0
  62. package/src/render/element.tsx +26 -3
  63. package/src/render/index.ts +250 -44
  64. package/src/render/loaders.ts +219 -18
  65. package/src/render/shell.ts +27 -12
  66. package/src/router-provider.tsx +414 -122
  67. package/src/router.ts +586 -54
  68. package/src/server-error.ts +47 -0
  69. package/src/utils.ts +31 -0
@@ -1138,16 +1138,41 @@ class MagicString {
1138
1138
 
1139
1139
  // src/plugin/transform-client.ts
1140
1140
  import { parse } from "yuku-parser";
1141
- var bunTranspiler = new Bun.Transpiler({
1142
- loader: "tsx",
1143
- tsconfig: {
1144
- compilerOptions: {
1145
- jsx: "react",
1146
- jsxFactory: "React.createElement",
1147
- jsxFragmentFactory: "React.Fragment"
1148
- }
1141
+
1142
+ // src/lang-detect.ts
1143
+ function detectLangFromPath(filePath) {
1144
+ if (filePath.endsWith(".d.ts")) {
1145
+ return "dts";
1146
+ }
1147
+ const ext = filePath.split(".").pop()?.toLowerCase();
1148
+ switch (ext) {
1149
+ case "ts":
1150
+ return "ts";
1151
+ case "tsx":
1152
+ return "tsx";
1153
+ case "jsx":
1154
+ return "jsx";
1155
+ default:
1156
+ return "js";
1149
1157
  }
1150
- });
1158
+ }
1159
+ var TS_WRAPPER_TYPES = new Set([
1160
+ "TSAsExpression",
1161
+ "TSSatisfiesExpression",
1162
+ "TSTypeAssertion",
1163
+ "TSNonNullExpression",
1164
+ "TSInstantiationExpression",
1165
+ "ParenthesizedExpression"
1166
+ ]);
1167
+ function unwrapTSExpression(node) {
1168
+ let current = node;
1169
+ while (current && typeof current === "object" && TS_WRAPPER_TYPES.has(current.type) && current.expression && typeof current.expression === "object") {
1170
+ current = current.expression;
1171
+ }
1172
+ return current;
1173
+ }
1174
+
1175
+ // src/plugin/transform-client.ts
1151
1176
  var SERVER_ONLY_PROPERTIES = new Set(["loader", "query", "params", "staticParams"]);
1152
1177
  function walk(node, visitor) {
1153
1178
  if (!node || typeof node !== "object") {
@@ -1231,6 +1256,45 @@ function removeServerProperties(s, source, obj) {
1231
1256
  }
1232
1257
  return true;
1233
1258
  }
1259
+ var TYPE_SCOPE_NODES = new Set([
1260
+ "TSTypeAnnotation",
1261
+ "TSTypeParameterDeclaration",
1262
+ "TSTypeParameterInstantiation",
1263
+ "TSInterfaceDeclaration",
1264
+ "TSTypeAliasDeclaration",
1265
+ "TSTypePredicate",
1266
+ "TSClassImplements"
1267
+ ]);
1268
+ function markTypeDescendants(node, excluded) {
1269
+ if (!node || typeof node !== "object") {
1270
+ return;
1271
+ }
1272
+ if (Array.isArray(node)) {
1273
+ for (const item of node) {
1274
+ markTypeDescendants(item, excluded);
1275
+ }
1276
+ return;
1277
+ }
1278
+ const n2 = node;
1279
+ if (n2.type === "Identifier" || n2.type === "JSXIdentifier") {
1280
+ excluded.add(n2);
1281
+ }
1282
+ for (const key of Object.keys(n2)) {
1283
+ if (key === "type" || key === "start" || key === "end") {
1284
+ continue;
1285
+ }
1286
+ markTypeDescendants(n2[key], excluded);
1287
+ }
1288
+ }
1289
+ function excludeTypePositionIdentifiers(node, excluded) {
1290
+ if (TYPE_SCOPE_NODES.has(node.type)) {
1291
+ markTypeDescendants(node, excluded);
1292
+ return;
1293
+ }
1294
+ if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSTypeAssertion") {
1295
+ markTypeDescendants(node.typeAnnotation, excluded);
1296
+ }
1297
+ }
1234
1298
  function collectReferencedNames(program) {
1235
1299
  const refs = new Set;
1236
1300
  const excluded = new Set;
@@ -1245,6 +1309,13 @@ function collectReferencedNames(program) {
1245
1309
  if (node.type === "MemberExpression" && !node.computed) {
1246
1310
  excluded.add(node.property);
1247
1311
  }
1312
+ if (node.type === "JSXAttribute") {
1313
+ excluded.add(node.name);
1314
+ }
1315
+ if (node.type === "JSXMemberExpression") {
1316
+ excluded.add(node.property);
1317
+ }
1318
+ excludeTypePositionIdentifiers(node, excluded);
1248
1319
  });
1249
1320
  }
1250
1321
  for (const stmt of program.body ?? []) {
@@ -1255,7 +1326,7 @@ function collectReferencedNames(program) {
1255
1326
  if (excluded.has(node)) {
1256
1327
  return;
1257
1328
  }
1258
- if (node.type === "Identifier" && typeof node.name === "string") {
1329
+ if ((node.type === "Identifier" || node.type === "JSXIdentifier") && typeof node.name === "string") {
1259
1330
  refs.add(node.name);
1260
1331
  }
1261
1332
  });
@@ -1286,9 +1357,9 @@ function removeUnusedSpecifiers(s, code, decl, refs) {
1286
1357
  s.remove(removeStart, removeEnd);
1287
1358
  }
1288
1359
  }
1289
- function deadCodeElimination(s) {
1360
+ function deadCodeElimination(s, lang) {
1290
1361
  const code = s.toString();
1291
- const { program, diagnostics } = parse(code, { sourceType: "module" });
1362
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1292
1363
  const firstError = diagnostics.find((d) => d.severity === "error");
1293
1364
  if (firstError) {
1294
1365
  console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
@@ -1329,7 +1400,7 @@ function removeServerExports(s, source, program) {
1329
1400
  if (!isTargetCall(call)) {
1330
1401
  return;
1331
1402
  }
1332
- const arg = call.arguments[0];
1403
+ const arg = call.arguments[0] ? unwrapTSExpression(call.arguments[0]) : undefined;
1333
1404
  if (!arg || arg.type !== "ObjectExpression") {
1334
1405
  return;
1335
1406
  }
@@ -1340,16 +1411,19 @@ function removeServerExports(s, source, program) {
1340
1411
  return removedServerCode;
1341
1412
  }
1342
1413
  function transformForClient(code, filename) {
1343
- const plainJs = bunTranspiler.transformSync(code);
1344
- const { program, diagnostics } = parse(plainJs, { sourceType: "module" });
1414
+ const lang = detectLangFromPath(filename);
1415
+ if (lang === "dts") {
1416
+ return { code, map: null, removedServerCode: false };
1417
+ }
1418
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
1345
1419
  const firstError = diagnostics.find((d) => d.severity === "error");
1346
1420
  if (firstError) {
1347
1421
  throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
1348
1422
  }
1349
- let s = new MagicString(plainJs);
1350
- const removedServerCode = removeServerExports(s, plainJs, program);
1423
+ let s = new MagicString(code);
1424
+ const removedServerCode = removeServerExports(s, code, program);
1351
1425
  if (removedServerCode) {
1352
- s = deadCodeElimination(s);
1426
+ s = deadCodeElimination(s, lang);
1353
1427
  }
1354
1428
  return {
1355
1429
  code: s.toString(),
@@ -1363,7 +1437,6 @@ var ELYSIA_FILTER = /^elysia$/;
1363
1437
  var BUN_BUILTIN_FILTER = /^bun:/;
1364
1438
  var ANY_FILTER = /.*/;
1365
1439
  var TS_FILE_FILTER = /\.(tsx|ts)$/;
1366
- var REACT_IMPORT_FILTER = /import\s+React\b/;
1367
1440
  var ELYSIA_STUB = `export const t = new Proxy({}, { get: () => (...args) => args[0] ?? {} });
1368
1441
  export class NotFoundError extends Error { constructor(m) { super(m); this.name = "NotFoundError"; } }
1369
1442
  export class ValidationError extends Error { constructor(m) { super(m); this.name = "ValidationError"; } }
@@ -1391,12 +1464,10 @@ var plugin = {
1391
1464
  const source = await Bun.file(args.path).text();
1392
1465
  try {
1393
1466
  const result = transformForClient(source, args.path);
1394
- let code = result.code;
1395
- if (code.includes("React.createElement") && !REACT_IMPORT_FILTER.test(code)) {
1396
- code = `import React from "react";
1397
- ${code}`;
1398
- }
1399
- return { contents: code, loader: "js" };
1467
+ return {
1468
+ contents: result.code,
1469
+ loader: args.path.endsWith(".tsx") ? "tsx" : "ts"
1470
+ };
1400
1471
  } catch (err) {
1401
1472
  console.error(`[furin] strip-plugin transform error for ${args.path}:`, err);
1402
1473
  return;
@@ -1,9 +1,10 @@
1
1
  import MagicString from "magic-string";
2
+ import { type SourceLang } from "yuku-parser";
2
3
  interface TransformResult {
3
4
  code: string;
4
5
  map: ReturnType<MagicString["generateMap"]> | null;
5
6
  removedServerCode: boolean;
6
7
  }
7
- export declare function deadCodeElimination(s: MagicString): MagicString;
8
+ export declare function deadCodeElimination(s: MagicString, lang: SourceLang): MagicString;
8
9
  export declare function transformForClient(code: string, filename: string): TransformResult;
9
10
  export {};
@@ -1,4 +1,36 @@
1
+ import type { toCrossJSON } from "seroval";
1
2
  import type { buildHeadInjection } from "./shell";
3
+ /**
4
+ * Single source of truth for the global registry name used by the SSR
5
+ * streaming script, the client hydration entry, and any test helper. Keeping
6
+ * it centralised here avoids `<script>`/JS source drift if the name is ever
7
+ * renamed.
8
+ */
9
+ export declare const FURIN_DEFERRED_GLOBAL = "__FURIN_DEFERRED__";
10
+ /**
11
+ * Generates the `window.__FURIN_DEFERRED__` registry script that is injected
12
+ * BEFORE the React stream starts. It sets up the resolve/reject/getPromise API
13
+ * for late chunks.
14
+ *
15
+ * Client-side `<Await>` components call `getPromise(key)` to obtain a Promise
16
+ * they can pass to React 19's `use()`. The late resolution scripts call
17
+ * `resolve(key, chunk)` / `reject(key, chunk)` to settle those Promises.
18
+ *
19
+ * Synchronous loader data is NOT carried here — it lives exclusively in the
20
+ * `__FURIN_DATA__` JSON script that the hydrate entry reads.
21
+ *
22
+ * CSP note: this is an inline `<script>` — nonce support is a v2 concern.
23
+ */
24
+ export declare function buildDeferredScript(deferredKeys: string[]): string;
25
+ /**
26
+ * Generates a late `<script>` that settles one deferred Promise on the client.
27
+ * The `chunk` must be a seroval CrossJSON value produced by `toCrossJSON(value)`.
28
+ *
29
+ * @param key - The Promise key (matches what `getPromise(key)` was called with)
30
+ * @param chunk - The already-serialised CrossJSON value
31
+ * @param action - "resolve" or "reject"
32
+ */
33
+ export declare function buildDeferredResolution(key: string, chunk: ReturnType<typeof toCrossJSON>, action: "resolve" | "reject"): string;
2
34
  /** Minimal context passed to background / synthetic render helpers — only `request` is needed. */
3
35
  export interface LoaderContext {
4
36
  request: Request;
@@ -8,6 +8,13 @@ export interface ISRCacheEntry {
8
8
  export interface SsgCacheEntry {
9
9
  cachedAt: number;
10
10
  html: string;
11
+ /**
12
+ * NDJSON payload identical in shape to what the live `/_furin/data` endpoint
13
+ * emits. Persisted alongside the HTML by the static adapter so SPA navigation
14
+ * on a static-hosted deployment can fetch loader data without going through
15
+ * a runtime endpoint that does not exist on a file server.
16
+ */
17
+ ndjson: string;
11
18
  status: number;
12
19
  }
13
20
  export declare const isrCache: Map<string, ISRCacheEntry>;
@@ -5,4 +5,20 @@ import type { FurinNotFoundError, NotFoundComponent } from "../not-found";
5
5
  import type { ResolvedRoute } from "../router";
6
6
  export declare function buildElement(route: ResolvedRoute, data: Record<string, unknown>, rootLayout: RuntimeRoute): ReactNode;
7
7
  export declare function buildNotFoundElement(component: NotFoundComponent | undefined, error: FurinNotFoundError): ReactNode;
8
- export declare function buildErrorElement(component: ErrorComponent | undefined, error: unknown, digest: string): ReactNode;
8
+ /**
9
+ * Builds the error element rendered when a loader (or the SSR shell) fails.
10
+ *
11
+ * @param component - User-declared `error.tsx` component, or `undefined` to
12
+ * fall back to the built-in `DefaultErrorScreen` with a generic message.
13
+ * @param error - The original thrown value. Kept for `errorMessageOf` lookup
14
+ * when no explicit `messageOverride` is provided (e.g. shell-render errors).
15
+ * @param digest - 10-hex-char digest correlating with server logs.
16
+ * @param messageOverride - Pre-extracted public message. Set by the loader
17
+ * pipeline when the thrown value is a `Response` (whose body has already
18
+ * been consumed in `runLoaders`); pass `undefined` to derive the message
19
+ * from `error` via `errorMessageOf`.
20
+ * @param status - HTTP status to surface in `ErrorProps.error.status`. The
21
+ * loader pipeline passes the thrown `Response.status` (default 500); the
22
+ * shell-error recovery path always passes 500.
23
+ */
24
+ export declare function buildErrorElement(component: ErrorComponent | undefined, error: unknown, digest: string, messageOverride: string | undefined, status: number): ReactNode;
@@ -3,12 +3,21 @@ import { type SsgCacheEntry } from "./cache.ts";
3
3
  import { type LoaderResult } from "./loaders.ts";
4
4
  export { type LoaderContext, streamToString } from "./assemble.ts";
5
5
  export { buildElement } from "./element.tsx";
6
- export { type LoaderResult, runLoaders } from "./loaders.ts";
6
+ export { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
7
7
  import type { Context } from "elysia";
8
8
  import type { ResolvedRoute } from "../router.ts";
9
9
  interface RenderResult {
10
10
  headers: Record<string, string>;
11
11
  html: string;
12
+ /**
13
+ * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
14
+ * resolved sync + deferred data. Identical in shape to the body the live
15
+ * `/_furin/data` endpoint emits, so the SPA client can consume both
16
+ * interchangeably. Populated for every render, not just SSG, because the
17
+ * static adapter is the only consumer that persists it today but ISR
18
+ * may want it tomorrow for the same reason.
19
+ */
20
+ ndjson: string;
12
21
  status: number;
13
22
  }
14
23
  export declare function renderToHTML(route: ResolvedRoute, ctx: Context, root: RootLayout): Promise<RenderResult>;