@askrjs/askr 0.0.43 → 0.0.45
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/dist/benchmark.js +2 -2
- package/dist/bin/askr-ssg.js.map +1 -1
- package/dist/boot/index.js.map +1 -1
- package/dist/common/env.js.map +1 -1
- package/dist/common/route-activity.js.map +1 -1
- package/dist/common/ssr.d.ts +22 -1
- package/dist/common/ssr.d.ts.map +1 -1
- package/dist/common/ssr.js +9 -1
- package/dist/common/ssr.js.map +1 -1
- package/dist/control/case.js.map +1 -1
- package/dist/control/show.js.map +1 -1
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/index.js.map +1 -1
- package/dist/foundations/icon/icon.js.map +1 -1
- package/dist/foundations/structures/layer.js.map +1 -1
- package/dist/foundations/structures/portal.js.map +1 -1
- package/dist/fx/fx.js.map +1 -1
- package/dist/fx/timing.js.map +1 -1
- package/dist/renderer/children.js.map +1 -1
- package/dist/renderer/cleanup.js.map +1 -1
- package/dist/renderer/dom.js.map +1 -1
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/fastpath.js.map +1 -1
- package/dist/renderer/for-commit.js.map +1 -1
- package/dist/renderer/keyed.js.map +1 -1
- package/dist/renderer/reconcile.js.map +1 -1
- package/dist/renderer/utils.js.map +1 -1
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/policy.js.map +1 -1
- package/dist/router/route.d.ts +4 -0
- package/dist/router/route.d.ts.map +1 -1
- package/dist/router/route.js +4 -1
- package/dist/router/route.js.map +1 -1
- package/dist/runtime/component.d.ts +1 -0
- package/dist/runtime/component.d.ts.map +1 -1
- package/dist/runtime/component.js +16 -8
- package/dist/runtime/component.js.map +1 -1
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/derive.js.map +1 -1
- package/dist/runtime/dev-namespace.js.map +1 -1
- package/dist/runtime/effect.js.map +1 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/fastlane.js.map +1 -1
- package/dist/runtime/for.js.map +1 -1
- package/dist/runtime/operations.js.map +1 -1
- package/dist/runtime/readable.d.ts +2 -1
- package/dist/runtime/readable.d.ts.map +1 -1
- package/dist/runtime/readable.js +41 -10
- package/dist/runtime/readable.js.map +1 -1
- package/dist/runtime/resource-cell.js.map +1 -1
- package/dist/runtime/scheduler.js.map +1 -1
- package/dist/runtime/selector.js.map +1 -1
- package/dist/ssg/batch-render.js +27 -5
- package/dist/ssg/batch-render.js.map +1 -1
- package/dist/ssg/create-static-gen.d.ts.map +1 -1
- package/dist/ssg/create-static-gen.js +6 -4
- package/dist/ssg/create-static-gen.js.map +1 -1
- package/dist/ssg/generate-metadata.js.map +1 -1
- package/dist/ssg/incremental-manifest.js.map +1 -1
- package/dist/ssg/index.d.ts +2 -1
- package/dist/ssg/resolve-ssg-data.js +18 -1
- package/dist/ssg/resolve-ssg-data.js.map +1 -1
- package/dist/ssg/types.d.ts +3 -0
- package/dist/ssg/types.d.ts.map +1 -1
- package/dist/ssg/write-static-files.js.map +1 -1
- package/dist/ssr/context.d.ts +1 -2
- package/dist/ssr/context.d.ts.map +1 -1
- package/dist/ssr/context.js.map +1 -1
- package/dist/ssr/escape.js.map +1 -1
- package/dist/ssr/index.d.ts +10 -11
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/ssr/index.js +104 -68
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/render-keys.js.map +1 -1
- package/dist/ssr/render-resolved.d.ts +1 -1
- package/dist/testing/index.js.map +1 -1
- package/package.json +4 -3
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { interpolateRoutePath } from "./route-utils.js";
|
|
2
2
|
//#region src/ssg/resolve-ssg-data.ts
|
|
3
|
+
function hasOwnRouteData(dataMap, path) {
|
|
4
|
+
return Object.prototype.hasOwnProperty.call(dataMap, path);
|
|
5
|
+
}
|
|
3
6
|
/**
|
|
4
7
|
* Resolve and validate data for SSG routes
|
|
5
8
|
* Returns a map of route path -> SSRData
|
|
@@ -21,6 +24,20 @@ function resolveSsgData(routes, options = {}) {
|
|
|
21
24
|
}
|
|
22
25
|
return dataMap;
|
|
23
26
|
}
|
|
27
|
+
function resolveSsgRouteData(dataMap, routePath, concretePath) {
|
|
28
|
+
if (hasOwnRouteData(dataMap, concretePath)) return {
|
|
29
|
+
hasData: true,
|
|
30
|
+
data: dataMap[concretePath]
|
|
31
|
+
};
|
|
32
|
+
if (hasOwnRouteData(dataMap, routePath)) return {
|
|
33
|
+
hasData: true,
|
|
34
|
+
data: dataMap[routePath]
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
hasData: false,
|
|
38
|
+
data: void 0
|
|
39
|
+
};
|
|
40
|
+
}
|
|
24
41
|
function isStringRecord(value) {
|
|
25
42
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
26
43
|
for (const recordValue of Object.values(value)) if (typeof recordValue !== "string") return false;
|
|
@@ -83,6 +100,6 @@ function validateRoutes(routes) {
|
|
|
83
100
|
}
|
|
84
101
|
}
|
|
85
102
|
//#endregion
|
|
86
|
-
export { expandRoutes, resolveSsgData, validateRoutes };
|
|
103
|
+
export { expandRoutes, resolveSsgData, resolveSsgRouteData, validateRoutes };
|
|
87
104
|
|
|
88
105
|
//# sourceMappingURL=resolve-ssg-data.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-ssg-data.js","names":[],"sources":["../../src/ssg/resolve-ssg-data.ts"],"sourcesContent":["/**\n * Data resolution for SSG\n *\n * Merges user-supplied data overrides with any auto-discovered resources.\n * In phase 1, primarily handles user-supplied data.\n */\n\nimport type { SSRData } from '../common/ssr';\nimport type { RouteConfig } from './types';\nimport { interpolateRoutePath } from './route-utils';\n\ninterface DataResolutionOptions {\n /** User-supplied data overrides per route path */\n dataOverrides?: Record<string, unknown>;\n}\n\n/**\n * Resolve and validate data for SSG routes\n * Returns a map of route path -> SSRData\n *\n * In phase 1: accepts user-supplied dataOverrides\n * In phase 2: can be extended to auto-discover resources\n */\nexport function resolveSsgData(\n routes: RouteConfig[],\n options: DataResolutionOptions = {}\n): Record<string, SSRData> {\n const { dataOverrides = {} } = options;\n const dataMap: Record<string, SSRData> = {};\n\n for (const route of routes) {\n const concretePath = interpolateRoutePath(route.path, route.params);\n const overridePath =\n concretePath in dataOverrides\n ? concretePath\n : route.path in dataOverrides\n ? route.path\n : null;\n\n // Check if user provided data for this route\n if (overridePath) {\n const data = dataOverrides[overridePath];\n if (typeof data !== 'object' || data === null || Array.isArray(data)) {\n throw new Error(\n `data for route \"${overridePath}\" must be an object, got ${typeof data}`\n );\n }\n dataMap[overridePath] = data as SSRData;\n }\n // In phase 1, routes without data are rendered with no SSR data\n // Phase 2 can add auto-discovery here\n }\n\n return dataMap;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n for (const recordValue of Object.values(value)) {\n if (typeof recordValue !== 'string') {\n return false;\n }\n }\n\n return true;\n}\n\nfunction validateRouteShape(route: RouteConfig): void {\n if (typeof route.path !== 'string' || !route.path.startsWith('/')) {\n throw new Error(\n `route path must be a string starting with \"/\", got \"${route.path}\"`\n );\n }\n\n const handler = route.handler ?? route.component;\n if (typeof handler !== 'function') {\n throw new Error(\n `route handler must be a function for path \"${route.path}\"`\n );\n }\n\n if (route.params !== undefined && !isStringRecord(route.params)) {\n throw new Error(\n `route \"${route.path}\" params must be an object containing only string values`\n );\n }\n\n if (route.invalidationKeys !== undefined) {\n if (!Array.isArray(route.invalidationKeys)) {\n throw new Error(\n `route \"${route.path}\" invalidationKeys must be an array of strings`\n );\n }\n for (const key of route.invalidationKeys) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `route \"${route.path}\" invalidationKeys must contain only non-empty strings`\n );\n }\n }\n }\n}\n\nfunction validateEntriesResult(\n route: RouteConfig,\n entries: unknown\n): Array<Record<string, string>> {\n if (!Array.isArray(entries)) {\n throw new Error(\n `route \"${route.path}\" entries must return an array of param maps`\n );\n }\n\n return entries.map((entry, index) => {\n if (!isStringRecord(entry)) {\n throw new Error(\n `route \"${route.path}\" entries[${index}] must be an object containing only string values`\n );\n }\n\n return entry;\n });\n}\n\nexport async function expandRoutes(\n routes: RouteConfig[]\n): Promise<RouteConfig[]> {\n if (!Array.isArray(routes)) {\n throw new Error('routes must be an array');\n }\n\n const expanded: RouteConfig[] = [];\n\n for (const route of routes) {\n validateRouteShape(route);\n\n if (route.params) {\n expanded.push({ ...route, entries: undefined });\n }\n\n if (!route.entries) {\n if (!route.params) {\n expanded.push(route);\n }\n continue;\n }\n\n const entries = validateEntriesResult(route, await route.entries());\n for (const params of entries) {\n expanded.push({ ...route, params, entries: undefined });\n }\n }\n\n return expanded;\n}\n\n/**\n * Validate routes are properly configured\n */\nexport function validateRoutes(routes: RouteConfig[]): void {\n if (!Array.isArray(routes)) {\n throw new Error('routes must be an array');\n }\n\n const seen = new Set<string>();\n\n for (const route of routes) {\n validateRouteShape(route);\n\n const key = `${route.path}::${JSON.stringify(route.params || {})}`;\n if (seen.has(key)) {\n throw new Error(\n `duplicate route entry detected for path \"${route.path}\"`\n );\n }\n seen.add(key);\n\n if (route.path.includes('{')) {\n const paramNames = Array.from(route.path.matchAll(/\\{([^}]+)\\}/g)).map(\n (m) => m[1]\n );\n if (!route.params) {\n throw new Error(\n `route \"${route.path}\" uses path parameters and requires params`\n );\n }\n for (const name of paramNames) {\n if (!(name in route.params)) {\n throw new Error(\n `route \"${route.path}\" missing required param \"${name}\"`\n );\n }\n }\n }\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"resolve-ssg-data.js","names":[],"sources":["../../src/ssg/resolve-ssg-data.ts"],"sourcesContent":["/**\n * Data resolution for SSG\n *\n * Merges user-supplied data overrides with any auto-discovered resources.\n * In phase 1, primarily handles user-supplied data.\n */\n\nimport type { SSRData } from '../common/ssr';\nimport type { RouteConfig } from './types';\nimport { interpolateRoutePath } from './route-utils';\n\ninterface DataResolutionOptions {\n /** User-supplied data overrides per route path */\n dataOverrides?: Record<string, unknown>;\n}\n\nexport interface ResolvedSsgRouteData {\n hasData: boolean;\n data?: SSRData;\n}\n\nfunction hasOwnRouteData(\n dataMap: Record<string, SSRData>,\n path: string\n): boolean {\n return Object.prototype.hasOwnProperty.call(dataMap, path);\n}\n\n/**\n * Resolve and validate data for SSG routes\n * Returns a map of route path -> SSRData\n *\n * In phase 1: accepts user-supplied dataOverrides\n * In phase 2: can be extended to auto-discover resources\n */\nexport function resolveSsgData(\n routes: RouteConfig[],\n options: DataResolutionOptions = {}\n): Record<string, SSRData> {\n const { dataOverrides = {} } = options;\n const dataMap: Record<string, SSRData> = {};\n\n for (const route of routes) {\n const concretePath = interpolateRoutePath(route.path, route.params);\n const overridePath =\n concretePath in dataOverrides\n ? concretePath\n : route.path in dataOverrides\n ? route.path\n : null;\n\n // Check if user provided data for this route\n if (overridePath) {\n const data = dataOverrides[overridePath];\n if (typeof data !== 'object' || data === null || Array.isArray(data)) {\n throw new Error(\n `data for route \"${overridePath}\" must be an object, got ${typeof data}`\n );\n }\n dataMap[overridePath] = data as SSRData;\n }\n // In phase 1, routes without data are rendered with no SSR data\n // Phase 2 can add auto-discovery here\n }\n\n return dataMap;\n}\n\nexport function resolveSsgRouteData(\n dataMap: Record<string, SSRData>,\n routePath: string,\n concretePath: string\n): ResolvedSsgRouteData {\n if (hasOwnRouteData(dataMap, concretePath)) {\n return {\n hasData: true,\n data: dataMap[concretePath],\n };\n }\n\n if (hasOwnRouteData(dataMap, routePath)) {\n return {\n hasData: true,\n data: dataMap[routePath],\n };\n }\n\n return {\n hasData: false,\n data: undefined,\n };\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n for (const recordValue of Object.values(value)) {\n if (typeof recordValue !== 'string') {\n return false;\n }\n }\n\n return true;\n}\n\nfunction validateRouteShape(route: RouteConfig): void {\n if (typeof route.path !== 'string' || !route.path.startsWith('/')) {\n throw new Error(\n `route path must be a string starting with \"/\", got \"${route.path}\"`\n );\n }\n\n const handler = route.handler ?? route.component;\n if (typeof handler !== 'function') {\n throw new Error(\n `route handler must be a function for path \"${route.path}\"`\n );\n }\n\n if (route.params !== undefined && !isStringRecord(route.params)) {\n throw new Error(\n `route \"${route.path}\" params must be an object containing only string values`\n );\n }\n\n if (route.invalidationKeys !== undefined) {\n if (!Array.isArray(route.invalidationKeys)) {\n throw new Error(\n `route \"${route.path}\" invalidationKeys must be an array of strings`\n );\n }\n for (const key of route.invalidationKeys) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error(\n `route \"${route.path}\" invalidationKeys must contain only non-empty strings`\n );\n }\n }\n }\n}\n\nfunction validateEntriesResult(\n route: RouteConfig,\n entries: unknown\n): Array<Record<string, string>> {\n if (!Array.isArray(entries)) {\n throw new Error(\n `route \"${route.path}\" entries must return an array of param maps`\n );\n }\n\n return entries.map((entry, index) => {\n if (!isStringRecord(entry)) {\n throw new Error(\n `route \"${route.path}\" entries[${index}] must be an object containing only string values`\n );\n }\n\n return entry;\n });\n}\n\nexport async function expandRoutes(\n routes: RouteConfig[]\n): Promise<RouteConfig[]> {\n if (!Array.isArray(routes)) {\n throw new Error('routes must be an array');\n }\n\n const expanded: RouteConfig[] = [];\n\n for (const route of routes) {\n validateRouteShape(route);\n\n if (route.params) {\n expanded.push({ ...route, entries: undefined });\n }\n\n if (!route.entries) {\n if (!route.params) {\n expanded.push(route);\n }\n continue;\n }\n\n const entries = validateEntriesResult(route, await route.entries());\n for (const params of entries) {\n expanded.push({ ...route, params, entries: undefined });\n }\n }\n\n return expanded;\n}\n\n/**\n * Validate routes are properly configured\n */\nexport function validateRoutes(routes: RouteConfig[]): void {\n if (!Array.isArray(routes)) {\n throw new Error('routes must be an array');\n }\n\n const seen = new Set<string>();\n\n for (const route of routes) {\n validateRouteShape(route);\n\n const key = `${route.path}::${JSON.stringify(route.params || {})}`;\n if (seen.has(key)) {\n throw new Error(\n `duplicate route entry detected for path \"${route.path}\"`\n );\n }\n seen.add(key);\n\n if (route.path.includes('{')) {\n const paramNames = Array.from(route.path.matchAll(/\\{([^}]+)\\}/g)).map(\n (m) => m[1]\n );\n if (!route.params) {\n throw new Error(\n `route \"${route.path}\" uses path parameters and requires params`\n );\n }\n for (const name of paramNames) {\n if (!(name in route.params)) {\n throw new Error(\n `route \"${route.path}\" missing required param \"${name}\"`\n );\n }\n }\n }\n }\n}\n"],"mappings":";;AAqBA,SAAS,gBACP,SACA,MACS;CACT,OAAO,OAAO,UAAU,eAAe,KAAK,SAAS,IAAI;AAC3D;;;;;;;;AASA,SAAgB,eACd,QACA,UAAiC,CAAC,GACT;CACzB,MAAM,EAAE,gBAAgB,CAAC,MAAM;CAC/B,MAAM,UAAmC,CAAC;CAE1C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,eAAe,qBAAqB,MAAM,MAAM,MAAM,MAAM;EAClE,MAAM,eACJ,gBAAgB,gBACZ,eACA,MAAM,QAAQ,gBACZ,MAAM,OACN;EAGR,IAAI,cAAc;GAChB,MAAM,OAAO,cAAc;GAC3B,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,IAAI,GACjE,MAAM,IAAI,MACR,mBAAmB,aAAa,2BAA2B,OAAO,MACpE;GAEF,QAAQ,gBAAgB;EAC1B;CAGF;CAEA,OAAO;AACT;AAEA,SAAgB,oBACd,SACA,WACA,cACsB;CACtB,IAAI,gBAAgB,SAAS,YAAY,GACvC,OAAO;EACL,SAAS;EACT,MAAM,QAAQ;CAChB;CAGF,IAAI,gBAAgB,SAAS,SAAS,GACpC,OAAO;EACL,SAAS;EACT,MAAM,QAAQ;CAChB;CAGF,OAAO;EACL,SAAS;EACT,MAAM;CACR;AACF;AAEA,SAAS,eAAe,OAAiD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;CA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C,MAAM,SAAS;GAClB,IAAI,CAAC,MAAM,QACT,SAAS,KAAK,KAAK;GAErB;EACF;EAEA,MAAM,UAAU,sBAAsB,OAAO,MAAM,MAAM,QAAQ,CAAC;EAClE,KAAK,MAAM,UAAU,SACnB,SAAS,KAAK;GAAE,GAAG;GAAO;GAAQ,SAAS;EAAU,CAAC;CAE1D;CAEA,OAAO;AACT;;;;AAKA,SAAgB,eAAe,QAA6B;CAC1D,IAAI,CAAC,MAAM,QAAQ,MAAM,GACvB,MAAM,IAAI,MAAM,yBAAyB;CAG3C,MAAM,uBAAO,IAAI,IAAY;CAE7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,mBAAmB,KAAK;EAExB,MAAM,MAAM,GAAG,MAAM,KAAK,IAAI,KAAK,UAAU,MAAM,UAAU,CAAC,CAAC;EAC/D,IAAI,KAAK,IAAI,GAAG,GACd,MAAM,IAAI,MACR,4CAA4C,MAAM,KAAK,EACzD;EAEF,KAAK,IAAI,GAAG;EAEZ,IAAI,MAAM,KAAK,SAAS,GAAG,GAAG;GAC5B,MAAM,aAAa,MAAM,KAAK,MAAM,KAAK,SAAS,cAAc,CAAC,CAAC,CAAC,KAChE,MAAM,EAAE,EACX;GACA,IAAI,CAAC,MAAM,QACT,MAAM,IAAI,MACR,UAAU,MAAM,KAAK,2CACvB;GAEF,KAAK,MAAM,QAAQ,YACjB,IAAI,EAAE,QAAQ,MAAM,SAClB,MAAM,IAAI,MACR,UAAU,MAAM,KAAK,4BAA4B,KAAK,EACxD;EAGN;CACF;AACF"}
|
package/dist/ssg/types.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ComponentFunction } from "../common/component.js";
|
|
2
|
+
import { DocumentRenderer } from "../common/ssr.js";
|
|
2
3
|
import { RouteAuthMode, RouteHandler, RoutePathParams, RoutePolicy } from "../common/router.js";
|
|
3
4
|
|
|
4
5
|
//#region src/ssg/types.d.ts
|
|
@@ -59,6 +60,8 @@ interface SSGOptions<TRoutes extends readonly RouteConfig[] = RouteConfig[]> {
|
|
|
59
60
|
seed?: number;
|
|
60
61
|
/** Optional override data for resources (route-keyed) */
|
|
61
62
|
dataOverrides?: Record<string, unknown>;
|
|
63
|
+
/** Optional document wrapper for full HTML output */
|
|
64
|
+
document?: DocumentRenderer;
|
|
62
65
|
/** Optional concurrency limit for rendering (default: 10) */
|
|
63
66
|
concurrency?: number;
|
|
64
67
|
/** Preferred render parallelism. `'auto'` resolves from the host machine. */
|
package/dist/ssg/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../src/ssg/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../src/ssg/types.ts"],"mappings":";;;;;KAaY,OAAA;AAAA,KAEA,iBAAA;AAAA,KAEA,iBAAA;AAAA,KAUP,iBAAA,uCAAwD,IAAA,GACzD,MAAA,mBACA,eAAA,CAAgB,IAAA;AAdpB;;;;AAA6B;AAE7B;AAFA,UAsBiB,WAAA;;EAEf,IAAA,EAAM,IAAA;EAtBqB;EAwB3B,OAAA,GAAU,YAAA;EAdU;EAgBpB,SAAA,GAAY,iBAAA;EAhB+C;EAkB3D,KAAA,GAAQ,MAAA;EAhBU;EAkBlB,SAAA;EAlBiB;EAoBjB,IAAA,GAAO,aAAA;EAtBc;EAwBrB,IAAA;EAvBE;EAyBF,UAAA;EAxBkB;EA0BlB,QAAA,YAAoB,WAAA;EA1BE;EA4BtB,MAAA,GAAS,iBAAA,CAAkB,IAAA;EApBD;EAsB1B,gBAAA;EApBM;;;;;;;;;;;;EAiCN,OAAA,SACI,KAAA,CAAM,iBAAA,CAAkB,IAAA,KACxB,OAAA,CAAQ,KAAA,CAAM,iBAAA,CAAkB,IAAA;AAAA;;UAIrB,UAAA,0BACU,WAAA,KAAgB,WAAA;EAL9B;EAQX,MAAA,EAAQ,OAAA;EA3CR;EA6CA,SAAA;EA3CA;EA6CA,IAAA;EA3C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ApCiC;IAsCjC,MAAA,EAAQ,iBAAA,EAlCV;IAoCE,MAAA,EAAQ,iBAAA,EAhCV;IAkCE,OAAA,WA9BF;IAgCE,KAAA;EAAA;AAAA;;UAKa,mBAAA;EAAA,CACd,GAAA;IACC,KAAA;IACA,YAAA;EAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write-static-files.js","names":[],"sources":["../../src/ssg/write-static-files.ts"],"sourcesContent":["/**\n * File I/O for Static Site Generation\n *\n * Uses Node.js fs/path modules to write rendered HTML files to disk.\n * This module is Node-only and not intended for browser builds.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as fsSync from 'node:fs';\nimport * as pathModule from 'node:path';\nimport type { RouteRenderResult } from './types';\n\ninterface WriteStaticFilesOptions {\n concurrency?: number;\n}\n\n/**\n * Write rendered routes to disk\n * Creates outputDir/{route-path}/index.html structure\n */\nexport async function writeStaticFiles(\n results: RouteRenderResult[],\n outputDir: string,\n options: WriteStaticFilesOptions = {}\n): Promise<void> {\n await fs.mkdir(outputDir, { recursive: true });\n\n for (const result of results) {\n if (result.status !== 'removed') {\n continue;\n }\n\n const fullPath = pathModule.join(outputDir, result.filePath);\n if (fsSync.existsSync(fullPath)) {\n await fs.rm(fullPath, { force: true });\n await pruneEmptyDirs(pathModule.dirname(fullPath), outputDir);\n }\n }\n\n const pendingWrites: RouteRenderResult[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const result = results[index];\n if (result.status === 'error') {\n console.warn(`Skipping failed route: ${result.path} - ${result.error}`);\n continue;\n }\n if (result.status === 'success' && result.written) {\n pendingWrites.push(result);\n }\n }\n\n const directories: string[] = [];\n const seenDirectories = new Set<string>();\n for (const result of pendingWrites) {\n const dir = pathModule.dirname(pathModule.join(outputDir, result.filePath));\n if (!seenDirectories.has(dir)) {\n seenDirectories.add(dir);\n directories.push(dir);\n }\n }\n\n for (const dir of directories) {\n await fs.mkdir(dir, { recursive: true });\n }\n\n const concurrency = Math.max(\n 1,\n Math.min(options.concurrency ?? 8, pendingWrites.length || 1)\n );\n let nextIndex = 0;\n\n const worker = async () => {\n while (true) {\n const current = nextIndex;\n nextIndex += 1;\n if (current >= pendingWrites.length) {\n return;\n }\n\n const result = pendingWrites[current];\n const fullPath = pathModule.join(outputDir, result.filePath);\n await fs.writeFile(fullPath, result.html, 'utf8');\n }\n };\n\n await Promise.all(Array.from({ length: concurrency }, () => worker()));\n}\n\n/**\n * Get the output file path for a route\n * E.g., \"/blog/post\" -> \"blog/post\" or \"/\" -> \"\"\n */\nexport { getOutputFilePath } from './route-utils';\n\nasync function pruneEmptyDirs(\n startDir: string,\n rootDir: string\n): Promise<void> {\n let current = startDir;\n const normalizedRoot = pathModule.resolve(rootDir);\n\n while (current.startsWith(normalizedRoot)) {\n if (!fsSync.existsSync(current)) {\n break;\n }\n\n if ((await fs.readdir(current)).length > 0) {\n break;\n }\n\n await fs.rmdir(current);\n if (pathModule.resolve(current) === normalizedRoot) {\n break;\n }\n current = pathModule.dirname(current);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,eAAsB,iBACpB,SACA,WACA,UAAmC,CAAC,GACrB;CACf,MAAM,GAAG,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;CAE7C,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,WAAW,WACpB;EAGF,MAAM,WAAW,WAAW,KAAK,WAAW,OAAO,QAAQ;EAC3D,IAAI,OAAO,WAAW,QAAQ,GAAG;GAC/B,MAAM,GAAG,GAAG,UAAU,EAAE,OAAO,KAAK,CAAC;GACrC,MAAM,eAAe,WAAW,QAAQ,QAAQ,GAAG,SAAS;EAC9D;CACF;CAEA,MAAM,gBAAqC,CAAC;CAC5C,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS,GAAG;EACtD,MAAM,SAAS,QAAQ;EACvB,IAAI,OAAO,WAAW,SAAS;GAC7B,QAAQ,KAAK,0BAA0B,OAAO,KAAK,KAAK,OAAO,OAAO;GACtE;EACF;EACA,IAAI,OAAO,WAAW,aAAa,OAAO,SACxC,cAAc,KAAK,MAAM;CAE7B;CAEA,MAAM,cAAwB,CAAC;CAC/B,MAAM,kCAAkB,IAAI,IAAY;CACxC,KAAK,MAAM,UAAU,eAAe;EAClC,MAAM,MAAM,WAAW,QAAQ,WAAW,KAAK,WAAW,OAAO,QAAQ,CAAC;EAC1E,IAAI,CAAC,gBAAgB,IAAI,GAAG,GAAG;GAC7B,gBAAgB,IAAI,GAAG;GACvB,YAAY,KAAK,GAAG;EACtB;CACF;CAEA,KAAK,MAAM,OAAO,aAChB,MAAM,GAAG,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;CAGzC,MAAM,cAAc,KAAK,IACvB,GACA,KAAK,IAAI,QAAQ,eAAe,GAAG,cAAc,UAAU,CAAC,CAC9D;CACA,IAAI,YAAY;CAEhB,MAAM,SAAS,YAAY;EACzB,OAAO,MAAM;GACX,MAAM,UAAU;GAChB,aAAa;GACb,IAAI,WAAW,cAAc,QAC3B;GAGF,MAAM,SAAS,cAAc;GAC7B,MAAM,WAAW,WAAW,KAAK,WAAW,OAAO,QAAQ;GAC3D,MAAM,GAAG,UAAU,UAAU,OAAO,MAAM,MAAM;EAClD;CACF;CAEA,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,YAAY,SAAS,OAAO,CAAC,CAAC;AACvE;AAQA,eAAe,eACb,UACA,SACe;CACf,IAAI,UAAU;CACd,MAAM,iBAAiB,WAAW,QAAQ,OAAO;CAEjD,OAAO,QAAQ,WAAW,cAAc,GAAG;EACzC,IAAI,CAAC,OAAO,WAAW,OAAO,GAC5B;EAGF,KAAK,MAAM,GAAG,QAAQ,OAAO,
|
|
1
|
+
{"version":3,"file":"write-static-files.js","names":[],"sources":["../../src/ssg/write-static-files.ts"],"sourcesContent":["/**\n * File I/O for Static Site Generation\n *\n * Uses Node.js fs/path modules to write rendered HTML files to disk.\n * This module is Node-only and not intended for browser builds.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as fsSync from 'node:fs';\nimport * as pathModule from 'node:path';\nimport type { RouteRenderResult } from './types';\n\ninterface WriteStaticFilesOptions {\n concurrency?: number;\n}\n\n/**\n * Write rendered routes to disk\n * Creates outputDir/{route-path}/index.html structure\n */\nexport async function writeStaticFiles(\n results: RouteRenderResult[],\n outputDir: string,\n options: WriteStaticFilesOptions = {}\n): Promise<void> {\n await fs.mkdir(outputDir, { recursive: true });\n\n for (const result of results) {\n if (result.status !== 'removed') {\n continue;\n }\n\n const fullPath = pathModule.join(outputDir, result.filePath);\n if (fsSync.existsSync(fullPath)) {\n await fs.rm(fullPath, { force: true });\n await pruneEmptyDirs(pathModule.dirname(fullPath), outputDir);\n }\n }\n\n const pendingWrites: RouteRenderResult[] = [];\n for (let index = 0; index < results.length; index += 1) {\n const result = results[index];\n if (result.status === 'error') {\n console.warn(`Skipping failed route: ${result.path} - ${result.error}`);\n continue;\n }\n if (result.status === 'success' && result.written) {\n pendingWrites.push(result);\n }\n }\n\n const directories: string[] = [];\n const seenDirectories = new Set<string>();\n for (const result of pendingWrites) {\n const dir = pathModule.dirname(pathModule.join(outputDir, result.filePath));\n if (!seenDirectories.has(dir)) {\n seenDirectories.add(dir);\n directories.push(dir);\n }\n }\n\n for (const dir of directories) {\n await fs.mkdir(dir, { recursive: true });\n }\n\n const concurrency = Math.max(\n 1,\n Math.min(options.concurrency ?? 8, pendingWrites.length || 1)\n );\n let nextIndex = 0;\n\n const worker = async () => {\n while (true) {\n const current = nextIndex;\n nextIndex += 1;\n if (current >= pendingWrites.length) {\n return;\n }\n\n const result = pendingWrites[current];\n const fullPath = pathModule.join(outputDir, result.filePath);\n await fs.writeFile(fullPath, result.html, 'utf8');\n }\n };\n\n await Promise.all(Array.from({ length: concurrency }, () => worker()));\n}\n\n/**\n * Get the output file path for a route\n * E.g., \"/blog/post\" -> \"blog/post\" or \"/\" -> \"\"\n */\nexport { getOutputFilePath } from './route-utils';\n\nasync function pruneEmptyDirs(\n startDir: string,\n rootDir: string\n): Promise<void> {\n let current = startDir;\n const normalizedRoot = pathModule.resolve(rootDir);\n\n while (current.startsWith(normalizedRoot)) {\n if (!fsSync.existsSync(current)) {\n break;\n }\n\n if ((await fs.readdir(current)).length > 0) {\n break;\n }\n\n await fs.rmdir(current);\n if (pathModule.resolve(current) === normalizedRoot) {\n break;\n }\n current = pathModule.dirname(current);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,eAAsB,iBACpB,SACA,WACA,UAAmC,CAAC,GACrB;CACf,MAAM,GAAG,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;CAE7C,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,WAAW,WACpB;EAGF,MAAM,WAAW,WAAW,KAAK,WAAW,OAAO,QAAQ;EAC3D,IAAI,OAAO,WAAW,QAAQ,GAAG;GAC/B,MAAM,GAAG,GAAG,UAAU,EAAE,OAAO,KAAK,CAAC;GACrC,MAAM,eAAe,WAAW,QAAQ,QAAQ,GAAG,SAAS;EAC9D;CACF;CAEA,MAAM,gBAAqC,CAAC;CAC5C,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS,GAAG;EACtD,MAAM,SAAS,QAAQ;EACvB,IAAI,OAAO,WAAW,SAAS;GAC7B,QAAQ,KAAK,0BAA0B,OAAO,KAAK,KAAK,OAAO,OAAO;GACtE;EACF;EACA,IAAI,OAAO,WAAW,aAAa,OAAO,SACxC,cAAc,KAAK,MAAM;CAE7B;CAEA,MAAM,cAAwB,CAAC;CAC/B,MAAM,kCAAkB,IAAI,IAAY;CACxC,KAAK,MAAM,UAAU,eAAe;EAClC,MAAM,MAAM,WAAW,QAAQ,WAAW,KAAK,WAAW,OAAO,QAAQ,CAAC;EAC1E,IAAI,CAAC,gBAAgB,IAAI,GAAG,GAAG;GAC7B,gBAAgB,IAAI,GAAG;GACvB,YAAY,KAAK,GAAG;EACtB;CACF;CAEA,KAAK,MAAM,OAAO,aAChB,MAAM,GAAG,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;CAGzC,MAAM,cAAc,KAAK,IACvB,GACA,KAAK,IAAI,QAAQ,eAAe,GAAG,cAAc,UAAU,CAAC,CAC9D;CACA,IAAI,YAAY;CAEhB,MAAM,SAAS,YAAY;EACzB,OAAO,MAAM;GACX,MAAM,UAAU;GAChB,aAAa;GACb,IAAI,WAAW,cAAc,QAC3B;GAGF,MAAM,SAAS,cAAc;GAC7B,MAAM,WAAW,WAAW,KAAK,WAAW,OAAO,QAAQ;GAC3D,MAAM,GAAG,UAAU,UAAU,OAAO,MAAM,MAAM;EAClD;CACF;CAEA,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,YAAY,SAAS,OAAO,CAAC,CAAC;AACvE;AAQA,eAAe,eACb,UACA,SACe;CACf,IAAI,UAAU;CACd,MAAM,iBAAiB,WAAW,QAAQ,OAAO;CAEjD,OAAO,QAAQ,WAAW,cAAc,GAAG;EACzC,IAAI,CAAC,OAAO,WAAW,OAAO,GAC5B;EAGF,KAAK,MAAM,GAAG,QAAQ,OAAO,EAAA,CAAG,SAAS,GACvC;EAGF,MAAM,GAAG,MAAM,OAAO;EACtB,IAAI,WAAW,QAAQ,OAAO,MAAM,gBAClC;EAEF,UAAU,WAAW,QAAQ,OAAO;CACtC;AACF"}
|
package/dist/ssr/context.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
+
import { SSRData } from "../common/ssr.js";
|
|
1
2
|
import { Route, RouteAuthOptions } from "../common/router.js";
|
|
2
3
|
import { SSRDataMissingError } from "../common/ssr-errors.js";
|
|
3
|
-
import { SSRData } from "../common/ssr.js";
|
|
4
|
-
|
|
5
4
|
//#region src/ssr/context.d.ts
|
|
6
5
|
interface RenderContext {
|
|
7
6
|
url: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","names":[],"sources":["../../src/ssr/context.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"context.d.ts","names":[],"sources":["../../src/ssr/context.ts"],"mappings":";;;;UAgBiB,aAAA;EACf,GAAA;EACA,IAAA;EACA,IAAA,GAAO,OAAA;EACP,MAAA,GAAS,MAAA;EACT,MAAA,YAAkB,KAAA;EAClB,SAAA,GAAY,gBAAA;EACZ,MAAA,GAAS,WAAA;EACT,UAAA,GAAa,GAAA;EACb,aAAA,EAAe,KAAA;EAEf,UAAA;EACA,UAAA,EAAY,MAAA;AAAA;AAAA,KAIF,UAAA,GAAa,aAAa;AAAA,iBAoDtB,mBAAA,CACd,IAAA,WACA,IAAA;EACE,GAAA;EACA,IAAA,GAAO,OAAA;EACP,MAAA,GAAS,MAAA;EACT,MAAA,YAAkB,KAAA;EAClB,SAAA,GAAY,gBAAA;EACZ,MAAA,GAAS,WAAA;AAAA,IAEV,aAAA;;;;;iBAsBa,iBAAA,IAAqB,GAAA,EAAK,aAAA,EAAe,EAAA,QAAU,CAAA,GAAI,CAAA;;AAxFnD;AAIpB;;iBAuGgB,gBAAA,IAAoB,aAAa;AAAA,cASpC,aAAA,SAAa,gBAAmB;AAAA,cAChC,cAAA,SAAc,iBAAoB;AAAA,cAClC,oBAAA,SAAoB,gBAAmB;AAAA,iBAEpC,iBAAA,IAAqB,GAAA,EAAK,aAAA,EAAe,EAAA,QAAU,CAAA,GAAI,CAAA;;;;;iBASvD,mBAAA"}
|
package/dist/ssr/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":[],"sources":["../../src/ssr/context.ts"],"sourcesContent":["/**\n * SSR Context Management\n *\n * Provides render-context storage for server-side rendering.\n * Node SSR lazily installs AsyncLocalStorage on first use; browser builds use\n * the fallback stack.\n */\n\nimport { SSRDataMissingError } from './errors';\nimport { clearEscapeCache } from './escape';\n\nexport type { SSRData } from '../common/ssr';\nimport type { SSRData } from '../common/ssr';\nimport type { Route, RouteAuthOptions } from '../common/router';\n\n// Unified per-render context combining SSRContext and RenderContext\nexport interface RenderContext {\n url: string;\n seed: number;\n data?: SSRData;\n params?: Record<string, string>;\n routes?: readonly Route[];\n routeAuth?: RouteAuthOptions;\n signal?: AbortSignal;\n queryCache?: Map<string, unknown>;\n ssrCleanupFns: Array<() => void>;\n // Per-render key state (moved from render-keys.ts globals)\n keyCounter: number;\n renderData: Record<string, unknown> | null;\n}\n\n// Legacy alias for compatibility\nexport type SSRContext = RenderContext;\n\ntype RenderContextAccessor = {\n getStore(): RenderContext | undefined;\n run<R>(store: RenderContext, fn: () => R): R;\n};\n\ntype AsyncHooksModule = {\n AsyncLocalStorage?: new () => RenderContextAccessor;\n};\n\nlet renderContextAccessor: RenderContextAccessor | null = null;\nlet renderContextAccessorInitialized = false;\n\n// Fallback stack for non-Node environments\nlet fallbackStack: RenderContext | null = null;\n\nfunction ensureRenderContextAccessor(): void {\n if (renderContextAccessorInitialized) {\n return;\n }\n\n renderContextAccessorInitialized = true;\n\n if (typeof process === 'undefined' || !process.versions?.node) {\n return;\n }\n\n try {\n // Hide the Node builtin from browser dependency scanners.\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const loadAsyncHooks = new Function(\n 'return require(' + JSON.stringify('async_hooks') + ');'\n ) as () => AsyncHooksModule;\n const asyncHooks = loadAsyncHooks();\n\n if (asyncHooks.AsyncLocalStorage) {\n const asyncLocalStorage = new asyncHooks.AsyncLocalStorage();\n renderContextAccessor = {\n getStore() {\n return asyncLocalStorage.getStore();\n },\n run<R>(store: RenderContext, fn: () => R): R {\n return asyncLocalStorage.run(store, fn);\n },\n };\n }\n } catch {\n // Keep the fallback stack when async_hooks is unavailable.\n }\n}\n\nexport function createRenderContext(\n seed = 12345,\n opts: {\n url?: string;\n data?: SSRData;\n params?: Record<string, string>;\n routes?: readonly Route[];\n routeAuth?: RouteAuthOptions;\n signal?: AbortSignal;\n } = {}\n): RenderContext {\n clearEscapeCache();\n\n return {\n url: opts.url ?? '',\n seed,\n data: opts.data,\n params: opts.params,\n routes: opts.routes,\n routeAuth: opts.routeAuth,\n signal: opts.signal,\n queryCache: new Map<string, unknown>(),\n ssrCleanupFns: [],\n keyCounter: 0,\n renderData: null,\n };\n}\n\n/**\n * Run a function with the given render context.\n * Concurrency-safe in Node.js via AsyncLocalStorage.\n */\nexport function withRenderContext<T>(ctx: RenderContext, fn: () => T): T {\n ensureRenderContextAccessor();\n if (renderContextAccessor) {\n return renderContextAccessor.run(ctx, fn);\n }\n // Fallback: stack-based (not concurrency-safe)\n const prev = fallbackStack;\n fallbackStack = ctx;\n try {\n return fn();\n } finally {\n fallbackStack = prev;\n }\n}\n\n/**\n * Get the current render context.\n * Returns null if not inside a render.\n */\nexport function getRenderContext(): RenderContext | null {\n ensureRenderContextAccessor();\n if (renderContextAccessor) {\n return renderContextAccessor.getStore() ?? null;\n }\n return fallbackStack;\n}\n\n// Legacy API aliases (deprecated, for backwards compatibility)\nexport const getSSRContext = getRenderContext;\nexport const withSSRContext = withRenderContext;\nexport const getCurrentSSRContext = getRenderContext;\n\nexport function runWithSSRContext<T>(ctx: RenderContext, fn: () => T): T {\n // This was a separate path for sync detection; now unified\n return withRenderContext(ctx, fn);\n}\n\n/**\n * Centralized SSR enforcement helper — throws a consistent error when async\n * data is encountered during synchronous SSR.\n */\nexport function throwSSRDataMissing(): never {\n throw new SSRDataMissingError();\n}\n\nexport { SSRDataMissingError };\n"],"mappings":";;;;;;;;;;;AA2CA,IAAI,wBAAsD;AAC1D,IAAI,mCAAmC;AAGvC,IAAI,gBAAsC;AAE1C,SAAS,8BAAoC;CAC3C,IAAI,kCACF;CAGF,mCAAmC;CAEnC,IAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,UAAU,MACvD;CAGF,IAAI;EAMF,MAAM,aAAa,IAHQ,SACzB,oBAAoB,KAAK,UAAU,aAAa,IAAI,IAEnC,
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../../src/ssr/context.ts"],"sourcesContent":["/**\n * SSR Context Management\n *\n * Provides render-context storage for server-side rendering.\n * Node SSR lazily installs AsyncLocalStorage on first use; browser builds use\n * the fallback stack.\n */\n\nimport { SSRDataMissingError } from './errors';\nimport { clearEscapeCache } from './escape';\n\nexport type { SSRData } from '../common/ssr';\nimport type { SSRData } from '../common/ssr';\nimport type { Route, RouteAuthOptions } from '../common/router';\n\n// Unified per-render context combining SSRContext and RenderContext\nexport interface RenderContext {\n url: string;\n seed: number;\n data?: SSRData;\n params?: Record<string, string>;\n routes?: readonly Route[];\n routeAuth?: RouteAuthOptions;\n signal?: AbortSignal;\n queryCache?: Map<string, unknown>;\n ssrCleanupFns: Array<() => void>;\n // Per-render key state (moved from render-keys.ts globals)\n keyCounter: number;\n renderData: Record<string, unknown> | null;\n}\n\n// Legacy alias for compatibility\nexport type SSRContext = RenderContext;\n\ntype RenderContextAccessor = {\n getStore(): RenderContext | undefined;\n run<R>(store: RenderContext, fn: () => R): R;\n};\n\ntype AsyncHooksModule = {\n AsyncLocalStorage?: new () => RenderContextAccessor;\n};\n\nlet renderContextAccessor: RenderContextAccessor | null = null;\nlet renderContextAccessorInitialized = false;\n\n// Fallback stack for non-Node environments\nlet fallbackStack: RenderContext | null = null;\n\nfunction ensureRenderContextAccessor(): void {\n if (renderContextAccessorInitialized) {\n return;\n }\n\n renderContextAccessorInitialized = true;\n\n if (typeof process === 'undefined' || !process.versions?.node) {\n return;\n }\n\n try {\n // Hide the Node builtin from browser dependency scanners.\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const loadAsyncHooks = new Function(\n 'return require(' + JSON.stringify('async_hooks') + ');'\n ) as () => AsyncHooksModule;\n const asyncHooks = loadAsyncHooks();\n\n if (asyncHooks.AsyncLocalStorage) {\n const asyncLocalStorage = new asyncHooks.AsyncLocalStorage();\n renderContextAccessor = {\n getStore() {\n return asyncLocalStorage.getStore();\n },\n run<R>(store: RenderContext, fn: () => R): R {\n return asyncLocalStorage.run(store, fn);\n },\n };\n }\n } catch {\n // Keep the fallback stack when async_hooks is unavailable.\n }\n}\n\nexport function createRenderContext(\n seed = 12345,\n opts: {\n url?: string;\n data?: SSRData;\n params?: Record<string, string>;\n routes?: readonly Route[];\n routeAuth?: RouteAuthOptions;\n signal?: AbortSignal;\n } = {}\n): RenderContext {\n clearEscapeCache();\n\n return {\n url: opts.url ?? '',\n seed,\n data: opts.data,\n params: opts.params,\n routes: opts.routes,\n routeAuth: opts.routeAuth,\n signal: opts.signal,\n queryCache: new Map<string, unknown>(),\n ssrCleanupFns: [],\n keyCounter: 0,\n renderData: null,\n };\n}\n\n/**\n * Run a function with the given render context.\n * Concurrency-safe in Node.js via AsyncLocalStorage.\n */\nexport function withRenderContext<T>(ctx: RenderContext, fn: () => T): T {\n ensureRenderContextAccessor();\n if (renderContextAccessor) {\n return renderContextAccessor.run(ctx, fn);\n }\n // Fallback: stack-based (not concurrency-safe)\n const prev = fallbackStack;\n fallbackStack = ctx;\n try {\n return fn();\n } finally {\n fallbackStack = prev;\n }\n}\n\n/**\n * Get the current render context.\n * Returns null if not inside a render.\n */\nexport function getRenderContext(): RenderContext | null {\n ensureRenderContextAccessor();\n if (renderContextAccessor) {\n return renderContextAccessor.getStore() ?? null;\n }\n return fallbackStack;\n}\n\n// Legacy API aliases (deprecated, for backwards compatibility)\nexport const getSSRContext = getRenderContext;\nexport const withSSRContext = withRenderContext;\nexport const getCurrentSSRContext = getRenderContext;\n\nexport function runWithSSRContext<T>(ctx: RenderContext, fn: () => T): T {\n // This was a separate path for sync detection; now unified\n return withRenderContext(ctx, fn);\n}\n\n/**\n * Centralized SSR enforcement helper — throws a consistent error when async\n * data is encountered during synchronous SSR.\n */\nexport function throwSSRDataMissing(): never {\n throw new SSRDataMissingError();\n}\n\nexport { SSRDataMissingError };\n"],"mappings":";;;;;;;;;;;AA2CA,IAAI,wBAAsD;AAC1D,IAAI,mCAAmC;AAGvC,IAAI,gBAAsC;AAE1C,SAAS,8BAAoC;CAC3C,IAAI,kCACF;CAGF,mCAAmC;CAEnC,IAAI,OAAO,YAAY,eAAe,CAAC,QAAQ,UAAU,MACvD;CAGF,IAAI;EAMF,MAAM,aAAa,IAHQ,SACzB,oBAAoB,KAAK,UAAU,aAAa,IAAI,IAEnC,CAAA,CAAe;EAElC,IAAI,WAAW,mBAAmB;GAChC,MAAM,oBAAoB,IAAI,WAAW,kBAAkB;GAC3D,wBAAwB;IACtB,WAAW;KACT,OAAO,kBAAkB,SAAS;IACpC;IACA,IAAO,OAAsB,IAAgB;KAC3C,OAAO,kBAAkB,IAAI,OAAO,EAAE;IACxC;GACF;EACF;CACF,QAAQ,CAER;AACF;AAEA,SAAgB,oBACd,OAAO,OACP,OAOI,CAAC,GACU;CACf,iBAAiB;CAEjB,OAAO;EACL,KAAK,KAAK,OAAO;EACjB;EACA,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,QAAQ,KAAK;EACb,WAAW,KAAK;EAChB,QAAQ,KAAK;EACb,4BAAY,IAAI,IAAqB;EACrC,eAAe,CAAC;EAChB,YAAY;EACZ,YAAY;CACd;AACF;;;;;AAMA,SAAgB,kBAAqB,KAAoB,IAAgB;CACvE,4BAA4B;CAC5B,IAAI,uBACF,OAAO,sBAAsB,IAAI,KAAK,EAAE;CAG1C,MAAM,OAAO;CACb,gBAAgB;CAChB,IAAI;EACF,OAAO,GAAG;CACZ,UAAU;EACR,gBAAgB;CAClB;AACF;;;;;AAMA,SAAgB,mBAAyC;CACvD,4BAA4B;CAC5B,IAAI,uBACF,OAAO,sBAAsB,SAAS,KAAK;CAE7C,OAAO;AACT;;;;;AAgBA,SAAgB,sBAA6B;CAC3C,MAAM,IAAI,oBAAoB;AAChC"}
|
package/dist/ssr/escape.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"escape.js","names":[],"sources":["../../src/ssr/escape.ts"],"sourcesContent":["/**\n * HTML escaping utilities for SSR\n *\n * Centralizes text and attribute escaping to avoid duplication\n * between sync and streaming SSR renderers.\n */\n\n// HTML5 void elements that don't have closing tags\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Escape cache for common values (bounded and clearable for long-running servers)\nconst escapeCache = new Map<string, string>();\nconst MAX_CACHE_SIZE = 256;\n\nconst _TEXT_ESCAPE_RE = /[&<>]/g;\n\nconst CSS_UNSAFE_RE = /[{}<>\\\\]/g;\nconst CSS_URI_SCHEME_RE = /(?:^|[\\s(,])([a-z][a-z0-9+.-]*):/i;\nconst CSS_FUNCTION_NAME_RE = /([a-z-][a-z0-9-]*)\\s*\\(/gi;\n\nconst CSS_ALLOWED_FUNCTIONS = new Set([\n 'var',\n 'calc',\n 'min',\n 'max',\n 'clamp',\n 'rgb',\n 'rgba',\n 'hsl',\n 'hsla',\n 'lab',\n 'lch',\n 'oklab',\n 'oklch',\n 'color',\n 'color-mix',\n 'translate',\n 'translatex',\n 'translatey',\n 'translatez',\n 'scale',\n 'scalex',\n 'scaley',\n 'scalez',\n 'rotate',\n 'rotatex',\n 'rotatey',\n 'rotatez',\n 'skew',\n 'skewx',\n 'skewy',\n 'matrix',\n 'matrix3d',\n 'linear-gradient',\n 'radial-gradient',\n 'conic-gradient',\n 'repeating-linear-gradient',\n 'repeating-radial-gradient',\n 'repeating-conic-gradient',\n 'cubic-bezier',\n 'steps',\n]);\n\nconst STYLE_PROP_CACHE = new Map<string, string>();\nconst MAX_STYLE_PROP_CACHE_SIZE = 512;\n\n// Pre-compute escape map functions for faster replacement\nconst _textEscapeMap = (ch: string): string => {\n const code = ch.charCodeAt(0);\n if (code === 38) return '&'; // &\n if (code === 60) return '<'; // <\n if (code === 62) return '>'; // >\n return ch;\n};\n\nfunction toKebabCached(prop: string): string {\n const cached = STYLE_PROP_CACHE.get(prop);\n if (cached !== undefined) return cached;\n const kebab = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n if (STYLE_PROP_CACHE.size < MAX_STYLE_PROP_CACHE_SIZE) {\n STYLE_PROP_CACHE.set(prop, kebab);\n }\n return kebab;\n}\n\n/**\n * Clear the escape cache. Call between SSR requests in long-running servers\n * to prevent memory buildup from unique strings.\n */\nexport function clearEscapeCache(): void {\n escapeCache.clear();\n}\n\n/**\n * Fast check if a string needs text escaping.\n * Used to skip the full escape call when not needed.\n */\nexport function needsEscapeText(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n if (ch === 38 || ch === 60 || ch === 62) return true;\n }\n return false;\n}\n\n/**\n * Fast check if a string needs attribute escaping.\n * Checks for & \" ' < > characters.\n */\nexport function needsEscapeAttr(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const ch = value.charCodeAt(i);\n // & \" ' < >\n if (ch === 38 || ch === 34 || ch === 39 || ch === 60 || ch === 62) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Escape HTML special characters in text content\n * Fast-path: cache first, then scan-then-escape for new strings\n */\nexport function escapeText(text: string): string {\n // Only use cache for short strings (likely to be repeated)\n const useCache = text.length <= 64;\n\n if (useCache) {\n const cached = escapeCache.get(text);\n if (cached !== undefined) return cached;\n }\n\n // Fast path: check if escaping needed\n if (!needsEscapeText(text)) {\n if (useCache && escapeCache.size < MAX_CACHE_SIZE) {\n escapeCache.set(text, text);\n }\n return text;\n }\n\n // Single-pass scan-and-build: avoids 3 separate regex passes\n let escaped = '';\n let lastIndex = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n let entity: string;\n if (ch === 38) entity = '&';\n else if (ch === 60) entity = '<';\n else if (ch === 62) entity = '>';\n else continue;\n escaped += text.slice(lastIndex, i) + entity;\n lastIndex = i + 1;\n }\n const result = escaped + text.slice(lastIndex);\n\n if (useCache && escapeCache.size < MAX_CACHE_SIZE) {\n escapeCache.set(text, result);\n }\n return result;\n}\n\n/**\n * Escape HTML special characters in attribute values.\n * Single-pass scan: returns the original string unchanged when no special\n * characters are found, so callers can drop separate needsEscapeAttr checks.\n */\nexport function escapeAttr(value: string): string {\n let escaped = '';\n let lastIndex = 0;\n for (let i = 0; i < value.length; i++) {\n const ch = value.charCodeAt(i);\n let entity: string;\n if (ch === 38) entity = '&';\n else if (ch === 34) entity = '"';\n else if (ch === 39) entity = ''';\n else if (ch === 60) entity = '<';\n else if (ch === 62) entity = '>';\n else continue;\n escaped += value.slice(lastIndex, i) + entity;\n lastIndex = i + 1;\n }\n // Return original reference when nothing needed escaping (no allocation)\n return lastIndex === 0 ? value : escaped + value.slice(lastIndex);\n}\n\n/**\n * Escape CSS value to prevent injection attacks.\n * Removes characters that could break out of CSS context.\n */\nfunction escapeCssValue(value: string): string {\n const str = String(value);\n\n if (CSS_URI_SCHEME_RE.test(str)) {\n return '';\n }\n\n if (str.includes('(')) {\n for (const match of str.matchAll(CSS_FUNCTION_NAME_RE)) {\n if (!CSS_ALLOWED_FUNCTIONS.has(match[1].toLowerCase())) {\n return '';\n }\n }\n }\n\n // Remove characters that could break out of CSS value context\n return str.replace(CSS_UNSAFE_RE, '');\n}\n\n/**\n * Convert style object to CSS string with value escaping\n * Optimized to avoid Object.entries allocation\n */\nexport function styleObjToCss(value: unknown): string | null {\n if (!value || typeof value !== 'object') return null;\n\n const styleObj = value as Record<string, unknown>;\n let result = '';\n\n for (const k in styleObj) {\n const v = styleObj[k];\n if (v === null || v === undefined || v === false) continue;\n\n const prop = toKebabCached(k);\n const safeValue = escapeCssValue(String(v));\n if (safeValue) {\n result += `${prop}:${safeValue};`;\n }\n }\n\n return result || null;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,gBAAgB,IAAI,IAAI;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,8BAAc,IAAI,IAAoB;AAC5C,MAAM,iBAAiB;AAIvB,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAE7B,MAAM,wBAAwB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CAC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AGA,IAAI,UAAU;CACd,IAAI,YAAY;CAChB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,KAAK,KAAK,WAAW,CAAC;EAC5B,IAAI;EACJ,IAAI,OAAO,IAAI,SAAS;OACnB,IAAI,OAAO,IAAI,SAAS;OACxB,IAAI,OAAO,IAAI,SAAS;OACxB;EACL,WAAW,KAAK,MAAM,WAAW,CAAC,IAAI;EACtC,YAAY,IAAI;CAClB;CACA,MAAM,SAAS,UAAU,KAAK,MAAM,SAAS;CAE7C,IAAI,YAAY,YAAY,OAAO,gBACjC,YAAY,IAAI,MAAM,MAAM;CAE9B,OAAO;AACT;;;;;;AAOA,SAAgB,WAAW,OAAuB;CAChD,IAAI,UAAU;CACd,IAAI,YAAY;CAChB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,KAAK,MAAM,WAAW,CAAC;EAC7B,IAAI;EACJ,IAAI,OAAO,IAAI,SAAS;OACnB,IAAI,OAAO,IAAI,SAAS;OACxB,IAAI,OAAO,IAAI,SAAS;OACxB,IAAI,OAAO,IAAI,SAAS;OACxB,IAAI,OAAO,IAAI,SAAS;OACxB;EACL,WAAW,MAAM,MAAM,WAAW,CAAC,IAAI;EACvC,YAAY,IAAI;CAClB;CAEA,OAAO,cAAc,IAAI,QAAQ,UAAU,MAAM,MAAM,SAAS;AAClE;;;;;AAMA,SAAS,eAAe,OAAuB;CAC7C,MAAM,MAAM,OAAO,KAAK;CAExB,IAAI,kBAAkB,KAAK,GAAG,GAC5B,OAAO;CAGT,IAAI,IAAI,SAAS,GAAG,GAClB;OAAK,MAAM,SAAS,IAAI,SAAS,oBAAoB,GACnD,IAAI,CAAC,sBAAsB,IAAI,MAAM,
|
|
1
|
+
{"version":3,"file":"escape.js","names":[],"sources":["../../src/ssr/escape.ts"],"sourcesContent":["/**\n * HTML escaping utilities for SSR\n *\n * Centralizes text and attribute escaping to avoid duplication\n * between sync and streaming SSR renderers.\n */\n\n// HTML5 void elements that don't have closing tags\nexport const VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Escape cache for common values (bounded and clearable for long-running servers)\nconst escapeCache = new Map<string, string>();\nconst MAX_CACHE_SIZE = 256;\n\nconst _TEXT_ESCAPE_RE = /[&<>]/g;\n\nconst CSS_UNSAFE_RE = /[{}<>\\\\]/g;\nconst CSS_URI_SCHEME_RE = /(?:^|[\\s(,])([a-z][a-z0-9+.-]*):/i;\nconst CSS_FUNCTION_NAME_RE = /([a-z-][a-z0-9-]*)\\s*\\(/gi;\n\nconst CSS_ALLOWED_FUNCTIONS = new Set([\n 'var',\n 'calc',\n 'min',\n 'max',\n 'clamp',\n 'rgb',\n 'rgba',\n 'hsl',\n 'hsla',\n 'lab',\n 'lch',\n 'oklab',\n 'oklch',\n 'color',\n 'color-mix',\n 'translate',\n 'translatex',\n 'translatey',\n 'translatez',\n 'scale',\n 'scalex',\n 'scaley',\n 'scalez',\n 'rotate',\n 'rotatex',\n 'rotatey',\n 'rotatez',\n 'skew',\n 'skewx',\n 'skewy',\n 'matrix',\n 'matrix3d',\n 'linear-gradient',\n 'radial-gradient',\n 'conic-gradient',\n 'repeating-linear-gradient',\n 'repeating-radial-gradient',\n 'repeating-conic-gradient',\n 'cubic-bezier',\n 'steps',\n]);\n\nconst STYLE_PROP_CACHE = new Map<string, string>();\nconst MAX_STYLE_PROP_CACHE_SIZE = 512;\n\n// Pre-compute escape map functions for faster replacement\nconst _textEscapeMap = (ch: string): string => {\n const code = ch.charCodeAt(0);\n if (code === 38) return '&'; // &\n if (code === 60) return '<'; // <\n if (code === 62) return '>'; // >\n return ch;\n};\n\nfunction toKebabCached(prop: string): string {\n const cached = STYLE_PROP_CACHE.get(prop);\n if (cached !== undefined) return cached;\n const kebab = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n if (STYLE_PROP_CACHE.size < MAX_STYLE_PROP_CACHE_SIZE) {\n STYLE_PROP_CACHE.set(prop, kebab);\n }\n return kebab;\n}\n\n/**\n * Clear the escape cache. Call between SSR requests in long-running servers\n * to prevent memory buildup from unique strings.\n */\nexport function clearEscapeCache(): void {\n escapeCache.clear();\n}\n\n/**\n * Fast check if a string needs text escaping.\n * Used to skip the full escape call when not needed.\n */\nexport function needsEscapeText(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n if (ch === 38 || ch === 60 || ch === 62) return true;\n }\n return false;\n}\n\n/**\n * Fast check if a string needs attribute escaping.\n * Checks for & \" ' < > characters.\n */\nexport function needsEscapeAttr(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const ch = value.charCodeAt(i);\n // & \" ' < >\n if (ch === 38 || ch === 34 || ch === 39 || ch === 60 || ch === 62) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Escape HTML special characters in text content\n * Fast-path: cache first, then scan-then-escape for new strings\n */\nexport function escapeText(text: string): string {\n // Only use cache for short strings (likely to be repeated)\n const useCache = text.length <= 64;\n\n if (useCache) {\n const cached = escapeCache.get(text);\n if (cached !== undefined) return cached;\n }\n\n // Fast path: check if escaping needed\n if (!needsEscapeText(text)) {\n if (useCache && escapeCache.size < MAX_CACHE_SIZE) {\n escapeCache.set(text, text);\n }\n return text;\n }\n\n // Single-pass scan-and-build: avoids 3 separate regex passes\n let escaped = '';\n let lastIndex = 0;\n for (let i = 0; i < text.length; i++) {\n const ch = text.charCodeAt(i);\n let entity: string;\n if (ch === 38) entity = '&';\n else if (ch === 60) entity = '<';\n else if (ch === 62) entity = '>';\n else continue;\n escaped += text.slice(lastIndex, i) + entity;\n lastIndex = i + 1;\n }\n const result = escaped + text.slice(lastIndex);\n\n if (useCache && escapeCache.size < MAX_CACHE_SIZE) {\n escapeCache.set(text, result);\n }\n return result;\n}\n\n/**\n * Escape HTML special characters in attribute values.\n * Single-pass scan: returns the original string unchanged when no special\n * characters are found, so callers can drop separate needsEscapeAttr checks.\n */\nexport function escapeAttr(value: string): string {\n let escaped = '';\n let lastIndex = 0;\n for (let i = 0; i < value.length; i++) {\n const ch = value.charCodeAt(i);\n let entity: string;\n if (ch === 38) entity = '&';\n else if (ch === 34) entity = '"';\n else if (ch === 39) entity = ''';\n else if (ch === 60) entity = '<';\n else if (ch === 62) entity = '>';\n else continue;\n escaped += value.slice(lastIndex, i) + entity;\n lastIndex = i + 1;\n }\n // Return original reference when nothing needed escaping (no allocation)\n return lastIndex === 0 ? value : escaped + value.slice(lastIndex);\n}\n\n/**\n * Escape CSS value to prevent injection attacks.\n * Removes characters that could break out of CSS context.\n */\nfunction escapeCssValue(value: string): string {\n const str = String(value);\n\n if (CSS_URI_SCHEME_RE.test(str)) {\n return '';\n }\n\n if (str.includes('(')) {\n for (const match of str.matchAll(CSS_FUNCTION_NAME_RE)) {\n if (!CSS_ALLOWED_FUNCTIONS.has(match[1].toLowerCase())) {\n return '';\n }\n }\n }\n\n // Remove characters that could break out of CSS value context\n return str.replace(CSS_UNSAFE_RE, '');\n}\n\n/**\n * Convert style object to CSS string with value escaping\n * Optimized to avoid Object.entries allocation\n */\nexport function styleObjToCss(value: unknown): string | null {\n if (!value || typeof value !== 'object') return null;\n\n const styleObj = value as Record<string, unknown>;\n let result = '';\n\n for (const k in styleObj) {\n const v = styleObj[k];\n if (v === null || v === undefined || v === false) continue;\n\n const prop = toKebabCached(k);\n const safeValue = escapeCssValue(String(v));\n if (safeValue) {\n result += `${prop}:${safeValue};`;\n }\n }\n\n return result || null;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,gBAAgB,IAAI,IAAI;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,8BAAc,IAAI,IAAoB;AAC5C,MAAM,iBAAiB;AAIvB,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;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I,QAAQ,eAAe,EAAE;AACtC;;;;;AAMA,SAAgB,cAAc,OAA+B;CAC3D,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAEhD,MAAM,WAAW;CACjB,IAAI,SAAS;CAEb,KAAK,MAAM,KAAK,UAAU;EACxB,MAAM,IAAI,SAAS;EACnB,IAAI,MAAM,QAAQ,MAAM,UAAa,MAAM,OAAO;EAElD,MAAM,OAAO,cAAc,CAAC;EAC5B,MAAM,YAAY,eAAe,OAAO,CAAC,CAAC;EAC1C,IAAI,WACF,UAAU,GAAG,KAAK,GAAG,UAAU;CAEnC;CAEA,OAAO,UAAU;AACnB"}
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { JSXElement } from "../common/jsx.js";
|
|
2
|
+
import { DocumentRenderArgs, DocumentRenderContext, DocumentRenderer, SSRData } from "../common/ssr.js";
|
|
2
3
|
import { RouteAuthOptions, RouteHandler, RouteManifest, RouteRequestResult } from "../common/router.js";
|
|
3
4
|
import { SSRDataMissingError } from "../common/ssr-errors.js";
|
|
4
|
-
import { SSRData } from "../common/ssr.js";
|
|
5
5
|
import { SSRComponent, VNode } from "./types.js";
|
|
6
6
|
import { renderResolvedToStringSync } from "./render-resolved.js";
|
|
7
7
|
|
|
@@ -41,21 +41,20 @@ type SSRRoute = {
|
|
|
41
41
|
handler: RouteHandler;
|
|
42
42
|
namespace?: string;
|
|
43
43
|
};
|
|
44
|
-
|
|
45
|
-
declare function renderToString(opts: {
|
|
46
|
-
url: string;
|
|
47
|
-
routes: SSRRoute[];
|
|
48
|
-
seed?: number;
|
|
49
|
-
data?: SSRData;
|
|
50
|
-
}): string;
|
|
51
|
-
declare function renderToStream(opts: {
|
|
44
|
+
type RouteRenderOptions = {
|
|
52
45
|
url: string;
|
|
53
46
|
routes: SSRRoute[];
|
|
54
47
|
seed?: number;
|
|
55
48
|
data?: SSRData;
|
|
49
|
+
document?: DocumentRenderer;
|
|
50
|
+
};
|
|
51
|
+
type RouteStreamOptions = RouteRenderOptions & {
|
|
56
52
|
onChunk(html: string): void;
|
|
57
53
|
onComplete(): void;
|
|
58
|
-
}
|
|
54
|
+
};
|
|
55
|
+
declare function renderToString(component: (props?: Record<string, unknown>) => VNode | JSXElement | string | number | null): string;
|
|
56
|
+
declare function renderToString(opts: RouteRenderOptions): string;
|
|
57
|
+
declare function renderToStream(opts: RouteStreamOptions): void;
|
|
59
58
|
//#endregion
|
|
60
|
-
export { type SSRComponent, SSRDataMissingError, SSRRoute, type VNode, renderResolvedToStringSync, renderToStream, renderToString, renderToStringSync, resolveRequest };
|
|
59
|
+
export { type DocumentRenderArgs, type DocumentRenderContext, type DocumentRenderer, type SSRComponent, SSRDataMissingError, SSRRoute, type VNode, renderResolvedToStringSync, renderToStream, renderToString, renderToStringSync, resolveRequest };
|
|
61
60
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/ssr/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ssr/index.ts"],"mappings":";;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/ssr/index.ts"],"mappings":";;;;;;;;;;;;;iBAosCgB,kBAAA,CACd,SAAA,GACE,KAAA,GAAQ,MAAA,sBACL,KAAA,GAAQ,UAAA,iDACb,KAAA,GAAQ,MAAA,mBACR,OAAA;EAAY,IAAA;EAAe,IAAA,GAAO,OAAA;AAAA;AAAA,iBAgCd,cAAA,CACpB,IAAA;EAEM,GAAA;EACA,QAAA,EAAU,aAAA;EACV,MAAA,GAAS,KAAA;IACP,IAAA;IACA,OAAA,EAAS,YAAA;IACT,SAAA;EAAA;EAEF,IAAA,GAAO,gBAAA;EACP,MAAA,GAAS,WAAA;AAAA;EAGT,GAAA;EACA,QAAA,GAAW,aAAA;EACX,MAAA,EAAQ,KAAA;IACN,IAAA;IACA,OAAA,EAAS,YAAA;IACT,SAAA;EAAA;EAEF,IAAA,GAAO,gBAAA;EACP,MAAA,GAAS,WAAA;AAAA,IAEd,OAAA,CAAQ,kBAAA;AAAA,KAsCC,QAAA;EACV,IAAA;EACA,OAAA,EAAS,YAAY;EACrB,SAAA;AAAA;AAAA,KAGG,kBAAA;EACH,GAAA;EACA,MAAA,EAAQ,QAAA;EACR,IAAA;EACA,IAAA,GAAO,OAAA;EACP,QAAA,GAAW,gBAAA;AAAA;AAAA,KAGR,kBAAA,GAAqB,kBAAkB;EAC1C,OAAA,CAAQ,IAAA;EACR,UAAA;AAAA;AAAA,iBAiGc,cAAA,CACd,SAAA,GACE,KAAA,GAAQ,MAAA,sBACL,KAAA,GAAQ,UAAA;AAAA,iBAEC,cAAA,CAAe,IAAwB,EAAlB,kBAAkB;AAAA,iBAiBvC,cAAA,CAAe,IAAwB,EAAlB,kBAAkB"}
|
package/dist/ssr/index.js
CHANGED
|
@@ -10,10 +10,10 @@ import { evaluateCaseState, evaluateShowState } from "../runtime/control.js";
|
|
|
10
10
|
import { SSRDataMissingError } from "../common/ssr-errors.js";
|
|
11
11
|
import { VOID_ELEMENTS, escapeText, styleObjToCss } from "./escape.js";
|
|
12
12
|
import { createRenderContext, getRenderContext, throwSSRDataMissing, withRenderContext } from "./context.js";
|
|
13
|
-
import { resolveRouteFromRoutes, resolveRouteRequest } from "../router/route.js";
|
|
13
|
+
import { _resolveRouteMatchFromRoutes, resolveRouteFromRoutes, resolveRouteRequest } from "../router/route.js";
|
|
14
14
|
import "../jsx/index.js";
|
|
15
15
|
import { DefaultPortal, disposeDefaultPortalScope } from "../foundations/structures/portal.js";
|
|
16
|
-
import { SSR_RENDER_DATA_ATTR } from "../common/ssr.js";
|
|
16
|
+
import { SSR_RENDER_DATA_ATTR, renderDocument } from "../common/ssr.js";
|
|
17
17
|
import { getCurrentRenderData, getNextKey, startRenderPhase, stopRenderPhase } from "./render-keys.js";
|
|
18
18
|
import { installSSRBridge } from "../runtime/ssr-bridge.js";
|
|
19
19
|
import { renderAttrs, renderAttrsDirect } from "./attrs.js";
|
|
@@ -65,24 +65,35 @@ function popSSRStrictPurityGuard() {
|
|
|
65
65
|
/**
|
|
66
66
|
* Synchronous rendering helpers (used for strictly synchronous SSR)
|
|
67
67
|
*/
|
|
68
|
-
function
|
|
69
|
-
if (typeof
|
|
70
|
-
if (typeof
|
|
71
|
-
if (
|
|
72
|
-
if (
|
|
68
|
+
function renderRenderableSync(value, ctx) {
|
|
69
|
+
if (typeof value === "string") return escapeText(value);
|
|
70
|
+
if (typeof value === "number") return escapeText(String(value));
|
|
71
|
+
if (value === null || value === void 0 || value === false) return "";
|
|
72
|
+
if (Array.isArray(value)) return renderChildrenSync(value, ctx);
|
|
73
|
+
if (value && typeof value === "object" && "type" in value) return renderNodeSync(value, ctx);
|
|
73
74
|
return "";
|
|
74
75
|
}
|
|
75
|
-
function
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
function renderChildSync(child, ctx) {
|
|
77
|
+
return renderRenderableSync(child, ctx);
|
|
78
|
+
}
|
|
79
|
+
function renderRenderableSyncToSink(value, sink, ctx) {
|
|
80
|
+
if (value === null || value === void 0 || value === false) return;
|
|
81
|
+
if (typeof value === "string") {
|
|
82
|
+
sink.write(escapeText(value));
|
|
79
83
|
return;
|
|
80
84
|
}
|
|
81
|
-
if (typeof
|
|
82
|
-
sink.write(escapeText(String(
|
|
85
|
+
if (typeof value === "number") {
|
|
86
|
+
sink.write(escapeText(String(value)));
|
|
83
87
|
return;
|
|
84
88
|
}
|
|
85
|
-
if (
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
renderChildrenSyncToSink(value, sink, ctx);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (value && typeof value === "object" && "type" in value) renderNodeSyncToSink(value, sink, ctx);
|
|
94
|
+
}
|
|
95
|
+
function renderChildSyncToSink(child, sink, ctx) {
|
|
96
|
+
renderRenderableSyncToSink(child, sink, ctx);
|
|
86
97
|
}
|
|
87
98
|
function serializeHydrationRenderData(data) {
|
|
88
99
|
if (!data || Object.keys(data).length === 0) return "";
|
|
@@ -195,19 +206,7 @@ function evaluateControlBoundaryChildren(node) {
|
|
|
195
206
|
function renderChildrenSyncToSink(children, sink, ctx) {
|
|
196
207
|
if (!children || !Array.isArray(children) || children.length === 0) return;
|
|
197
208
|
if (children.length >= 32) {
|
|
198
|
-
for (let i = 0; i < children.length; i++)
|
|
199
|
-
const child = children[i];
|
|
200
|
-
if (child === null || child === void 0 || child === false) continue;
|
|
201
|
-
if (typeof child === "string") {
|
|
202
|
-
sink.write(escapeText(child));
|
|
203
|
-
continue;
|
|
204
|
-
}
|
|
205
|
-
if (typeof child === "number") {
|
|
206
|
-
sink.write(escapeText(String(child)));
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
if (child && typeof child === "object" && "type" in child) renderNodeSyncToSink(child, sink, ctx);
|
|
210
|
-
}
|
|
209
|
+
for (let i = 0; i < children.length; i++) renderRenderableSyncToSink(children[i], sink, ctx);
|
|
211
210
|
return;
|
|
212
211
|
}
|
|
213
212
|
for (let i = 0; i < children.length; i++) renderChildSyncToSink(children[i], sink, ctx);
|
|
@@ -238,14 +237,10 @@ function renderNodeSync(node, ctx) {
|
|
|
238
237
|
if (__SSR_DEBUG) try {
|
|
239
238
|
logger.warn("[SSR] renderNodeSync type:", typeof type, type);
|
|
240
239
|
} catch {}
|
|
241
|
-
if (typeof type === "function")
|
|
242
|
-
const result = executeComponentSync(type, props, ctx);
|
|
243
|
-
if (isPromiseLike(result)) throwSSRDataMissing();
|
|
244
|
-
return renderNodeSync(result, ctx);
|
|
245
|
-
}
|
|
240
|
+
if (typeof type === "function") return renderRenderableSync(inheritRenderableKey(node, executeComponentSync(type, props, ctx)), ctx);
|
|
246
241
|
if (typeof type === "symbol") {
|
|
247
242
|
if (type === Fragment) {
|
|
248
|
-
const childrenArr =
|
|
243
|
+
const childrenArr = getRenderableChildren(node);
|
|
249
244
|
/* istanbul ignore if - dev-only debug */
|
|
250
245
|
if (__SSR_DEBUG) try {
|
|
251
246
|
logger.warn("[SSR] fragment children length:", childrenArr?.length);
|
|
@@ -283,19 +278,19 @@ function renderNodeSync(node, ctx) {
|
|
|
283
278
|
if (maybeDangerous !== void 0 && maybeDangerous !== null) {
|
|
284
279
|
const { attrs, dangerousHtml } = renderAttrs(props, { returnDangerousHtml: true });
|
|
285
280
|
if (dangerousHtml !== void 0) return `<${typeStr}${attrs}>${dangerousHtml}</${typeStr}>`;
|
|
286
|
-
return `<${typeStr}${attrs}>${renderChildrenSync(node
|
|
281
|
+
return `<${typeStr}${attrs}>${renderChildrenSync(getRenderableChildren(node), ctx)}</${typeStr}>`;
|
|
287
282
|
}
|
|
288
|
-
return `<${typeStr}${renderAttrs(props)}>${renderChildrenSync(node
|
|
283
|
+
return `<${typeStr}${renderAttrs(props)}>${renderChildrenSync(getRenderableChildren(node), ctx)}</${typeStr}>`;
|
|
289
284
|
}
|
|
290
285
|
function renderNodeSyncToSink(node, sink, ctx) {
|
|
291
286
|
const { type, props } = node;
|
|
292
287
|
if (typeof type === "function") {
|
|
293
|
-
|
|
288
|
+
renderRenderableSyncToSink(inheritRenderableKey(node, executeComponentSync(type, props, ctx)), sink, ctx);
|
|
294
289
|
return;
|
|
295
290
|
}
|
|
296
291
|
if (typeof type === "symbol") {
|
|
297
292
|
if (type === Fragment) {
|
|
298
|
-
renderChildrenSyncToSink(
|
|
293
|
+
renderChildrenSyncToSink(getRenderableChildren(node), sink, ctx);
|
|
299
294
|
return;
|
|
300
295
|
}
|
|
301
296
|
if (type === __CONTROL_BOUNDARY__) {
|
|
@@ -344,16 +339,11 @@ function renderNodeSyncToSink(node, sink, ctx) {
|
|
|
344
339
|
renderAttrsDirect(props, sink);
|
|
345
340
|
sink.write(">");
|
|
346
341
|
if (dangerousHtml !== void 0) sink.write(dangerousHtml);
|
|
347
|
-
else renderChildrenSyncToSink(node
|
|
342
|
+
else renderChildrenSyncToSink(getRenderableChildren(node), sink, ctx);
|
|
348
343
|
sinkWrite3(sink, "</", typeStr, ">");
|
|
349
344
|
return;
|
|
350
345
|
}
|
|
351
|
-
|
|
352
|
-
if (children === void 0 && props?.children !== void 0) {
|
|
353
|
-
const propsChildren = props.children;
|
|
354
|
-
if (Array.isArray(propsChildren)) children = propsChildren;
|
|
355
|
-
else if (propsChildren !== null && propsChildren !== false) children = [propsChildren];
|
|
356
|
-
}
|
|
346
|
+
const children = getRenderableChildren(node);
|
|
357
347
|
if (!children || Array.isArray(children) && children.length === 0) {
|
|
358
348
|
sinkWrite2(sink, "<", typeStr);
|
|
359
349
|
renderAttrsDirect(props, sink);
|
|
@@ -532,10 +522,11 @@ function verifyExpectedNode(node, state, ctx) {
|
|
|
532
522
|
state.pendingText += String(node);
|
|
533
523
|
return true;
|
|
534
524
|
}
|
|
525
|
+
if (Array.isArray(node)) return verifyExpectedChildren(node, state, ctx);
|
|
535
526
|
if (!node || typeof node !== "object" || !("type" in node)) return true;
|
|
536
527
|
const vnode = node;
|
|
537
528
|
const { type, props } = vnode;
|
|
538
|
-
if (typeof type === "function") return
|
|
529
|
+
if (typeof type === "function") return verifyRenderableNode(inheritRenderableKey(vnode, executeComponentSync(type, props, ctx)), state, ctx);
|
|
539
530
|
if (typeof type === "symbol") {
|
|
540
531
|
if (type === __CONTROL_BOUNDARY__) {
|
|
541
532
|
const children = evaluateControlBoundaryChildren(vnode);
|
|
@@ -655,6 +646,64 @@ async function resolveRequest(opts) {
|
|
|
655
646
|
params: resolved.params
|
|
656
647
|
};
|
|
657
648
|
}
|
|
649
|
+
function resolveSSRRouteRender(opts) {
|
|
650
|
+
const { url, routes, seed = 12345, data, document } = opts;
|
|
651
|
+
const routeTable = routes.map((route) => ({ ...route }));
|
|
652
|
+
const requestUrl = new URL(url, "http://localhost");
|
|
653
|
+
const matched = _resolveRouteMatchFromRoutes(requestUrl.pathname, routeTable);
|
|
654
|
+
if (!matched) throw new Error(`SSR: no route found for url: ${url}`);
|
|
655
|
+
const ctx = createRenderContext(seed, {
|
|
656
|
+
url,
|
|
657
|
+
data,
|
|
658
|
+
params: matched.params,
|
|
659
|
+
routes: routeTable
|
|
660
|
+
});
|
|
661
|
+
return {
|
|
662
|
+
url,
|
|
663
|
+
requestUrl,
|
|
664
|
+
route: matched.route,
|
|
665
|
+
params: matched.params,
|
|
666
|
+
seed,
|
|
667
|
+
data,
|
|
668
|
+
ctx,
|
|
669
|
+
document
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
function buildDocumentRenderArgs(resolved, appHtml) {
|
|
673
|
+
return {
|
|
674
|
+
appHtml,
|
|
675
|
+
context: {
|
|
676
|
+
mode: "ssr",
|
|
677
|
+
url: resolved.url,
|
|
678
|
+
pathname: resolved.requestUrl.pathname,
|
|
679
|
+
search: resolved.requestUrl.search,
|
|
680
|
+
hash: resolved.requestUrl.hash,
|
|
681
|
+
params: resolved.params,
|
|
682
|
+
data: resolved.data,
|
|
683
|
+
seed: resolved.seed,
|
|
684
|
+
route: {
|
|
685
|
+
path: resolved.route.path,
|
|
686
|
+
namespace: resolved.route.namespace
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
function renderResolvedRouteAppToSink(resolved, sink) {
|
|
692
|
+
const { ctx, data, route, params } = resolved;
|
|
693
|
+
withRenderContext(ctx, () => {
|
|
694
|
+
startRenderPhase(data || null);
|
|
695
|
+
try {
|
|
696
|
+
renderRenderableSyncToSink(executeComponentSync(route.handler, params, ctx), sink, ctx);
|
|
697
|
+
sink.write(serializeHydrationRenderData(data));
|
|
698
|
+
} finally {
|
|
699
|
+
try {
|
|
700
|
+
stopRenderPhase();
|
|
701
|
+
} finally {
|
|
702
|
+
disposeSSRTemporaryOwners(ctx);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
});
|
|
706
|
+
}
|
|
658
707
|
function renderToString(arg) {
|
|
659
708
|
if (typeof arg === "function") return renderToStringSync(arg);
|
|
660
709
|
const opts = arg;
|
|
@@ -675,29 +724,16 @@ function renderToStream(opts) {
|
|
|
675
724
|
sink.end();
|
|
676
725
|
}
|
|
677
726
|
function renderToSinkInternal(opts) {
|
|
678
|
-
const {
|
|
679
|
-
const
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
withRenderContext(ctx, () => {
|
|
689
|
-
startRenderPhase(data || null);
|
|
690
|
-
try {
|
|
691
|
-
renderNodeSyncToSink(executeComponentSync(resolved.handler, resolved.params, ctx), sink, ctx);
|
|
692
|
-
sink.write(serializeHydrationRenderData(data));
|
|
693
|
-
} finally {
|
|
694
|
-
try {
|
|
695
|
-
stopRenderPhase();
|
|
696
|
-
} finally {
|
|
697
|
-
disposeSSRTemporaryOwners(ctx);
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
});
|
|
727
|
+
const { sink, ...renderOptions } = opts;
|
|
728
|
+
const resolved = resolveSSRRouteRender(renderOptions);
|
|
729
|
+
if (!resolved.document) {
|
|
730
|
+
renderResolvedRouteAppToSink(resolved, sink);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
const appSink = new StringSink();
|
|
734
|
+
renderResolvedRouteAppToSink(resolved, appSink);
|
|
735
|
+
appSink.end();
|
|
736
|
+
sink.write(renderDocument(resolved.document, buildDocumentRenderArgs(resolved, appSink.toString()), "renderToString()/renderToStream()"));
|
|
701
737
|
}
|
|
702
738
|
//#endregion
|
|
703
739
|
export { SSRDataMissingError, renderResolvedToStringSync, renderToStream, renderToString, renderToStringSync, resolveRequest };
|