@taujs/server 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -85,10 +85,10 @@ Integral to τjs is its internal routing:
85
85
 
86
86
  In ensuring a particular 'route' receives data for hydration there are two options:
87
87
 
88
- 1. An HTTP call syntactically not unlike 'fetch' providing params to a 'fetch' call
89
- 2. Internal service call returning data as per your architecture
88
+ 1. Internal service call returning data as per your architecture
89
+ 2. An HTTP call from your app passing resolved data to @taujs/server
90
90
 
91
- In supporting Option 2. there is a registry of services. More detail in 'Service Registry'.
91
+ In supporting Option 1. there is a registry of services. More detail in 'Service Registry'.
92
92
 
93
93
  Each routes 'path' is a simple URL regex as per below examples.
94
94
 
@@ -1,5 +1,5 @@
1
1
  import { ServerResponse } from 'node:http';
2
- import { FastifyRequest, FastifyReply, HookHandlerDoneFunction, FastifyPluginAsync } from 'fastify';
2
+ import { FastifyRequest, FastifyReply, HookHandlerDoneFunction, FastifyPluginAsync, FastifyInstance } from 'fastify';
3
3
  import { PluginOption } from 'vite';
4
4
 
5
5
  type CSPDirectives = Record<string, string[]>;
@@ -69,6 +69,7 @@ type SSRServerOptions = {
69
69
  generateCSP?: (directives: CSPDirectives, nonce: string) => string;
70
70
  };
71
71
  };
72
+ registerStaticAssets?: false | ((app: FastifyInstance) => Promise<void> | void);
72
73
  isDebug?: boolean;
73
74
  };
74
75
  type ServiceMethod = (params: Record<string, unknown>) => Promise<Record<string, unknown>>;
@@ -79,14 +80,6 @@ type RenderCallbacks = {
79
80
  onFinish: (initialDataResolved: unknown) => void;
80
81
  onError: (error: unknown) => void;
81
82
  };
82
- type FetchConfig = {
83
- url?: string;
84
- options: RequestInit & {
85
- params?: Record<string, unknown>;
86
- };
87
- serviceName?: string;
88
- serviceMethod?: string;
89
- };
90
83
  type SSRManifest = {
91
84
  [key: string]: string[];
92
85
  };
@@ -118,22 +111,28 @@ type BaseMiddleware = {
118
111
  strategy?: string;
119
112
  };
120
113
  };
114
+ type ServiceCall = {
115
+ serviceName: string;
116
+ serviceMethod: string;
117
+ args?: Record<string, unknown>;
118
+ };
119
+ type DataResult = Record<string, unknown> | ServiceCall;
120
+ type DataHandler<Params> = (params: Params, ctx: {
121
+ headers: Record<string, string>;
122
+ [key: string]: unknown;
123
+ }) => Promise<DataResult>;
121
124
  type RouteAttributes<Params = {}, Middleware = BaseMiddleware> = {
122
125
  render: 'ssr';
123
126
  hydrate?: boolean;
124
127
  meta?: Record<string, unknown>;
125
128
  middleware?: Middleware;
126
- fetch?: (params?: Params, options?: RequestInit & {
127
- params?: Record<string, unknown>;
128
- }) => Promise<FetchConfig>;
129
+ data?: DataHandler<Params>;
129
130
  } | {
130
131
  render: 'streaming';
131
132
  hydrate?: never;
132
133
  meta: Record<string, unknown>;
133
134
  middleware?: Middleware;
134
- fetch?: (params?: Params, options?: RequestInit & {
135
- params?: Record<string, unknown>;
136
- }) => Promise<FetchConfig>;
135
+ data?: DataHandler<Params>;
137
136
  };
