@tanstack/start-server-core 1.20.3-alpha.1

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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -0
  3. package/dist/cjs/createRequestHandler.cjs +50 -0
  4. package/dist/cjs/createRequestHandler.cjs.map +1 -0
  5. package/dist/cjs/createRequestHandler.d.cts +8 -0
  6. package/dist/cjs/createStartHandler.cjs +254 -0
  7. package/dist/cjs/createStartHandler.cjs.map +1 -0
  8. package/dist/cjs/createStartHandler.d.cts +10 -0
  9. package/dist/cjs/h3.cjs +355 -0
  10. package/dist/cjs/h3.cjs.map +1 -0
  11. package/dist/cjs/h3.d.cts +109 -0
  12. package/dist/cjs/handlerCallback.cjs +7 -0
  13. package/dist/cjs/handlerCallback.cjs.map +1 -0
  14. package/dist/cjs/handlerCallback.d.cts +9 -0
  15. package/dist/cjs/index.cjs +245 -0
  16. package/dist/cjs/index.cjs.map +1 -0
  17. package/dist/cjs/index.d.cts +12 -0
  18. package/dist/cjs/router-manifest.cjs +44 -0
  19. package/dist/cjs/router-manifest.cjs.map +1 -0
  20. package/dist/cjs/router-manifest.d.cts +17 -0
  21. package/dist/cjs/server-functions-handler.cjs +154 -0
  22. package/dist/cjs/server-functions-handler.cjs.map +1 -0
  23. package/dist/cjs/server-functions-handler.d.cts +4 -0
  24. package/dist/cjs/serverRoute.cjs +100 -0
  25. package/dist/cjs/serverRoute.cjs.map +1 -0
  26. package/dist/cjs/serverRoute.d.cts +115 -0
  27. package/dist/cjs/ssr-server.cjs +246 -0
  28. package/dist/cjs/ssr-server.cjs.map +1 -0
  29. package/dist/cjs/ssr-server.d.cts +29 -0
  30. package/dist/cjs/transformStreamWithRouter.cjs +183 -0
  31. package/dist/cjs/transformStreamWithRouter.cjs.map +1 -0
  32. package/dist/cjs/transformStreamWithRouter.d.cts +6 -0
  33. package/dist/cjs/tsrScript.cjs +4 -0
  34. package/dist/cjs/tsrScript.cjs.map +1 -0
  35. package/dist/cjs/tsrScript.d.cts +1 -0
  36. package/dist/cjs/undici.cjs +14 -0
  37. package/dist/cjs/undici.cjs.map +1 -0
  38. package/dist/cjs/undici.d.cts +43 -0
  39. package/dist/esm/createRequestHandler.d.ts +8 -0
  40. package/dist/esm/createRequestHandler.js +50 -0
  41. package/dist/esm/createRequestHandler.js.map +1 -0
  42. package/dist/esm/createStartHandler.d.ts +10 -0
  43. package/dist/esm/createStartHandler.js +232 -0
  44. package/dist/esm/createStartHandler.js.map +1 -0
  45. package/dist/esm/h3.d.ts +109 -0
  46. package/dist/esm/h3.js +248 -0
  47. package/dist/esm/h3.js.map +1 -0
  48. package/dist/esm/handlerCallback.d.ts +9 -0
  49. package/dist/esm/handlerCallback.js +7 -0
  50. package/dist/esm/handlerCallback.js.map +1 -0
  51. package/dist/esm/index.d.ts +12 -0
  52. package/dist/esm/index.js +137 -0
  53. package/dist/esm/index.js.map +1 -0
  54. package/dist/esm/router-manifest.d.ts +17 -0
  55. package/dist/esm/router-manifest.js +44 -0
  56. package/dist/esm/router-manifest.js.map +1 -0
  57. package/dist/esm/server-functions-handler.d.ts +4 -0
  58. package/dist/esm/server-functions-handler.js +154 -0
  59. package/dist/esm/server-functions-handler.js.map +1 -0
  60. package/dist/esm/serverRoute.d.ts +115 -0
  61. package/dist/esm/serverRoute.js +100 -0
  62. package/dist/esm/serverRoute.js.map +1 -0
  63. package/dist/esm/ssr-server.d.ts +29 -0
  64. package/dist/esm/ssr-server.js +246 -0
  65. package/dist/esm/ssr-server.js.map +1 -0
  66. package/dist/esm/transformStreamWithRouter.d.ts +6 -0
  67. package/dist/esm/transformStreamWithRouter.js +183 -0
  68. package/dist/esm/transformStreamWithRouter.js.map +1 -0
  69. package/dist/esm/tsrScript.d.ts +1 -0
  70. package/dist/esm/tsrScript.js +5 -0
  71. package/dist/esm/tsrScript.js.map +1 -0
  72. package/dist/esm/undici.d.ts +43 -0
  73. package/dist/esm/undici.js +14 -0
  74. package/dist/esm/undici.js.map +1 -0
  75. package/package.json +68 -0
  76. package/src/createRequestHandler.ts +73 -0
  77. package/src/createStartHandler.ts +348 -0
  78. package/src/h3.ts +492 -0
  79. package/src/handlerCallback.ts +15 -0
  80. package/src/index.tsx +24 -0
  81. package/src/router-manifest.ts +79 -0
  82. package/src/server-functions-handler.ts +273 -0
  83. package/src/serverRoute.ts +661 -0
  84. package/src/ssr-server.ts +350 -0
  85. package/src/tanstack-start.d.ts +5 -0
  86. package/src/transformStreamWithRouter.ts +258 -0
  87. package/src/tsrScript.ts +91 -0
  88. package/src/undici.ts +60 -0
  89. package/src/vite-env.d.ts +4 -0
