@taujs/server 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Aoede Ltd 2024
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # @taujs/server
2
+
3
+ Streaming React SSR & Hydration Fastify Plugin for integration with taujs [ τjs ] template
4
+
5
+ TypeScript / ESM-only focus
6
+ τjs - DX: Developer eXperience first focus. Integrated ViteDevServer HMR + Vite Runtime API run alongside tsx (TS eXecute) providing fast responsive dev reload times for both backend / frontend
7
+
8
+ Build: client (Vite) & server (ESBuild + Rollup)
9
+
10
+ Fastify https://fastify.dev/
11
+ Vite https://vitejs.dev/guide/ssr#building-for-production
12
+ React https://reactjs.org/
13
+
14
+ tsx https://tsx.is/
15
+ ViteDevServer HMR https://vitejs.dev/guide/ssr#setting-up-the-dev-server
16
+ Vite Runtime API https://vitejs.dev/guide/api-vite-runtime
17
+ ESBuild https://esbuild.github.io/
18
+ Rollup https://rollupjs.org/
19
+ ESM https://nodejs.org/api/esm.html
20
+
21
+ ## Development / CI
22
+
23
+ "@fastify/static": "^7.0.4",
24
+ "path-to-regexp": "^7.0.0"
25
+
26
+ npm install --legacy-peer-deps
@@ -0,0 +1,15 @@
1
+ import React from 'react';
2
+
3
+ type SSRStore<T> = {
4
+ getSnapshot: () => T;
5
+ getServerSnapshot: () => T;
6
+ setData: (newData: T) => void;
7
+ subscribe: (callback: () => void) => () => void;
8
+ };
9
+ declare const createSSRStore: <T>(initialDataPromise: Promise<T>) => SSRStore<T>;
10
+ declare const SSRStoreProvider: React.FC<React.PropsWithChildren<{
11
+ store: SSRStore<Record<string, unknown>>;
12
+ }>>;
13
+ declare const useSSRStore: <T>() => SSRStore<T>;
14
+
15
+ export { SSRStoreProvider, createSSRStore, useSSRStore };
@@ -0,0 +1,58 @@
1
+ // src/SSRDataStore.tsx
2
+ import { createContext, useContext, useSyncExternalStore } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+ var createSSRStore = (initialDataPromise) => {
5
+ let currentData;
6
+ let status = "pending";
7
+ const subscribers = /* @__PURE__ */ new Set();
8
+ let resolvePromise = null;
9
+ const serverDataPromise = new Promise((resolve) => resolvePromise = resolve);
10
+ initialDataPromise.then((data) => {
11
+ currentData = data;
12
+ status = "success";
13
+ subscribers.forEach((callback) => callback());
14
+ if (resolvePromise) resolvePromise();
15
+ }).catch((error) => {
16
+ console.error("Failed to load initial data:", error);
17
+ status = "error";
18
+ });
19
+ const setData = (newData) => {
20
+ currentData = newData;
21
+ status = "success";
22
+ subscribers.forEach((callback) => callback());
23
+ if (resolvePromise) resolvePromise();
24
+ };
25
+ const subscribe = (callback) => {
26
+ subscribers.add(callback);
27
+ return () => subscribers.delete(callback);
28
+ };
29
+ const getSnapshot = () => {
30
+ if (status === "pending") {
31
+ throw initialDataPromise;
32
+ } else if (status === "error") {
33
+ throw new Error("An error occurred while fetching the data.");
34
+ }
35
+ return currentData;
36
+ };
37
+ const getServerSnapshot = () => {
38
+ if (status === "pending") {
39
+ throw serverDataPromise;
40
+ } else if (status === "error") {
41
+ throw new Error("Data is not available on the server.");
42
+ }
43
+ return currentData;
44
+ };
45
+ return { getSnapshot, getServerSnapshot, setData, subscribe };
46
+ };
47
+ var SSRStoreContext = createContext(null);
48
+ var SSRStoreProvider = ({ store, children }) => /* @__PURE__ */ jsx(SSRStoreContext.Provider, { value: store, children });
49
+ var useSSRStore = () => {
50
+ const store = useContext(SSRStoreContext);
51
+ if (!store) throw new Error("useSSRStore must be used within a SSRStoreProvider");
52
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
53
+ };
54
+ export {
55
+ SSRStoreProvider,
56
+ createSSRStore,
57
+ useSSRStore
58
+ };
@@ -0,0 +1,68 @@
1
+ import { FastifyPluginAsync } from 'fastify';
2
+ import { ServerResponse } from 'node:http';
3
+
4
+ declare const SSRServer: FastifyPluginAsync<SSRServerOptions>;
5
+ type ServiceRegistry = {
6
+ [serviceName: string]: {
7
+ [methodName: string]: (params: Record<string, unknown>) => Promise<Record<string, unknown>>;
8
+ };
9
+ };
10
+ type RenderCallbacks = {
11
+ onHead: (headContent: string) => void;
12
+ onFinish: (initialDataResolved: unknown) => void;
13
+ onError: (error: unknown) => void;
14
+ };
15
+ type FetchConfig = {
16
+ url?: string;
17
+ options: RequestInit & {
18
+ params?: any;
19
+ };
20
+ serviceName?: string;
21
+ serviceMethod?: string;
22
+ };
23
+ type SSRServerOptions = {
24
+ clientRoot: string;
25
+ clientHtmlTemplate: string;
26
+ clientEntryClient: string;
27
+ clientEntryServer: string;
28
+ routes: Route<RouteParams>[];
29
+ serviceRegistry: ServiceRegistry;
30
+ isDebug?: boolean;
31
+ };
32
+ type Manifest = {
33
+ [key: string]: {
34
+ file: string;
35
+ src?: string;
36
+ isDynamicEntry?: boolean;
37
+ imports?: string[];
38
+ css?: string[];
39
+ assets?: string[];
40
+ };
41
+ };
42
+ type RenderModule = {
43
+ streamRender: (serverResponse: ServerResponse, callbacks: RenderCallbacks, initialDataPromise: Promise<Record<string, unknown>>, bootstrapModules: string) => void;
44
+ };
45
+ type RouteAttributes<Params = {}> = {
46
+ fetch: (params?: Params, options?: RequestInit & {
47
+ params?: Record<string, unknown>;
48
+ }) => Promise<{
49
+ options: RequestInit & {
50
+ params?: Record<string, unknown>;
51
+ };
52
+ serviceName?: string;
53
+ serviceMethod?: string;
54
+ url?: string;
55
+ }>;
56
+ };
57
+ type Route<Params = {}> = {
58
+ attributes: RouteAttributes<Params>;
59
+ path: string;
60
+ };
61
+ interface InitialRouteParams extends Record<string, unknown> {
62
+ serviceName?: string;
63
+ serviceMethod?: string;
64
+ }
65
+ type RouteParams = InitialRouteParams & Record<string, unknown>;
66
+ type RoutePathsAndAttributes<Params = {}> = Omit<Route<Params>, 'element'>;
67
+
68
+ export { type FetchConfig, type InitialRouteParams, type Manifest, type RenderCallbacks, type RenderModule, type Route, type RouteAttributes, type RouteParams, type RoutePathsAndAttributes, SSRServer, type SSRServerOptions, type ServiceRegistry };
@@ -0,0 +1,395 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // node_modules/fastify-plugin/lib/getPluginName.js
28
+ var require_getPluginName = __commonJS({
29
+ "node_modules/fastify-plugin/lib/getPluginName.js"(exports, module) {
30
+ "use strict";
31
+ var fpStackTracePattern = /at\s{1}(?:.*\.)?plugin\s{1}.*\n\s*(.*)/;
32
+ var fileNamePattern = /(\w*(\.\w*)*)\..*/;
33
+ module.exports = function getPluginName(fn) {
34
+ if (fn.name.length > 0) return fn.name;
35
+ const stackTraceLimit = Error.stackTraceLimit;
36
+ Error.stackTraceLimit = 10;
37
+ try {
38
+ throw new Error("anonymous function");
39
+ } catch (e) {
40
+ Error.stackTraceLimit = stackTraceLimit;
41
+ return extractPluginName(e.stack);
42
+ }
43
+ };
44
+ function extractPluginName(stack) {
45
+ const m = stack.match(fpStackTracePattern);
46
+ return m ? m[1].split(/[/\\]/).slice(-1)[0].match(fileNamePattern)[1] : "anonymous";
47
+ }
48
+ module.exports.extractPluginName = extractPluginName;
49
+ }
50
+ });
51
+
52
+ // node_modules/fastify-plugin/lib/toCamelCase.js
53
+ var require_toCamelCase = __commonJS({
54
+ "node_modules/fastify-plugin/lib/toCamelCase.js"(exports, module) {
55
+ "use strict";
56
+ module.exports = function toCamelCase(name) {
57
+ if (name[0] === "@") {
58
+ name = name.slice(1).replace("/", "-");
59
+ }
60
+ const newName = name.replace(/-(.)/g, function(match2, g1) {
61
+ return g1.toUpperCase();
62
+ });
63
+ return newName;
64
+ };
65
+ }
66
+ });
67
+
68
+ // node_modules/fastify-plugin/plugin.js
69
+ var require_plugin = __commonJS({
70
+ "node_modules/fastify-plugin/plugin.js"(exports, module) {
71
+ "use strict";
72
+ var getPluginName = require_getPluginName();
73
+ var toCamelCase = require_toCamelCase();
74
+ var count = 0;
75
+ function plugin(fn, options = {}) {
76
+ let autoName = false;
77
+ if (typeof fn.default !== "undefined") {
78
+ fn = fn.default;
79
+ }
80
+ if (typeof fn !== "function") {
81
+ throw new TypeError(
82
+ `fastify-plugin expects a function, instead got a '${typeof fn}'`
83
+ );
84
+ }
85
+ if (typeof options === "string") {
86
+ options = {
87
+ fastify: options
88
+ };
89
+ }
90
+ if (typeof options !== "object" || Array.isArray(options) || options === null) {
91
+ throw new TypeError("The options object should be an object");
92
+ }
93
+ if (options.fastify !== void 0 && typeof options.fastify !== "string") {
94
+ throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof options.fastify}'`);
95
+ }
96
+ if (!options.name) {
97
+ autoName = true;
98
+ options.name = getPluginName(fn) + "-auto-" + count++;
99
+ }
100
+ fn[Symbol.for("skip-override")] = options.encapsulate !== true;
101
+ fn[Symbol.for("fastify.display-name")] = options.name;
102
+ fn[Symbol.for("plugin-meta")] = options;
103
+ if (!fn.default) {
104
+ fn.default = fn;
105
+ }
106
+ const camelCase = toCamelCase(options.name);
107
+ if (!autoName && !fn[camelCase]) {
108
+ fn[camelCase] = fn;
109
+ }
110
+ return fn;
111
+ }
112
+ module.exports = plugin;
113
+ module.exports.default = plugin;
114
+ module.exports.fastifyPlugin = plugin;
115
+ }
116
+ });
117
+
118
+ // src/SSRServer.ts
119
+ var import_fastify_plugin = __toESM(require_plugin(), 1);
120
+ import fs from "node:fs/promises";
121
+ import path from "node:path";
122
+ import { createViteRuntime } from "vite";
123
+
124
+ // src/utils/index.ts
125
+ import { fileURLToPath } from "node:url";
126
+ import { dirname, join } from "node:path";
127
+ import { match } from "path-to-regexp";
128
+ var isDevelopment = process.env.NODE_ENV === "development";
129
+ var __filename = fileURLToPath(import.meta.url);
130
+ var __dirname = join(dirname(__filename), !isDevelopment ? "./" : "..");
131
+ var CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
132
+ async function collectStyle(server, entries) {
133
+ const urls = await collectStyleUrls(server, entries);
134
+ const codes = await Promise.all(
135
+ urls.map(async (url) => {
136
+ const res = await server.transformRequest(url + "?direct");
137
+ return [`/* [collectStyle] ${url} */`, res?.code];
138
+ })
139
+ );
140
+ return codes.flat().filter(Boolean).join("\n\n");
141
+ }
142
+ async function collectStyleUrls(server, entries) {
143
+ const visited = /* @__PURE__ */ new Set();
144
+ async function traverse(url) {
145
+ const [, id] = await server.moduleGraph.resolveUrl(url);
146
+ if (visited.has(id)) return;
147
+ visited.add(id);
148
+ const mod = server.moduleGraph.getModuleById(id);
149
+ if (!mod) return;
150
+ await Promise.all([...mod.importedModules].map((childMod) => traverse(childMod.url)));
151
+ }
152
+ await Promise.all(entries.map((e) => server.transformRequest(e)));
153
+ await Promise.all(entries.map((url) => traverse(url)));
154
+ return [...visited].filter((url) => url.match(CSS_LANGS_RE));
155
+ }
156
+ function renderPreloadLinks(modules, manifest) {
157
+ const seen = /* @__PURE__ */ new Set();
158
+ let links = "";
159
+ modules.forEach((id) => {
160
+ const files = manifest[id];
161
+ if (files) {
162
+ files.forEach((file) => {
163
+ if (!seen.has(file)) {
164
+ seen.add(file);
165
+ links += renderPreloadLink(file);
166
+ }
167
+ });
168
+ }
169
+ });
170
+ return links;
171
+ }
172
+ function renderPreloadLink(file) {
173
+ const fileType = file.match(/\.(js|css|woff2?|gif|jpe?g|png|svg)$/)?.[1];
174
+ if (!fileType) return "";
175
+ switch (fileType) {
176
+ case "js":
177
+ return `<link rel="modulepreload" href="${file}">`;
178
+ case "css":
179
+ return `<link rel="stylesheet" href="${file}">`;
180
+ case "woff":
181
+ case "woff2":
182
+ return `<link rel="preload" href="${file}" as="font" type="font/${fileType}" crossorigin>`;
183
+ case "gif":
184
+ case "jpeg":
185
+ case "jpg":
186
+ case "png":
187
+ return `<link rel="preload" href="${file}" as="image" type="image/${fileType}">`;
188
+ case "svg":
189
+ return `<link rel="preload" href="${file}" as="image" type="image/svg+xml">`;
190
+ default:
191
+ return "";
192
+ }
193
+ }
194
+ var callServiceMethod = async (serviceRegistry, serviceName, serviceMethod, params) => {
195
+ const service = serviceRegistry[serviceName];
196
+ if (service && typeof service[serviceMethod] === "function") {
197
+ const method = service[serviceMethod];
198
+ const data = await method(params);
199
+ if (typeof data !== "object" || data === null)
200
+ throw new Error(`Expected object response from service method ${serviceMethod} on ${serviceName}, but got ${typeof data}`);
201
+ return data;
202
+ }
203
+ throw new Error(`Service method ${serviceMethod} does not exist on ${serviceName}`);
204
+ };
205
+ var fetchData = async ({ url, options }) => {
206
+ if (url) {
207
+ const response = await fetch(url, options);
208
+ if (!response.ok) throw new Error(`Failed to fetch data from ${url}`);
209
+ const data = await response.json();
210
+ if (typeof data !== "object" || data === null) throw new Error(`Expected object response from ${url}, but got ${typeof data}`);
211
+ return data;
212
+ }
213
+ throw new Error("URL must be provided to fetch data");
214
+ };
215
+ var matchRoute = (url, renderRoutes) => {
216
+ for (const route of renderRoutes) {
217
+ const matcher = match(route.path, {
218
+ decode: decodeURIComponent
219
+ });
220
+ const matched = matcher(url);
221
+ if (matched) return { route, params: matched.params };
222
+ }
223
+ return null;
224
+ };
225
+ var getCssLinks = (manifest) => {
226
+ const links = [];
227
+ for (const value of Object.values(manifest)) {
228
+ if (value.css && value.css.length > 0) {
229
+ value.css.forEach((cssFile) => {
230
+ links.push(`<link rel="preload stylesheet" as="style" type="text/css" href="/${cssFile}">`);
231
+ });
232
+ }
233
+ }
234
+ return links.join("");
235
+ };
236
+ var overrideCSSHMRConsoleError = () => {
237
+ const originalConsoleError = console.error;
238
+ console.error = function(message, ...optionalParams) {
239
+ if (typeof message === "string" && message.includes("css hmr is not supported in runtime mode")) return;
240
+ originalConsoleError.apply(console, [message, ...optionalParams]);
241
+ };
242
+ };
243
+
244
+ // src/SSRServer.ts
245
+ var SSRServer = (0, import_fastify_plugin.default)(
246
+ async (app, opts) => {
247
+ const { clientRoot, clientHtmlTemplate, clientEntryClient, clientEntryServer, routes, serviceRegistry, isDebug } = opts;
248
+ const templateHtmlPath = path.join(clientRoot, clientHtmlTemplate);
249
+ const templateHtml = !isDevelopment ? await fs.readFile(templateHtmlPath, "utf-8") : await fs.readFile(path.join(clientRoot, clientHtmlTemplate), "utf-8");
250
+ const ssrManifestPath = path.join(clientRoot, ".vite/ssr-manifest.json");
251
+ const ssrManifest = !isDevelopment ? JSON.parse(await fs.readFile(ssrManifestPath, "utf-8")) : void 0;
252
+ const manifestPath = path.join(clientRoot, ".vite/manifest.json");
253
+ const manifest = !isDevelopment ? JSON.parse(await fs.readFile(manifestPath, "utf-8")) : void 0;
254
+ const bootstrapModules = isDevelopment ? `/${clientEntryClient}.tsx` : `/${manifest[`${clientEntryClient}.tsx`].file}`;
255
+ const preloadLinks = !isDevelopment ? renderPreloadLinks(Object.keys(ssrManifest), ssrManifest) : void 0;
256
+ const cssLinks = !isDevelopment ? getCssLinks(manifest) : void 0;
257
+ let renderModule;
258
+ let styles;
259
+ let template = templateHtml;
260
+ let viteDevServer;
261
+ let viteRuntime;
262
+ if (isDevelopment) {
263
+ const { createServer } = await import("vite");
264
+ viteDevServer = await createServer({
265
+ appType: "custom",
266
+ mode: "development",
267
+ plugins: [
268
+ ...isDebug ? [
269
+ {
270
+ name: "taujs-ssr-server-debug-logging",
271
+ configureServer(server) {
272
+ console.log("\u03C4js debug ssr server started.");
273
+ server.middlewares.use((req, res, next) => {
274
+ console.log(`rx: ${req.url}`);
275
+ res.on("finish", () => {
276
+ console.log(`cx: ${req.url}`);
277
+ });
278
+ next();
279
+ });
280
+ }
281
+ }
282
+ ] : []
283
+ ],
284
+ resolve: {
285
+ alias: {
286
+ "@client": path.resolve(clientRoot),
287
+ "@server": path.resolve(__dirname),
288
+ "@shared": path.resolve(__dirname, "../shared")
289
+ }
290
+ },
291
+ root: clientRoot,
292
+ server: {
293
+ middlewareMode: true,
294
+ hmr: {
295
+ port: 5174
296
+ }
297
+ }
298
+ });
299
+ viteRuntime = await createViteRuntime(viteDevServer);
300
+ overrideCSSHMRConsoleError();
301
+ void app.addHook("onRequest", async (request, reply) => {
302
+ await new Promise((resolve) => {
303
+ viteDevServer.middlewares(request.raw, reply.raw, () => {
304
+ if (!reply.sent) resolve();
305
+ });
306
+ });
307
+ });
308
+ } else {
309
+ renderModule = await import(path.join(clientRoot, `${clientEntryServer}.js`));
310
+ void await app.register(import("@fastify/static"), {
311
+ index: false,
312
+ root: path.resolve(clientRoot),
313
+ wildcard: false
314
+ });
315
+ }
316
+ void app.get("/*", async (req, reply) => {
317
+ try {
318
+ const url = req.url ? new URL(req.url, `http://${req.headers.host}`).pathname : "/";
319
+ const matchedRoute = matchRoute(url, routes);
320
+ if (!matchedRoute) {
321
+ reply.callNotFound();
322
+ return;
323
+ }
324
+ if (isDevelopment) {
325
+ template = await viteDevServer.transformIndexHtml(url, template);
326
+ renderModule = await viteRuntime.executeEntrypoint(path.join(clientRoot, `${clientEntryServer}.tsx`));
327
+ styles = await collectStyle(viteDevServer, [`${clientRoot}/${clientEntryServer}.tsx`]);
328
+ template = template.replace("</head>", `<style type="text/css">${styles}</style></head>`);
329
+ }
330
+ const { streamRender } = renderModule;
331
+ const { route, params } = matchedRoute;
332
+ const { attributes } = route;
333
+ const [beforeBody = "", afterBody] = template.split("<!--ssr-html-->");
334
+ const [beforeHead, afterHead] = beforeBody.split("<!--ssr-head-->");
335
+ const initialDataPromise = attributes && typeof attributes.fetch === "function" ? attributes.fetch(params, {
336
+ headers: { "Content-Type": "application/json" },
337
+ params
338
+ }).then((data) => {
339
+ if (data.serviceName && data.serviceMethod)
340
+ return callServiceMethod(serviceRegistry, data.serviceName, data.serviceMethod, data.options.params ?? {});
341
+ return fetchData(data);
342
+ }).catch((error) => {
343
+ console.error("Error fetching initial data:", error);
344
+ return {};
345
+ }) : Promise.resolve({});
346
+ reply.raw.writeHead(200, { "Content-Type": "text/html" });
347
+ reply.raw.write(beforeHead);
348
+ streamRender(
349
+ reply.raw,
350
+ {
351
+ onHead: (headContent) => {
352
+ let fullHeadContent = headContent;
353
+ if (ssrManifest) fullHeadContent += preloadLinks;
354
+ if (manifest) fullHeadContent += cssLinks;
355
+ reply.raw.write(`${fullHeadContent}${afterHead}`);
356
+ },
357
+ onFinish: async (initialDataResolved) => {
358
+ reply.raw.write(`<script>window.__INITIAL_DATA__ = ${JSON.stringify(initialDataResolved).replace(/</g, "\\u003c")}</script>`);
359
+ reply.raw.write(afterBody);
360
+ reply.raw.end();
361
+ },
362
+ onError: (error) => {
363
+ console.error("Critical rendering error:", error);
364
+ if (!reply.raw.headersSent) reply.raw.writeHead(500, { "Content-Type": "text/plain" });
365
+ reply.raw.end("Internal Server Error");
366
+ }
367
+ },
368
+ initialDataPromise,
369
+ bootstrapModules
370
+ );
371
+ } catch (error) {
372
+ console.error("Error setting up SSR stream:", error);
373
+ if (!reply.raw.headersSent) reply.raw.writeHead(500, { "Content-Type": "text/plain" });
374
+ reply.raw.end("Internal Server Error");
375
+ }
376
+ });
377
+ void app.setNotFoundHandler(async (req, reply) => {
378
+ if (/\.\w+$/.test(req.raw.url ?? "")) return reply.callNotFound();
379
+ try {
380
+ let template2 = templateHtml;
381
+ template2 = template2.replace("<!--ssr-head-->", "").replace("<!--ssr-html-->", "");
382
+ if (!isDevelopment) template2 = template2.replace("</head>", `${getCssLinks(manifest)}</head>`);
383
+ template2 = template2.replace("</body>", `<script type="module" src="${bootstrapModules}" async=""></script></body>`);
384
+ reply.status(200).type("text/html").send(template2);
385
+ } catch (error) {
386
+ console.error("Failed to serve clientHtmlTemplate:", error);
387
+ reply.status(500).send("Internal Server Error");
388
+ }
389
+ });
390
+ },
391
+ { name: "taujs-ssr-server" }
392
+ );
393
+ export {
394
+ SSRServer
395
+ };
package/package.json ADDED
@@ -0,0 +1,85 @@
1
+ {
2
+ "author": "Aoede <taujs@aoede.uk.net> (https://www.aoede.uk.net)",
3
+ "bugs": {
4
+ "url": "https://github.com/aoede3/taujs-server/issues"
5
+ },
6
+ "description": "taujs | τjs",
7
+ "homepage": "https://github.com/aoede3/taujs-server",
8
+ "keywords": [
9
+ "fastify",
10
+ "typescript",
11
+ "esm",
12
+ "vite",
13
+ "streaming",
14
+ "react",
15
+ "ssr"
16
+ ],
17
+ "license": "MIT",
18
+ "name": "@taujs/server",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/aoede3/taujs-server.git"
22
+ },
23
+ "version": "0.0.1",
24
+ "exports": {
25
+ ".": {
26
+ "import": "./dist/SSRServer.js",
27
+ "types": "./dist/SSRServer.d.ts"
28
+ },
29
+ "./data-store": {
30
+ "import": "./dist/SSRDataStore.js",
31
+ "types": "./dist/SSRDataStore.d.ts"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "dist"
37
+ ],
38
+ "main": "./dist/SSRServer.js",
39
+ "types": "./dist/SSRServer.d.ts",
40
+ "typesVersions": {
41
+ "*": {
42
+ "data-store": [
43
+ "./dist/SSRDataStore.d.ts"
44
+ ]
45
+ }
46
+ },
47
+ "type": "module",
48
+ "dependencies": {
49
+ "@fastify/static": "^7.0.4",
50
+ "path-to-regexp": "^7.0.0"
51
+ },
52
+ "devDependencies": {
53
+ "@arethetypeswrong/cli": "^0.15.4",
54
+ "@babel/preset-typescript": "^7.24.7",
55
+ "@changesets/cli": "^2.27.7",
56
+ "@types/node": "^20.14.9",
57
+ "@types/react": "^18.3.3",
58
+ "fastify": "^4.28.0",
59
+ "prettier": "^3.3.3",
60
+ "tsup": "^8.2.4",
61
+ "vite": "^5.4.2",
62
+ "vitest": "^2.0.5"
63
+ },
64
+ "peerDependencies": {
65
+ "@types/node": "^20.14.9",
66
+ "@types/react": "^18.3.3",
67
+ "@vitejs/plugin-react": "^4.3.1",
68
+ "fastify": "^4.28.0",
69
+ "react": "^18.3.1",
70
+ "react-dom": "^18.3.1",
71
+ "typescript": "^5.5.4",
72
+ "vite": "^5.4.2"
73
+ },
74
+ "scripts": {
75
+ "build": "tsup",
76
+ "ci": "npm run build && npm run check-format && npm run check-exports && npm run lint",
77
+ "lint": "tsc",
78
+ "test": "vitest run",
79
+ "format": "prettier --write .",
80
+ "check-format": "prettier --check .",
81
+ "check-exports": "attw --pack . --ignore-rules=cjs-resolves-to-esm",
82
+ "prepublishOnly": "npm run ci",
83
+ "local-release": "npm run ci && changeset version && changeset publish"
84
+ }
85
+ }