138
137
  type Route<Params = {}> = {
139
138
  attr?: RouteAttributes<Params>;
@@ -147,4 +146,4 @@ interface InitialRouteParams extends Record<string, unknown> {
147
146
  type RouteParams = InitialRouteParams & Record<string, unknown>;
148
147
  type RoutePathsAndAttributes<Params = {}> = Omit<Route<Params>, 'element'>;
149
148
 
150
- export { type BaseMiddleware as B, type Config as C, type FetchConfig as F, type InitialRouteParams as I, type ManifestEntry as M, type NamedService as N, type ProcessedConfig as P, type Route as R, SSRServer as S, TEMPLATE as T, type RouteParams as a, type RouteAttributes as b, createMaps as c, type SSRServerOptions as d, type ServiceMethod as e, type ServiceRegistry as f, type RenderCallbacks as g, type SSRManifest as h, type Manifest as i, type RenderSSR as j, type RenderStream as k, type RenderModule as l, type RoutePathsAndAttributes as m, type CSPDirectives as n, type CSPOptions as o, processConfigs as p, defaultGenerateCSP as q, generateNonce as r, createCSPHook as s, getRequestNonce as t, applyCSP as u };
149
+ export { type BaseMiddleware as B, type Config as C, type DataResult as D, type InitialRouteParams as I, type ManifestEntry as M, type NamedService as N, type ProcessedConfig as P, type Route as R, SSRServer as S, TEMPLATE as T, type RouteParams as a, type RouteAttributes as b, createMaps as c, type SSRServerOptions as d, type ServiceMethod as e, type ServiceRegistry as f, type RenderCallbacks as g, type SSRManifest as h, type Manifest as i, type RenderSSR as j, type RenderStream as k, type RenderModule as l, type ServiceCall as m, type DataHandler as n, type RoutePathsAndAttributes as o, processConfigs as p, type CSPDirectives as q, type CSPOptions as r, defaultGenerateCSP as s, generateNonce as t, createCSPHook as u, getRequestNonce as v, applyCSP as w };
package/dist/build.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AppConfig } from './config.js';
2
2
  import 'vite';
3
- import './SSRServer-C7MMCfVq.js';
3
+ import './SSRServer-C9yjcgke.js';
4
4
  import 'node:http';
5
5
  import 'fastify';
6
6
 
package/dist/build.js CHANGED
@@ -406,32 +406,25 @@ var callServiceMethod = async (registry, serviceName, methodName, params) => {
406
406
  throw new Error(`Expected object response from ${String(serviceName)}.${String(methodName)}, but got ${typeof data}`);
407
407
  return data;
408
408
  };
409
- var fetchData = async ({ url, options }) => {
410
- if (url) {
411
- const response = await fetch(url, options);
412
- if (!response.ok) throw new Error(`Failed to fetch data from ${url}`);
413
- const data = await response.json();
414
- if (typeof data !== "object" || data === null) throw new Error(`Expected object response from ${url}, but got ${typeof data}`);
415
- return data;
416
- }
417
- throw new Error("URL must be provided to fetch data");
409
+ var isServiceDescriptor = (obj) => {
410
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return false;
411
+ const maybe = obj;
412
+ return typeof maybe.serviceName === "string" && typeof maybe.serviceMethod === "string";
418
413
  };
419
- var fetchInitialData = async (attr, params, serviceRegistry) => {
420
- if (attr && typeof attr.fetch === "function") {
421
- return attr.fetch(params, {
422
- headers: { "Content-Type": "application/json" },
423
- params
424
- }).then(async (data) => {
425
- if (data.serviceName && data.serviceMethod && typeof data.serviceName === "string" && typeof data.serviceMethod === "string")
426
- return await callServiceMethod(serviceRegistry, data.serviceName, data.serviceMethod, data.options?.params ?? {});
427
- if (data.url && typeof data.url === "string") return await fetchData(data);
428
- throw new Error("Invalid fetch configuration: must have either serviceName+serviceMethod or url");
429
- }).catch((error) => {
430
- console.error("Error fetching initial data:", error);
431
- throw error;
432
- });
414
+ var fetchInitialData = async (attr, params, serviceRegistry, ctx = { headers: {} }, callServiceMethodImpl = callServiceMethod) => {
415
+ if (!attr?.data || typeof attr.data !== "function") return {};
416
+ const result = await attr.data(params, ctx);
417
+ if (isServiceDescriptor(result)) {
418
+ const { serviceName, serviceMethod, args } = result;
419
+ if (serviceRegistry[serviceName]?.[serviceMethod]) {
420
+ return await callServiceMethodImpl(serviceRegistry, serviceName, serviceMethod, args ?? {});
421
+ }
422
+ throw new Error(`Invalid service: serviceName=${String(serviceName)}, method=${String(serviceMethod)}`);
423
+ }
424
+ if (typeof result === "object" && result !== null) {
425
+ return result;
433
426
  }
434
- return Promise.resolve({});
427
+ throw new Error("Invalid result from attr.data");
435
428
  };
436
429
  var matchRoute = (url, renderRoutes) => {
437
430
  for (const route of renderRoutes) {
@@ -545,12 +538,25 @@ var SSRServer = (0, import_fastify_plugin.default)(
545
538
  ],
546
539
  opts.isDebug
547
540
  );
548
- await app.register(import("@fastify/static"), {
549
- index: false,
550
- prefix: "/",
551
- root: baseClientRoot,
552
- wildcard: false
553
- });
541
+ if (opts.registerStaticAssets !== false) {
542
+ if (typeof opts.registerStaticAssets === "function") {
543
+ await opts.registerStaticAssets(app);
544
+ } else {
545
+ try {
546
+ const fastifyStatic = await import("@fastify/static");
547
+ await app.register(fastifyStatic.default, {
548
+ index: false,
549
+ prefix: "/",
550
+ root: baseClientRoot,
551
+ wildcard: false
552
+ });
553
+ } catch (err) {
554
+ throw new Error(
555
+ "Static asset handling requires @fastify/static to be installed. Either install it or provide your own static asset handler using `registerStaticAssets`."
556
+ );
557
+ }
558
+ }
559
+ }
554
560
  app.addHook(
555
561
  "onRequest",
556
562
  createCSPHook({
package/dist/config.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PluginOption } from 'vite';
2
- import { R as Route, a as RouteParams, b as RouteAttributes } from './SSRServer-C7MMCfVq.js';
2
+ import { R as Route, a as RouteParams, b as RouteAttributes } from './SSRServer-C9yjcgke.js';
3
3
  import 'node:http';
4
4
  import 'fastify';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { FastifyReply } from 'fastify';
2
- export { B as BaseMiddleware, C as Config, F as FetchConfig, I as InitialRouteParams, i as Manifest, M as ManifestEntry, N as NamedService, P as ProcessedConfig, g as RenderCallbacks, l as RenderModule, j as RenderSSR, k as RenderStream, R as Route, b as RouteAttributes, a as RouteParams, m as RoutePathsAndAttributes, h as SSRManifest, S as SSRServer, d as SSRServerOptions, e as ServiceMethod, f as ServiceRegistry, T as TEMPLATE, c as createMaps, p as processConfigs } from './SSRServer-C7MMCfVq.js';
2
+ export { B as BaseMiddleware, C as Config, n as DataHandler, D as DataResult, I as InitialRouteParams, i as Manifest, M as ManifestEntry, N as NamedService, P as ProcessedConfig, g as RenderCallbacks, l as RenderModule, j as RenderSSR, k as RenderStream, R as Route, b as RouteAttributes, a as RouteParams, o as RoutePathsAndAttributes, h as SSRManifest, S as SSRServer, d as SSRServerOptions, m as ServiceCall, e as ServiceMethod, f as ServiceRegistry, T as TEMPLATE, c as createMaps, p as processConfigs } from './SSRServer-C9yjcgke.js';
3
3
  import 'node:http';
4
4
  import 'vite';
5
5
 
@@ -9,7 +9,7 @@ declare module 'fastify' {
9
9
  }
10
10
  interface FastifyInstance {
11
11
  /**
12
- * Optional authentication hook to be used by the TauJS SSRServer.
12
+ * Optional authentication hook to be used by the taujs SSRServer.
13
13
  * This method must be decorated by the user when using auth middleware in `taujs.config.ts`.
14
14
  *
15
15
  * Example usage:
package/dist/index.js CHANGED
@@ -404,32 +404,25 @@ var callServiceMethod = async (registry, serviceName, methodName, params) => {
404
404
  throw new Error(`Expected object response from ${String(serviceName)}.${String(methodName)}, but got ${typeof data}`);
405
405
  return data;
406
406
  };
407
- var fetchData = async ({ url, options }) => {
408
- if (url) {
409
- const response = await fetch(url, options);
410
- if (!response.ok) throw new Error(`Failed to fetch data from ${url}`);
411
- const data = await response.json();
412
- if (typeof data !== "object" || data === null) throw new Error(`Expected object response from ${url}, but got ${typeof data}`);
413
- return data;
414
- }
415
- throw new Error("URL must be provided to fetch data");
407
+ var isServiceDescriptor = (obj) => {
408
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) return false;
409
+ const maybe = obj;
410
+ return typeof maybe.serviceName === "string" && typeof maybe.serviceMethod === "string";
416
411
  };
417
- var fetchInitialData = async (attr, params, serviceRegistry) => {
418
- if (attr && typeof attr.fetch === "function") {
419
- return attr.fetch(params, {
420
- headers: { "Content-Type": "application/json" },
421
- params
422
- }).then(async (data) => {
423
- if (data.serviceName && data.serviceMethod && typeof data.serviceName === "string" && typeof data.serviceMethod === "string")
424
- return await callServiceMethod(serviceRegistry, data.serviceName, data.serviceMethod, data.options?.params ?? {});
425
- if (data.url && typeof data.url === "string") return await fetchData(data);
426
- throw new Error("Invalid fetch configuration: must have either serviceName+serviceMethod or url");
427
- }).catch((error) => {
428
- console.error("Error fetching initial data:", error);
429
- throw error;
430
- });
412
+ var fetchInitialData = async (attr, params, serviceRegistry, ctx = { headers: {} }, callServiceMethodImpl = callServiceMethod) => {
413
+ if (!attr?.data || typeof attr.data !== "function") return {};
414
+ const result = await attr.data(params, ctx);
415
+ if (isServiceDescriptor(result)) {
416
+ const { serviceName, serviceMethod, args } = result;
417
+ if (serviceRegistry[serviceName]?.[serviceMethod]) {
418
+ return await callServiceMethodImpl(serviceRegistry, serviceName, serviceMethod, args ?? {});
419
+ }
420
+ throw new Error(`Invalid service: serviceName=${String(serviceName)}, method=${String(serviceMethod)}`);
421
+ }
422
+ if (typeof result === "object" && result !== null) {
423
+ return result;
431
424
  }
432
- return Promise.resolve({});
425
+ throw new Error("Invalid result from attr.data");
433
426
  };
434
427
  var matchRoute = (url, renderRoutes) => {
435
428
  for (const route of renderRoutes) {
@@ -543,12 +536,25 @@ var SSRServer = (0, import_fastify_plugin.default)(
543
536
  ],
544
537
  opts.isDebug
545
538
  );
546
- await app.register(import("@fastify/static"), {
547
- index: false,
548
- prefix: "/",
549
- root: baseClientRoot,
550
- wildcard: false
551
- });
539
+ if (opts.registerStaticAssets !== false) {
540
+ if (typeof opts.registerStaticAssets === "function") {
541
+ await opts.registerStaticAssets(app);
542
+ } else {
543
+ try {
544
+ const fastifyStatic = await import("@fastify/static");
545
+ await app.register(fastifyStatic.default, {
546
+ index: false,
547
+ prefix: "/",
548
+ root: baseClientRoot,
549
+ wildcard: false
550
+ });
551
+ } catch (err) {
552
+ throw new Error(
553
+ "Static asset handling requires @fastify/static to be installed. Either install it or provide your own static asset handler using `registerStaticAssets`."
554
+ );
555
+ }
556
+ }
557
+ }
552
558
  app.addHook(
553
559
  "onRequest",
554
560
  createCSPHook({
@@ -1,4 +1,4 @@
1
1
  import 'fastify';
2
- export { n as CSPDirectives, o as CSPOptions, u as applyCSP, s as createCSPHook, q as defaultGenerateCSP, r as generateNonce, t as getRequestNonce } from '../SSRServer-C7MMCfVq.js';
2
+ export { q as CSPDirectives, r as CSPOptions, w as applyCSP, u as createCSPHook, s as defaultGenerateCSP, t as generateNonce, v as getRequestNonce } from '../SSRServer-C9yjcgke.js';
3
3
  import 'node:http';
4
4
  import 'vite';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taujs/server",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "taujs [ τjs ]",
5
5
  "author": "John Smith | Aoede <taujs@aoede.uk.net> (https://www.aoede.uk.net)",
6
6
  "license": "MIT",
@@ -47,7 +47,6 @@
47
47
  "dist"
48
48
  ],
49
49
  "dependencies": {
50
- "@fastify/static": "^8.0.3",
51
50
  "path-to-regexp": "^8.1.0",
52
51
  "vite-plugin-node-polyfills": "^0.23.0"
53
52
  },
@@ -55,6 +54,7 @@
55
54
  "@arethetypeswrong/cli": "^0.15.4",
56
55
  "@babel/preset-typescript": "^7.24.7",
57
56
  "@changesets/cli": "^2.27.7",
57
+ "@fastify/static": "^8.0.3",
58
58
  "@types/node": "^20.14.9",
59
59
  "@vitest/coverage-v8": "^2.1.0",
60
60
  "@vitest/ui": "^2.1.9",
@@ -67,10 +67,16 @@
67
67
  "vitest": "^2.0.5"
68
68
  },
69
69
  "peerDependencies": {
70
+ "@fastify/static": "^8.0.3",
70
71
  "fastify": "^5.3.3",
71
72
  "typescript": "^5.5.4",
72
73
  "vite": "^6.3.5"
73
74
  },
75
+ "peerDependenciesMeta": {
76
+ "@fastify/static": {
77
+ "optional": true
78
+ }
79
+ },
74
80
  "scripts": {
75
81
  "build": "tsup",
76
82
  "build-local": "tsup && ./move.sh",