@@ -0,0 +1,115 @@
1
+ import { Assign, Constrain, Expand, ResolveParams, RouteConstraints, TrimPathRight } from '@tanstack/router-core';
2
+ import { AnyRequestMiddleware, AssignAllServerContext } from '@tanstack/start-client-core';
3
+ type TODO = any;
4
+ export declare function createServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren>(__?: never): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
5
+ export interface ServerRouteOptions<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares> {
6
+ id: TId;
7
+ path: TPath;
8
+ pathname: TFullPath;
9
+ originalIndex: number;
10
+ getParentRoute?: () => TParentRoute;
11
+ middleware: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>;
12
+ methods: Record<string, ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>>;
13
+ caseSensitive?: boolean;
14
+ }
15
+ export type ServerRouteManifest = {
16
+ middleware: boolean;
17
+ methods: Record<string, {
18
+ middleware: boolean;
19
+ }>;
20
+ };
21
+ export declare function createServerRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren>(__?: never, __opts?: Partial<ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>>): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
22
+ export type ServerRouteAddFileChildrenFn<in out TParentRoute extends AnyServerRouteWithTypes, in out TId extends RouteConstraints['TId'], in out TPath extends RouteConstraints['TPath'], in out TFullPath extends RouteConstraints['TFullPath'], in out TMiddlewares, in out TMethods, in out TChildren> = (children: TChildren) => ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren>;
23
+ export type CreateServerFileRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> = (options?: undefined) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
24
+ export type AnyServerRouteWithTypes = ServerRouteWithTypes<any, any, any, any, any, any, any>;
25
+ export interface ServerRouteWithTypes<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods, TChildren> {
26
+ _types: ServerRouteTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods>;
27
+ path: TPath;
28
+ id: TId;
29
+ fullPath: TFullPath;
30
+ to: TrimPathRight<TFullPath>;
31
+ parentRoute: TParentRoute;
32
+ children?: TChildren;
33
+ options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>;
34
+ update: (opts: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>;
35
+ init: (opts: {
36
+ originalIndex: number;
37
+ }) => void;
38
+ _addFileChildren: ServerRouteAddFileChildrenFn<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren>;
39
+ _addFileTypes: () => ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren>;
40
+ }
41
+ export interface ServerRouteTypes<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods> {
42
+ id: TId;
43
+ path: TPath;
44
+ fullPath: TFullPath;
45
+ middlewares: TMiddlewares;
46
+ methods: TMethods;
47
+ parentRoute: TParentRoute;
48
+ allContext: ResolveAllServerContext<TParentRoute, TMiddlewares>;
49
+ }
50
+ export type ResolveAllServerContext<TParentRoute extends AnyServerRouteWithTypes, TMiddlewares> = unknown extends TParentRoute ? AssignAllServerContext<TMiddlewares> : Assign<TParentRoute['_types']['allContext'], AssignAllServerContext<TMiddlewares>>;
51
+ export type AnyServerRoute = AnyServerRouteWithTypes;
52
+ export interface ServerRoute<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> extends ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, undefined, undefined, TChildren>, ServerRouteMiddleware<TParentRoute, TId, TPath, TFullPath, TChildren>, ServerRouteMethods<TParentRoute, TId, TPath, TFullPath, undefined, TChildren> {
53
+ }
54
+ export interface ServerRouteMiddleware<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TChildren> {
55
+ middleware: <const TNewMiddleware>(middleware: Constrain<TNewMiddleware, ReadonlyArray<AnyRequestMiddleware>>) => ServerRouteAfterMiddleware<TParentRoute, TId, TPath, TFullPath, TNewMiddleware, TChildren>;
56
+ }
57
+ export interface ServerRouteAfterMiddleware<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TChildren> extends ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, undefined, TChildren>, ServerRouteMethods<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TChildren> {
58
+ }
59
+ export interface ServerRouteMethods<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TChildren> {
60
+ methods: <const TMethods>(methodsOrGetMethods: Constrain<TMethods, ServerRouteMethodsOptions<TParentRoute, TFullPath, TMiddlewares>>) => ServerRouteAfterMethods<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren>;
61
+ }
62
+ export type ServerRouteMethodsOptions<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> = ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares> | ((api: ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares>) => ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>);
63
+ export interface ServerRouteMethodsRecord<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> {
64
+ GET?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
65
+ POST?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
66
+ PUT?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
67
+ PATCH?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
68
+ DELETE?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
69
+ OPTIONS?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
70
+ HEAD?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>;
71
+ }
72
+ export type ServerRouteMethodRecordValue<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> = ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, undefined, any> | AnyRouteMethodsBuilder;
73
+ export type ServerRouteVerb = (typeof ServerRouteVerbs)[number];
74
+ export declare const ServerRouteVerbs: readonly ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"];
75
+ export type ServerRouteMethodHandlerFn<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> = (ctx: ServerRouteMethodHandlerCtx<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares>) => TResponse | Promise<TResponse>;
76
+ export interface ServerRouteMethodHandlerCtx<in out TParentRoute extends AnyServerRouteWithTypes, in out TFullPath extends string, in out TMiddlewares, in out TMethodMiddlewares> {
77
+ context: Expand<AssignAllMethodContext<TParentRoute, TMiddlewares, TMethodMiddlewares>>;
78
+ request: Request;
79
+ params: ResolveParams<TFullPath>;
80
+ pathname: TFullPath;
81
+ }
82
+ export type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> = TMiddlewares extends ReadonlyArray<any> ? TMethodMiddlewares extends ReadonlyArray<any> ? readonly [...TMiddlewares, ...TMethodMiddlewares] : TMiddlewares : TMethodMiddlewares;
83
+ export type AssignAllMethodContext<TParentRoute extends AnyServerRouteWithTypes, TMiddlewares, TMethodMiddlewares> = ResolveAllServerContext<TParentRoute, MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>>;
84
+ export type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<any, any, any, any>;
85
+ export interface ServerRouteMethodBuilder<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, undefined, undefined>, ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, undefined> {
86
+ }
87
+ export interface ServerRouteMethodBuilderWithTypes<TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> {
88
+ _options: TODO;
89
+ _types: ServerRouteMethodBuilderTypes<TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
90
+ }
91
+ export interface ServerRouteMethodBuilderTypes<in out TFullPath extends string, in out TMiddlewares, in out TMethodMiddlewares, in out TResponse> {
92
+ middlewares: TMiddlewares;
93
+ methodMiddleware: TMethodMiddlewares;
94
+ fullPath: TFullPath;
95
+ response: TResponse;
96
+ }
97
+ export interface ServerRouteMethodBuilderMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares> {
98
+ middleware: <const TNewMethodMiddlewares>(middleware: Constrain<TNewMethodMiddlewares, ReadonlyArray<AnyRequestMiddleware>>) => ServerRouteMethodBuilderAfterMiddleware<TParentRoute, TFullPath, TMiddlewares, TNewMethodMiddlewares>;
99
+ }
100
+ export interface ServerRouteMethodBuilderAfterMiddleware<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, TMethodMiddlewares, undefined>, ServerRouteMethodBuilderHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares> {
101
+ }
102
+ export interface ServerRouteMethodBuilderHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> {
103
+ handler: <TResponse>(handler: ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>) => ServerRouteMethodBuilderAfterHandler<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, TResponse>;
104
+ }
105
+ export interface ServerRouteMethodBuilderAfterHandler<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares, TResponse> extends ServerRouteMethodBuilderWithTypes<TFullPath, TMiddlewares, TMethodMiddlewares, TResponse> {
106
+ opts: ServerRouteMethod<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares>;
107
+ }
108
+ export interface ServerRouteMethod<TParentRoute extends AnyServerRouteWithTypes, TFullPath extends string, TMiddlewares, TMethodMiddlewares> {
109
+ middleware?: Constrain<TMiddlewares, Array<AnyRequestMiddleware>>;
110
+ handler?: ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, TMethodMiddlewares, undefined>;
111
+ }
112
+ export interface ServerRouteAfterMethods<TParentRoute extends AnyServerRouteWithTypes, TId extends RouteConstraints['TId'], TPath extends RouteConstraints['TPath'], TFullPath extends RouteConstraints['TFullPath'], TMiddlewares, TMethods, TChildren> extends ServerRouteWithTypes<TParentRoute, TId, TPath, TFullPath, TMiddlewares, TMethods, TChildren> {
113
+ options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>;
114
+ }
115
+ export {};
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const warning = require("tiny-warning");
4
+ const routerCore = require("@tanstack/router-core");
5
+ const jsesc = require("jsesc");
6
+ const startClientCore = require("@tanstack/start-client-core");
7
+ const tsrScript = require("./tsrScript.cjs");
8
+ function attachRouterServerSsrUtils(router, manifest) {
9
+ router.ssr = {
10
+ manifest,
11
+ serializer: startClientCore.startSerializer
12
+ };
13
+ router.serverSsr = {
14
+ injectedHtml: [],
15
+ streamedKeys: /* @__PURE__ */ new Set(),
16
+ injectHtml: (getHtml) => {
17
+ const promise = Promise.resolve().then(getHtml);
18
+ router.serverSsr.injectedHtml.push(promise);
19
+ router.emit({
20
+ type: "onInjectedHtml",
21
+ promise
22
+ });
23
+ return promise.then(() => {
24
+ });
25
+ },
26
+ injectScript: (getScript, opts) => {
27
+ return router.serverSsr.injectHtml(async () => {
28
+ const script = await getScript();
29
+ return `<script class='tsr-once'>${script}${process.env.NODE_ENV === "development" && ((opts == null ? void 0 : opts.logScript) ?? true) ? `; console.info(\`Injected From Server:
30
+ ${jsesc(script, { quotes: "backtick" })}\`)` : ""}; if (typeof __TSR_SSR__ !== 'undefined') __TSR_SSR__.cleanScripts()<\/script>`;
31
+ });
32
+ },
33
+ streamValue: (key, value) => {
34
+ warning(
35
+ !router.serverSsr.streamedKeys.has(key),
36
+ "Key has already been streamed: " + key
37
+ );
38
+ router.serverSsr.streamedKeys.add(key);
39
+ router.serverSsr.injectScript(
40
+ () => `__TSR_SSR__.streamedValues['${key}'] = { value: ${jsesc(
41
+ router.ssr.serializer.stringify(value),
42
+ {
43
+ isScriptContext: true,
44
+ wrap: true,
45
+ json: true
46
+ }
47
+ )}}`
48
+ );
49
+ },
50
+ onMatchSettled
51
+ };
52
+ router.serverSsr.injectScript(() => tsrScript, {
53
+ logScript: false
54
+ });
55
+ }
56
+ function dehydrateRouter(router) {
57
+ var _a, _b;
58
+ const dehydratedRouter = {
59
+ manifest: router.ssr.manifest,
60
+ dehydratedData: (_b = (_a = router.options).dehydrate) == null ? void 0 : _b.call(_a)
61
+ };
62
+ router.serverSsr.injectScript(
63
+ () => `__TSR_SSR__.dehydrated = ${jsesc(
64
+ router.ssr.serializer.stringify(dehydratedRouter),
65
+ {
66
+ isScriptContext: true,
67
+ wrap: true,
68
+ json: true
69
+ }
70
+ )}`
71
+ );
72
+ }
73
+ function extractAsyncLoaderData(loaderData, ctx) {
74
+ const extracted = [];
75
+ const replaced = replaceBy(loaderData, (value, path) => {
76
+ if (value instanceof ReadableStream) {
77
+ const [copy1, copy2] = value.tee();
78
+ const entry = {
79
+ type: "stream",
80
+ path,
81
+ id: extracted.length,
82
+ matchIndex: ctx.match.index,
83
+ stream: copy2
84
+ };
85
+ extracted.push(entry);
86
+ return copy1;
87
+ } else if (value instanceof Promise) {
88
+ const deferredPromise = routerCore.defer(value);
89
+ const entry = {
90
+ type: "promise",
91
+ path,
92
+ id: extracted.length,
93
+ matchIndex: ctx.match.index,
94
+ promise: deferredPromise
95
+ };
96
+ extracted.push(entry);
97
+ }
98
+ return value;
99
+ });
100
+ return { replaced, extracted };
101
+ }
102
+ function onMatchSettled(opts) {
103
+ const { router, match } = opts;
104
+ let extracted = void 0;
105
+ let serializedLoaderData = void 0;
106
+ if (match.loaderData !== void 0) {
107
+ const result = extractAsyncLoaderData(match.loaderData, {
108
+ match
109
+ });
110
+ match.loaderData = result.replaced;
111
+ extracted = result.extracted;
112
+ serializedLoaderData = extracted.reduce(
113
+ (acc, entry) => {
114
+ return deepImmutableSetByPath(acc, ["temp", ...entry.path], void 0);
115
+ },
116
+ { temp: result.replaced }
117
+ ).temp;
118
+ }
119
+ const initCode = `__TSR_SSR__.initMatch(${jsesc(
120
+ {
121
+ id: match.id,
122
+ __beforeLoadContext: router.ssr.serializer.stringify(
123
+ match.__beforeLoadContext
124
+ ),
125
+ loaderData: router.ssr.serializer.stringify(serializedLoaderData),
126
+ error: router.ssr.serializer.stringify(match.error),
127
+ extracted: extracted == null ? void 0 : extracted.map((entry) => routerCore.pick(entry, ["type", "path"])),
128
+ updatedAt: match.updatedAt,
129
+ status: match.status
130
+ },
131
+ {
132
+ isScriptContext: true,
133
+ wrap: true,
134
+ json: true
135
+ }
136
+ )})`;
137
+ router.serverSsr.injectScript(() => initCode);
138
+ if (extracted) {
139
+ extracted.forEach((entry) => {
140
+ if (entry.type === "promise") return injectPromise(entry);
141
+ return injectStream(entry);
142
+ });
143
+ }
144
+ function injectPromise(entry) {
145
+ router.serverSsr.injectScript(async () => {
146
+ await entry.promise;
147
+ return `__TSR_SSR__.resolvePromise(${jsesc(
148
+ {
149
+ matchId: match.id,
150
+ id: entry.id,
151
+ promiseState: entry.promise[routerCore.TSR_DEFERRED_PROMISE]
152
+ },
153
+ {
154
+ isScriptContext: true,
155
+ wrap: true,
156
+ json: true
157
+ }
158
+ )})`;
159
+ });
160
+ }
161
+ function injectStream(entry) {
162
+ router.serverSsr.injectHtml(async () => {
163
+ try {
164
+ const reader = entry.stream.getReader();
165
+ let chunk = null;
166
+ while (!(chunk = await reader.read()).done) {
167
+ if (chunk.value) {
168
+ const code = `__TSR_SSR__.injectChunk(${jsesc(
169
+ {
170
+ matchId: match.id,
171
+ id: entry.id,
172
+ chunk: chunk.value
173
+ },
174
+ {
175
+ isScriptContext: true,
176
+ wrap: true,
177
+ json: true
178
+ }
179
+ )})`;
180
+ router.serverSsr.injectScript(() => code);
181
+ }
182
+ }
183
+ router.serverSsr.injectScript(
184
+ () => `__TSR_SSR__.closeStream(${jsesc(
185
+ {
186
+ matchId: match.id,
187
+ id: entry.id
188
+ },
189
+ {
190
+ isScriptContext: true,
191
+ wrap: true,
192
+ json: true
193
+ }
194
+ )})`
195
+ );
196
+ } catch (err) {
197
+ console.error("stream read error", err);
198
+ }
199
+ return "";
200
+ });
201
+ }
202
+ }
203
+ function deepImmutableSetByPath(obj, path, value) {
204
+ if (path.length === 0) {
205
+ return value;
206
+ }
207
+ const [key, ...rest] = path;
208
+ if (Array.isArray(obj)) {
209
+ return obj.map((item, i) => {
210
+ if (i === Number(key)) {
211
+ return deepImmutableSetByPath(item, rest, value);
212
+ }
213
+ return item;
214
+ });
215
+ }
216
+ if (routerCore.isPlainObject(obj)) {
217
+ return {
218
+ ...obj,
219
+ [key]: deepImmutableSetByPath(obj[key], rest, value)
220
+ };
221
+ }
222
+ return obj;
223
+ }
224
+ function replaceBy(obj, cb, path = []) {
225
+ if (routerCore.isPlainArray(obj)) {
226
+ return obj.map((value, i) => replaceBy(value, cb, [...path, `${i}`]));
227
+ }
228
+ if (routerCore.isPlainObject(obj)) {
229
+ const newObj2 = {};
230
+ for (const key in obj) {
231
+ newObj2[key] = replaceBy(obj[key], cb, [...path, key]);
232
+ }
233
+ return newObj2;
234
+ }
235
+ const newObj = cb(obj, path);
236
+ if (newObj !== obj) {
237
+ return newObj;
238
+ }
239
+ return obj;
240
+ }
241
+ exports.attachRouterServerSsrUtils = attachRouterServerSsrUtils;
242
+ exports.dehydrateRouter = dehydrateRouter;
243
+ exports.extractAsyncLoaderData = extractAsyncLoaderData;
244
+ exports.onMatchSettled = onMatchSettled;
245
+ exports.replaceBy = replaceBy;
246
+ //# sourceMappingURL=ssr-server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr-server.cjs","sources":["../../src/ssr-server.ts"],"sourcesContent":["import { default as warning } from 'tiny-warning'\nimport {\n TSR_DEFERRED_PROMISE,\n defer,\n isPlainArray,\n isPlainObject,\n pick,\n} from '@tanstack/router-core'\nimport jsesc from 'jsesc'\nimport { startSerializer } from '@tanstack/start-client-core'\nimport minifiedTsrBootStrapScript from './tsrScript?script-string'\nimport type {\n ClientExtractedBaseEntry,\n DehydratedRouter,\n ResolvePromiseState,\n SsrMatch,\n} from '@tanstack/start-client-core'\nimport type {\n AnyRouteMatch,\n AnyRouter,\n DeferredPromise,\n Manifest,\n} from '@tanstack/router-core'\n\nexport type ServerExtractedEntry =\n | ServerExtractedStream\n | ServerExtractedPromise\n\nexport interface ServerExtractedBaseEntry extends ClientExtractedBaseEntry {\n id: number\n matchIndex: number\n}\n\nexport interface ServerExtractedStream extends ServerExtractedBaseEntry {\n type: 'stream'\n stream: ReadableStream\n}\n\nexport interface ServerExtractedPromise extends ServerExtractedBaseEntry {\n type: 'promise'\n promise: DeferredPromise<any>\n}\n\nexport function attachRouterServerSsrUtils(\n router: AnyRouter,\n manifest: Manifest | undefined,\n) {\n router.ssr = {\n manifest,\n serializer: startSerializer,\n }\n\n router.serverSsr = {\n injectedHtml: [],\n streamedKeys: new Set(),\n injectHtml: (getHtml) => {\n const promise = Promise.resolve().then(getHtml)\n router.serverSsr!.injectedHtml.push(promise)\n router.emit({\n type: 'onInjectedHtml',\n promise,\n })\n\n return promise.then(() => {})\n },\n injectScript: (getScript, opts) => {\n return router.serverSsr!.injectHtml(async () => {\n const script = await getScript()\n return `<script class='tsr-once'>${script}${\n process.env.NODE_ENV === 'development' && (opts?.logScript ?? true)\n ? `; console.info(\\`Injected From Server:\n${jsesc(script, { quotes: 'backtick' })}\\`)`\n : ''\n }; if (typeof __TSR_SSR__ !== 'undefined') __TSR_SSR__.cleanScripts()</script>`\n })\n },\n streamValue: (key, value) => {\n warning(\n !router.serverSsr!.streamedKeys.has(key),\n 'Key has already been streamed: ' + key,\n )\n\n router.serverSsr!.streamedKeys.add(key)\n router.serverSsr!.injectScript(\n () =>\n `__TSR_SSR__.streamedValues['${key}'] = { value: ${jsesc(\n router.ssr!.serializer.stringify(value),\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )}}`,\n )\n },\n onMatchSettled,\n }\n\n router.serverSsr.injectScript(() => minifiedTsrBootStrapScript, {\n logScript: false,\n })\n}\n\nexport function dehydrateRouter(router: AnyRouter) {\n const dehydratedRouter: DehydratedRouter = {\n manifest: router.ssr!.manifest,\n dehydratedData: router.options.dehydrate?.(),\n }\n\n router.serverSsr!.injectScript(\n () =>\n `__TSR_SSR__.dehydrated = ${jsesc(\n router.ssr!.serializer.stringify(dehydratedRouter),\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )}`,\n )\n}\n\nexport function extractAsyncLoaderData(\n loaderData: any,\n ctx: {\n match: AnyRouteMatch\n router: AnyRouter\n },\n) {\n const extracted: Array<ServerExtractedEntry> = []\n\n const replaced = replaceBy(loaderData, (value, path) => {\n // If it's a stream, we need to tee it so we can read it multiple times\n if (value instanceof ReadableStream) {\n const [copy1, copy2] = value.tee()\n const entry: ServerExtractedStream = {\n type: 'stream',\n path,\n id: extracted.length,\n matchIndex: ctx.match.index,\n stream: copy2,\n }\n\n extracted.push(entry)\n return copy1\n } else if (value instanceof Promise) {\n const deferredPromise = defer(value)\n const entry: ServerExtractedPromise = {\n type: 'promise',\n path,\n id: extracted.length,\n matchIndex: ctx.match.index,\n promise: deferredPromise,\n }\n extracted.push(entry)\n }\n\n return value\n })\n\n return { replaced, extracted }\n}\n\nexport function onMatchSettled(opts: {\n router: AnyRouter\n match: AnyRouteMatch\n}) {\n const { router, match } = opts\n\n let extracted: Array<ServerExtractedEntry> | undefined = undefined\n let serializedLoaderData: any = undefined\n if (match.loaderData !== undefined) {\n const result = extractAsyncLoaderData(match.loaderData, {\n router,\n match,\n })\n match.loaderData = result.replaced\n extracted = result.extracted\n serializedLoaderData = extracted.reduce(\n (acc: any, entry: ServerExtractedEntry) => {\n return deepImmutableSetByPath(acc, ['temp', ...entry.path], undefined)\n },\n { temp: result.replaced },\n ).temp\n }\n\n const initCode = `__TSR_SSR__.initMatch(${jsesc(\n {\n id: match.id,\n __beforeLoadContext: router.ssr!.serializer.stringify(\n match.__beforeLoadContext,\n ),\n loaderData: router.ssr!.serializer.stringify(serializedLoaderData),\n error: router.ssr!.serializer.stringify(match.error),\n extracted: extracted?.map((entry) => pick(entry, ['type', 'path'])),\n updatedAt: match.updatedAt,\n status: match.status,\n } satisfies SsrMatch,\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`\n\n router.serverSsr!.injectScript(() => initCode)\n\n if (extracted) {\n extracted.forEach((entry) => {\n if (entry.type === 'promise') return injectPromise(entry)\n return injectStream(entry)\n })\n }\n\n function injectPromise(entry: ServerExtractedPromise) {\n router.serverSsr!.injectScript(async () => {\n await entry.promise\n\n return `__TSR_SSR__.resolvePromise(${jsesc(\n {\n matchId: match.id,\n id: entry.id,\n promiseState: entry.promise[TSR_DEFERRED_PROMISE],\n } satisfies ResolvePromiseState,\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`\n })\n }\n\n function injectStream(entry: ServerExtractedStream) {\n // Inject a promise that resolves when the stream is done\n // We do this to keep the stream open until we're done\n router.serverSsr!.injectHtml(async () => {\n //\n try {\n const reader = entry.stream.getReader()\n let chunk: ReadableStreamReadResult<any> | null = null\n while (!(chunk = await reader.read()).done) {\n if (chunk.value) {\n const code = `__TSR_SSR__.injectChunk(${jsesc(\n {\n matchId: match.id,\n id: entry.id,\n chunk: chunk.value,\n },\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`\n\n router.serverSsr!.injectScript(() => code)\n }\n }\n\n router.serverSsr!.injectScript(\n () =>\n `__TSR_SSR__.closeStream(${jsesc(\n {\n matchId: match.id,\n id: entry.id,\n },\n {\n isScriptContext: true,\n wrap: true,\n json: true,\n },\n )})`,\n )\n } catch (err) {\n console.error('stream read error', err)\n }\n\n return ''\n })\n }\n}\n\nfunction deepImmutableSetByPath<T>(obj: T, path: Array<string>, value: any): T {\n // immutable set by path retaining array and object references\n if (path.length === 0) {\n return value\n }\n\n const [key, ...rest] = path\n\n if (Array.isArray(obj)) {\n return obj.map((item, i) => {\n if (i === Number(key)) {\n return deepImmutableSetByPath(item, rest, value)\n }\n return item\n }) as T\n }\n\n if (isPlainObject(obj)) {\n return {\n ...obj,\n [key!]: deepImmutableSetByPath((obj as any)[key!], rest, value),\n }\n }\n\n return obj\n}\n\nexport function replaceBy<T>(\n obj: T,\n cb: (value: any, path: Array<string>) => any,\n path: Array<string> = [],\n): T {\n if (isPlainArray(obj)) {\n return obj.map((value, i) => replaceBy(value, cb, [...path, `${i}`])) as any\n }\n\n if (isPlainObject(obj)) {\n // Do not allow objects with illegal\n const newObj: any = {}\n\n for (const key in obj) {\n newObj[key] = replaceBy(obj[key], cb, [...path, key])\n }\n\n return newObj\n }\n\n // // Detect classes, functions, and other non-serializable objects\n // // and return undefined. Exclude some known types that are serializable\n // if (\n // typeof obj === 'function' ||\n // (typeof obj === 'object' &&\n // ![Object, Promise, ReadableStream].includes((obj as any)?.constructor))\n // ) {\n // console.info(obj)\n // warning(false, `Non-serializable value ☝️ found at ${path.join('.')}`)\n // return undefined as any\n // }\n\n const newObj = cb(obj, path)\n\n if (newObj !== obj) {\n return newObj\n }\n\n return obj\n}\n"],"names":["startSerializer","minifiedTsrBootStrapScript","defer","pick","TSR_DEFERRED_PROMISE","isPlainObject","isPlainArray","newObj"],"mappings":";;;;;;;AA2CgB,SAAA,2BACd,QACA,UACA;AACA,SAAO,MAAM;AAAA,IACX;AAAA,IACA,YAAYA,gBAAAA;AAAAA,EACd;AAEA,SAAO,YAAY;AAAA,IACjB,cAAc,CAAC;AAAA,IACf,kCAAkB,IAAI;AAAA,IACtB,YAAY,CAAC,YAAY;AACvB,YAAM,UAAU,QAAQ,QAAQ,EAAE,KAAK,OAAO;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Ac,CAAC;AAErB,eAAW,OAAO,KAAK;AACrBA,cAAO,GAAG,IAAI,UAAU,IAAI,GAAG,GAAG,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC;AAAA,IAAA;AAG/CA,WAAAA;AAAAA,EAAA;AAeH,QAAA,SAAS,GAAG,KAAK,IAAI;AAE3B,MAAI,WAAW,KAAK;AACX,WAAA;AAAA,EAAA;AAGF,SAAA;AACT;;;;;;"}
@@ -0,0 +1,29 @@
1
+ import { ClientExtractedBaseEntry } from '@tanstack/start-client-core';
2
+ import { AnyRouteMatch, AnyRouter, DeferredPromise, Manifest } from '@tanstack/router-core';
3
+ export type ServerExtractedEntry = ServerExtractedStream | ServerExtractedPromise;
4
+ export interface ServerExtractedBaseEntry extends ClientExtractedBaseEntry {
5
+ id: number;
6
+ matchIndex: number;
7
+ }
8
+ export interface ServerExtractedStream extends ServerExtractedBaseEntry {
9
+ type: 'stream';
10
+ stream: ReadableStream;
11
+ }
12
+ export interface ServerExtractedPromise extends ServerExtractedBaseEntry {
13
+ type: 'promise';
14
+ promise: DeferredPromise<any>;
15
+ }
16
+ export declare function attachRouterServerSsrUtils(router: AnyRouter, manifest: Manifest | undefined): void;
17
+ export declare function dehydrateRouter(router: AnyRouter): void;
18
+ export declare function extractAsyncLoaderData(loaderData: any, ctx: {
19
+ match: AnyRouteMatch;
20
+ router: AnyRouter;
21
+ }): {
22
+ replaced: any;
23
+ extracted: ServerExtractedEntry[];
24
+ };
25
+ export declare function onMatchSettled(opts: {
26
+ router: AnyRouter;
27
+ match: AnyRouteMatch;
28
+ }): void;
29
+ export declare function replaceBy<T>(obj: T, cb: (value: any, path: Array<string>) => any, path?: Array<string>): T;
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const web = require("node:stream/web");
4
+ const node_stream = require("node:stream");
5
+ const routerCore = require("@tanstack/router-core");
6
+ function transformReadableStreamWithRouter(router, routerStream) {
7
+ return transformStreamWithRouter(router, routerStream);
8
+ }
9
+ function transformPipeableStreamWithRouter(router, routerStream) {
10
+ return node_stream.Readable.fromWeb(
11
+ transformStreamWithRouter(router, node_stream.Readable.toWeb(routerStream))
12
+ );
13
+ }
14
+ const patternBodyStart = /(<body)/;
15
+ const patternBodyEnd = /(<\/body>)/;
16
+ const patternHtmlEnd = /(<\/html>)/;
17
+ const patternHeadStart = /(<head.*?>)/;
18
+ const patternClosingTag = /(<\/[a-zA-Z][\w:.-]*?>)/g;
19
+ const textDecoder = new TextDecoder();
20
+ function createPassthrough() {
21
+ let controller;
22
+ const encoder = new TextEncoder();
23
+ const stream = new web.ReadableStream({
24
+ start(c) {
25
+ controller = c;
26
+ }
27
+ });
28
+ const res = {
29
+ stream,
30
+ write: (chunk) => {
31
+ controller.enqueue(encoder.encode(chunk));
32
+ },
33
+ end: (chunk) => {
34
+ if (chunk) {
35
+ controller.enqueue(encoder.encode(chunk));
36
+ }
37
+ controller.close();
38
+ res.destroyed = true;
39
+ },
40
+ destroy: (error) => {
41
+ controller.error(error);
42
+ },
43
+ destroyed: false
44
+ };
45
+ return res;
46
+ }
47
+ async function readStream(stream, opts) {
48
+ var _a, _b, _c;
49
+ try {
50
+ const reader = stream.getReader();
51
+ let chunk;
52
+ while (!(chunk = await reader.read()).done) {
53
+ (_a = opts.onData) == null ? void 0 : _a.call(opts, chunk);
54
+ }
55
+ (_b = opts.onEnd) == null ? void 0 : _b.call(opts);
56
+ } catch (error) {
57
+ (_c = opts.onError) == null ? void 0 : _c.call(opts, error);
58
+ }
59
+ }
60
+ function transformStreamWithRouter(router, appStream) {
61
+ const finalPassThrough = createPassthrough();
62
+ let isAppRendering = true;
63
+ let routerStreamBuffer = "";
64
+ let pendingClosingTags = "";
65
+ let bodyStarted = false;
66
+ let headStarted = false;
67
+ let leftover = "";
68
+ let leftoverHtml = "";
69
+ function getBufferedRouterStream() {
70
+ const html = routerStreamBuffer;
71
+ routerStreamBuffer = "";
72
+ return html;
73
+ }
74
+ function decodeChunk(chunk) {
75
+ if (chunk instanceof Uint8Array) {
76
+ return textDecoder.decode(chunk);
77
+ }
78
+ return String(chunk);
79
+ }
80
+ const injectedHtmlDonePromise = routerCore.createControlledPromise();
81
+ let processingCount = 0;
82
+ router.serverSsr.injectedHtml.forEach((promise) => {
83
+ handleInjectedHtml(promise);
84
+ });
85
+ const stopListeningToInjectedHtml = router.subscribe(
86
+ "onInjectedHtml",
87
+ (e) => {
88
+ handleInjectedHtml(e.promise);
89
+ }
90
+ );
91
+ function handleInjectedHtml(promise) {
92
+ processingCount++;
93
+ promise.then((html) => {
94
+ if (!bodyStarted) {
95
+ routerStreamBuffer += html;
96
+ } else {
97
+ finalPassThrough.write(html);
98
+ }
99
+ }).catch(injectedHtmlDonePromise.reject).finally(() => {
100
+ processingCount--;
101
+ if (!isAppRendering && processingCount === 0) {
102
+ stopListeningToInjectedHtml();
103
+ injectedHtmlDonePromise.resolve();
104
+ }
105
+ });
106
+ }
107
+ injectedHtmlDonePromise.then(() => {
108
+ const finalHtml = leftoverHtml + getBufferedRouterStream() + pendingClosingTags;
109
+ finalPassThrough.end(finalHtml);
110
+ }).catch((err) => {
111
+ console.error("Error reading routerStream:", err);
112
+ finalPassThrough.destroy(err);
113
+ });
114
+ readStream(appStream, {
115
+ onData: (chunk) => {
116
+ const text = decodeChunk(chunk.value);
117
+ let chunkString = leftover + text;
118
+ const bodyEndMatch = chunkString.match(patternBodyEnd);
119
+ const htmlEndMatch = chunkString.match(patternHtmlEnd);
120
+ if (!bodyStarted) {
121
+ const bodyStartMatch = chunkString.match(patternBodyStart);
122
+ if (bodyStartMatch) {
123
+ bodyStarted = true;
124
+ }
125
+ }
126
+ if (!headStarted) {
127
+ const headStartMatch = chunkString.match(patternHeadStart);
128
+ if (headStartMatch) {
129
+ headStarted = true;
130
+ const index = headStartMatch.index;
131
+ const headTag = headStartMatch[0];
132
+ const remaining = chunkString.slice(index + headTag.length);
133
+ finalPassThrough.write(
134
+ chunkString.slice(0, index) + headTag + getBufferedRouterStream()
135
+ );
136
+ chunkString = remaining;
137
+ }
138
+ }
139
+ if (!bodyStarted) {
140
+ finalPassThrough.write(chunkString);
141
+ leftover = "";
142
+ return;
143
+ }
144
+ if (bodyEndMatch && htmlEndMatch && bodyEndMatch.index < htmlEndMatch.index) {
145
+ const bodyEndIndex = bodyEndMatch.index;
146
+ pendingClosingTags = chunkString.slice(bodyEndIndex);
147
+ finalPassThrough.write(
148
+ chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream()
149
+ );
150
+ leftover = "";
151
+ return;
152
+ }
153
+ let result;
154
+ let lastIndex = 0;
155
+ while ((result = patternClosingTag.exec(chunkString)) !== null) {
156
+ lastIndex = result.index + result[0].length;
157
+ }
158
+ if (lastIndex > 0) {
159
+ const processed = chunkString.slice(0, lastIndex) + getBufferedRouterStream() + leftoverHtml;
160
+ finalPassThrough.write(processed);
161
+ leftover = chunkString.slice(lastIndex);
162
+ } else {
163
+ leftover = chunkString;
164
+ leftoverHtml += getBufferedRouterStream();
165
+ }
166
+ },
167
+ onEnd: () => {
168
+ isAppRendering = false;
169
+ if (processingCount === 0) {
170
+ injectedHtmlDonePromise.resolve();
171
+ }
172
+ },
173
+ onError: (error) => {
174
+ console.error("Error reading appStream:", error);
175
+ finalPassThrough.destroy(error);
176
+ }
177
+ });
178
+ return finalPassThrough.stream;
179
+ }
180
+ exports.transformPipeableStreamWithRouter = transformPipeableStreamWithRouter;
181
+ exports.transformReadableStreamWithRouter = transformReadableStreamWithRouter;
182
+ exports.transformStreamWithRouter = transformStreamWithRouter;
183
+ //# sourceMappingURL=transformStreamWithRouter.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transformStreamWithRouter.cjs","sources":["../../src/transformStreamWithRouter.ts"],"sourcesContent":["import { ReadableStream } from 'node:stream/web'\nimport { Readable } from 'node:stream'\nimport { createControlledPromise } from '@tanstack/router-core'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nexport function transformReadableStreamWithRouter(\n router: AnyRouter,\n routerStream: ReadableStream,\n) {\n return transformStreamWithRouter(router, routerStream)\n}\n\nexport function transformPipeableStreamWithRouter(\n router: AnyRouter,\n routerStream: Readable,\n) {\n return Readable.fromWeb(\n transformStreamWithRouter(router, Readable.toWeb(routerStream)),\n )\n}\n\n// regex pattern for matching closing body and html tags\nconst patternBodyStart = /(<body)/\nconst patternBodyEnd = /(<\\/body>)/\nconst patternHtmlEnd = /(<\\/html>)/\nconst patternHeadStart = /(<head.*?>)/\n// regex pattern for matching closing tags\nconst patternClosingTag = /(<\\/[a-zA-Z][\\w:.-]*?>)/g\n\nconst textDecoder = new TextDecoder()\n\ntype ReadablePassthrough = {\n stream: ReadableStream\n write: (chunk: string) => void\n end: (chunk?: string) => void\n destroy: (error: unknown) => void\n destroyed: boolean\n}\n\nfunction createPassthrough() {\n let controller: ReadableStreamDefaultController<any>\n const encoder = new TextEncoder()\n const stream = new ReadableStream({\n start(c) {\n controller = c\n },\n })\n\n const res: ReadablePassthrough = {\n stream,\n write: (chunk) => {\n controller.enqueue(encoder.encode(chunk))\n },\n end: (chunk) => {\n if (chunk) {\n controller.enqueue(encoder.encode(chunk))\n }\n controller.close()\n res.destroyed = true\n },\n destroy: (error) => {\n controller.error(error)\n },\n destroyed: false,\n }\n\n return res\n}\n\nasync function readStream(\n stream: ReadableStream,\n opts: {\n onData?: (chunk: ReadableStreamReadValueResult<any>) => void\n onEnd?: () => void\n onError?: (error: unknown) => void\n },\n) {\n try {\n const reader = stream.getReader()\n let chunk\n while (!(chunk = await reader.read()).done) {\n opts.onData?.(chunk)\n }\n opts.onEnd?.()\n } catch (error) {\n opts.onError?.(error)\n }\n}\n\nexport function transformStreamWithRouter(\n router: AnyRouter,\n appStream: ReadableStream,\n) {\n const finalPassThrough = createPassthrough()\n\n let isAppRendering = true as boolean\n let routerStreamBuffer = ''\n let pendingClosingTags = ''\n let bodyStarted = false as boolean\n let headStarted = false as boolean\n let leftover = ''\n let leftoverHtml = ''\n\n function getBufferedRouterStream() {\n const html = routerStreamBuffer\n routerStreamBuffer = ''\n return html\n }\n\n function decodeChunk(chunk: unknown): string {\n if (chunk instanceof Uint8Array) {\n return textDecoder.decode(chunk)\n }\n return String(chunk)\n }\n\n const injectedHtmlDonePromise = createControlledPromise<void>()\n\n let processingCount = 0\n\n // Process any already-injected HTML\n router.serverSsr!.injectedHtml.forEach((promise) => {\n handleInjectedHtml(promise)\n })\n\n // Listen for any new injected HTML\n const stopListeningToInjectedHtml = router.subscribe(\n 'onInjectedHtml',\n (e) => {\n handleInjectedHtml(e.promise)\n },\n )\n\n function handleInjectedHtml(promise: Promise<string>) {\n processingCount++\n\n promise\n .then((html) => {\n if (!bodyStarted) {\n routerStreamBuffer += html\n } else {\n finalPassThrough.write(html)\n }\n })\n .catch(injectedHtmlDonePromise.reject)\n .finally(() => {\n processingCount--\n\n if (!isAppRendering && processingCount === 0) {\n stopListeningToInjectedHtml()\n injectedHtmlDonePromise.resolve()\n }\n })\n }\n\n injectedHtmlDonePromise\n .then(() => {\n const finalHtml =\n leftoverHtml + getBufferedRouterStream() + pendingClosingTags\n\n finalPassThrough.end(finalHtml)\n })\n .catch((err) => {\n console.error('Error reading routerStream:', err)\n finalPassThrough.destroy(err)\n })\n\n // Transform the appStream\n readStream(appStream, {\n onData: (chunk) => {\n const text = decodeChunk(chunk.value)\n\n let chunkString = leftover + text\n const bodyEndMatch = chunkString.match(patternBodyEnd)\n const htmlEndMatch = chunkString.match(patternHtmlEnd)\n\n if (!bodyStarted) {\n const bodyStartMatch = chunkString.match(patternBodyStart)\n if (bodyStartMatch) {\n bodyStarted = true\n }\n }\n\n if (!headStarted) {\n const headStartMatch = chunkString.match(patternHeadStart)\n if (headStartMatch) {\n headStarted = true\n const index = headStartMatch.index!\n const headTag = headStartMatch[0]\n const remaining = chunkString.slice(index + headTag.length)\n finalPassThrough.write(\n chunkString.slice(0, index) + headTag + getBufferedRouterStream(),\n )\n // make sure to only write `remaining` until the next closing tag\n chunkString = remaining\n }\n }\n\n if (!bodyStarted) {\n finalPassThrough.write(chunkString)\n leftover = ''\n return\n }\n\n // If either the body end or html end is in the chunk,\n // We need to get all of our data in asap\n if (\n bodyEndMatch &&\n htmlEndMatch &&\n bodyEndMatch.index! < htmlEndMatch.index!\n ) {\n const bodyEndIndex = bodyEndMatch.index!\n pendingClosingTags = chunkString.slice(bodyEndIndex)\n\n finalPassThrough.write(\n chunkString.slice(0, bodyEndIndex) + getBufferedRouterStream(),\n )\n\n leftover = ''\n return\n }\n\n let result: RegExpExecArray | null\n let lastIndex = 0\n while ((result = patternClosingTag.exec(chunkString)) !== null) {\n lastIndex = result.index + result[0].length\n }\n\n if (lastIndex > 0) {\n const processed =\n chunkString.slice(0, lastIndex) +\n getBufferedRouterStream() +\n leftoverHtml\n\n finalPassThrough.write(processed)\n leftover = chunkString.slice(lastIndex)\n } else {\n leftover = chunkString\n leftoverHtml += getBufferedRouterStream()\n }\n },\n onEnd: () => {\n // Mark the app as done rendering\n isAppRendering = false\n\n // If there are no pending promises, resolve the injectedHtmlDonePromise\n if (processingCount === 0) {\n injectedHtmlDonePromise.resolve()\n }\n },\n onError: (error) => {\n console.error('Error reading appStream:', error)\n finalPassThrough.destroy(error)\n },\n })\n\n return finalPassThrough.stream\n}\n"],"names":["Readable","ReadableStream","createControlledPromise"],"mappings":";;;;;AAKgB,SAAA,kCACd,QACA,cACA;AACO,SAAA,0BAA0B,QAAQ,YAAY;AACvD;AAEgB,SAAA,kCACd,QACA,cACA;AACA,SAAOA,YAAS,SAAA;AAAA,IACd,0BAA0B,QAAQA,qBAAS,MAAM,YAAY,CAAC;AAAA,EAChE;AACF;AAGA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AAEzB,MAAM,oBAAoB;AAE1B,MAAM,cAAc,IAAI,YAAY;AAUpC,SAAS,oBAAoB;AACvB,MAAA;AACE,QAAA,UAAU,IAAI,YAAY;AAC1B,QAAA,SAAS,IAAIC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AAG,KAAK,IAAI,UAAU,wBAAwB;AAAA,UAClE;AAEc,wBAAA;AAAA,QAAA;AAAA,MAChB;AAGF,UAAI,CAAC,aAAa;AAChB,yBAAiB,MAAM,WAAW;AACvB,mBAAA;AACX;AAAA,MAAA;AAKF,UACE,gBACA,gBACA,aAAa,QAAS,aAAa,OACnC;AACA,cAAM,eAAe,aAAa;AACb,6BAAA,YAAY,MAAM,YAAY;AAElC,yBAAA;AAAA,UACf,YAAY,MAAM,GAAG,YAAY,IAAI,wBAAwB;AAAA,QAC/D;AAEW,mBAAA;AACX;AAAA,MAAA;AAGE,UAAA;AACJ,UAAI,YAAY;AAChB,cAAQ,SAAS,kBAAkB,KAAK,WAAW,OAAO,MAAM;AAC9D,oBAAY,OAAO,QAAQ,OAAO,CAAC,EAAE;AAAA,MAAA;AAGvC,UAAI,YAAY,GAAG;AACjB,cAAM,YACJ,YAAY,MAAM,GAAG,SAAS,IAC9B,4BACA;AAEF,yBAAiB,MAAM,SAAS;AACrB,mBAAA,YAAY,MAAM,SAAS;AAAA,MAAA,OACjC;AACM,mBAAA;AACX,wBAAgB,wBAAwB;AAAA,MAAA;AAAA,IAE5C;AAAA,IACA,OAAO,MAAM;AAEM,uBAAA;AAGjB,UAAI,oBAAoB,GAAG;AACzB,gCAAwB,QAAQ;AAAA,MAAA;AAAA,IAEpC;AAAA,IACA,SAAS,CAAC,UAAU;AACV,cAAA,MAAM,4BAA4B,KAAK;AAC/C,uBAAiB,QAAQ,KAAK;AAAA,IAAA;AAAA,EAChC,CACD;AAED,SAAO,iBAAiB;AAC1B;;;;"}
@@ -0,0 +1,6 @@
1
+ import { ReadableStream } from 'node:stream/web';
2
+ import { Readable } from 'node:stream';
3
+ import { AnyRouter } from '@tanstack/router-core';
4
+ export declare function transformReadableStreamWithRouter(router: AnyRouter, routerStream: ReadableStream): ReadableStream<any>;
5
+ export declare function transformPipeableStreamWithRouter(router: AnyRouter, routerStream: Readable): Readable;
6
+ export declare function transformStreamWithRouter(router: AnyRouter, appStream: ReadableStream): ReadableStream<any>;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ const minifiedTsrBootStrapScript = 'const __TSR_SSR__={matches:[],streamedValues:{},initMatch:o=>(__TSR_SSR__.matches.push(o),o.extracted?.forEach(l=>{if(l.type==="stream"){let r;l.value=new ReadableStream({start(e){r={enqueue:t=>{try{e.enqueue(t)}catch{}},close:()=>{try{e.close()}catch{}}}}}),l.value.controller=r}else{let r,e;l.value=new Promise((t,a)=>{e=a,r=t}),l.value.reject=e,l.value.resolve=r}}),!0),resolvePromise:({matchId:o,id:l,promiseState:r})=>{const e=__TSR_SSR__.matches.find(t=>t.id===o);if(e){const t=e.extracted?.[l];if(t&&t.type==="promise"&&t.value&&r.status==="success")return t.value.resolve(r.data),!0}return!1},injectChunk:({matchId:o,id:l,chunk:r})=>{const e=__TSR_SSR__.matches.find(t=>t.id===o);if(e){const t=e.extracted?.[l];if(t&&t.type==="stream"&&t.value?.controller)return t.value.controller.enqueue(new TextEncoder().encode(r.toString())),!0}return!1},closeStream:({matchId:o,id:l})=>{const r=__TSR_SSR__.matches.find(e=>e.id===o);if(r){const e=r.extracted?.[l];if(e&&e.type==="stream"&&e.value?.controller)return e.value.controller.close(),!0}return!1},cleanScripts:()=>{document.querySelectorAll(".tsr-once").forEach(o=>{o.remove()})}};window.__TSR_SSR__=__TSR_SSR__;\n';
3
+ module.exports = minifiedTsrBootStrapScript;
4
+ //# sourceMappingURL=tsrScript.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tsrScript.cjs","sources":["../../src/tsrScript.ts?script-string"],"sourcesContent":["import type { ControllablePromise } from '@tanstack/router-core'\nimport type { StartSsrGlobal } from '@tanstack/start-client-core'\n\nconst __TSR_SSR__: StartSsrGlobal = {\n matches: [],\n streamedValues: {},\n initMatch: (match) => {\n __TSR_SSR__.matches.push(match)\n\n match.extracted?.forEach((ex) => {\n if (ex.type === 'stream') {\n let controller\n ex.value = new ReadableStream({\n start(c) {\n controller = {\n enqueue: (chunk: unknown) => {\n try {\n c.enqueue(chunk)\n } catch {}\n },\n close: () => {\n try {\n c.close()\n } catch {}\n },\n }\n },\n })\n ex.value.controller = controller\n } else {\n let resolve: ControllablePromise['reject'] | undefined\n let reject: ControllablePromise['reject'] | undefined\n\n ex.value = new Promise((_resolve, _reject) => {\n reject = _reject\n resolve = _resolve\n }) as ControllablePromise\n ex.value.reject = reject!\n ex.value.resolve = resolve!\n }\n })\n\n return true\n },\n resolvePromise: ({ matchId, id, promiseState }) => {\n const match = __TSR_SSR__.matches.find((m) => m.id === matchId)\n if (match) {\n const ex = match.extracted?.[id]\n if (\n ex &&\n ex.type === 'promise' &&\n ex.value &&\n promiseState.status === 'success'\n ) {\n ex.value.resolve(promiseState.data)\n return true\n }\n }\n return false\n },\n injectChunk: ({ matchId, id, chunk }) => {\n const match = __TSR_SSR__.matches.find((m) => m.id === matchId)\n\n if (match) {\n const ex = match.extracted?.[id]\n if (ex && ex.type === 'stream' && ex.value?.controller) {\n ex.value.controller.enqueue(new TextEncoder().encode(chunk.toString()))\n return true\n }\n }\n return false\n },\n closeStream: ({ matchId, id }) => {\n const match = __TSR_SSR__.matches.find((m) => m.id === matchId)\n if (match) {\n const ex = match.extracted?.[id]\n if (ex && ex.type === 'stream' && ex.value?.controller) {\n ex.value.controller.close()\n return true\n }\n }\n return false\n },\n cleanScripts: () => {\n document.querySelectorAll('.tsr-once').forEach((el) => {\n el.remove()\n })\n },\n}\n\nwindow.__TSR_SSR__ = __TSR_SSR__\n"],"names":[],"mappings":";AAAA,MAAA,6BAAe;;"}