@vertz/ui-server 0.2.29 → 0.2.31

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.
@@ -0,0 +1,1284 @@
1
+ import {
2
+ clearGlobalSSRTimeout,
3
+ createSSRAdapter,
4
+ getSSRQueries,
5
+ installDomShim,
6
+ setGlobalSSRTimeout,
7
+ ssrStorage,
8
+ toVNode
9
+ } from "./chunk-ybftdw1r.js";
10
+
11
+ // src/html-serializer.ts
12
+ var VOID_ELEMENTS = new Set([
13
+ "area",
14
+ "base",
15
+ "br",
16
+ "col",
17
+ "embed",
18
+ "hr",
19
+ "img",
20
+ "input",
21
+ "link",
22
+ "meta",
23
+ "param",
24
+ "source",
25
+ "track",
26
+ "wbr"
27
+ ]);
28
+ var RAW_TEXT_ELEMENTS = new Set(["script", "style"]);
29
+ function escapeHtml(text) {
30
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
31
+ }
32
+ function escapeAttr(value) {
33
+ const str = typeof value === "string" ? value : String(value);
34
+ return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
35
+ }
36
+ function serializeAttrs(attrs) {
37
+ const parts = [];
38
+ for (const [key, value] of Object.entries(attrs)) {
39
+ parts.push(` ${key}="${escapeAttr(value)}"`);
40
+ }
41
+ return parts.join("");
42
+ }
43
+ function isRawHtml(value) {
44
+ return typeof value === "object" && "__raw" in value && value.__raw === true;
45
+ }
46
+ function serializeToHtml(node) {
47
+ if (typeof node === "string") {
48
+ return escapeHtml(node);
49
+ }
50
+ if (isRawHtml(node)) {
51
+ return node.html;
52
+ }
53
+ const { tag, attrs, children } = node;
54
+ if (tag === "fragment") {
55
+ return children.map((child) => serializeToHtml(child)).join("");
56
+ }
57
+ const attrStr = serializeAttrs(attrs);
58
+ if (VOID_ELEMENTS.has(tag)) {
59
+ return `<${tag}${attrStr}>`;
60
+ }
61
+ const isRawText = RAW_TEXT_ELEMENTS.has(tag);
62
+ const childrenHtml = children.map((child) => {
63
+ if (typeof child === "string" && isRawText) {
64
+ return child;
65
+ }
66
+ return serializeToHtml(child);
67
+ }).join("");
68
+ return `<${tag}${attrStr}>${childrenHtml}</${tag}>`;
69
+ }
70
+
71
+ // src/ssr-access-set.ts
72
+ function getAccessSetForSSR(jwtPayload) {
73
+ if (!jwtPayload)
74
+ return null;
75
+ const acl = jwtPayload.acl;
76
+ if (!acl)
77
+ return null;
78
+ if (acl.overflow)
79
+ return null;
80
+ if (!acl.set)
81
+ return null;
82
+ return {
83
+ entitlements: Object.fromEntries(Object.entries(acl.set.entitlements).map(([name, check]) => [
84
+ name,
85
+ {
86
+ allowed: check.allowed,
87
+ reasons: check.reasons ?? [],
88
+ ...check.reason ? { reason: check.reason } : {},
89
+ ...check.meta ? { meta: check.meta } : {}
90
+ }
91
+ ])),
92
+ flags: acl.set.flags,
93
+ plan: acl.set.plan,
94
+ plans: acl.set.plans ?? {},
95
+ computedAt: acl.set.computedAt
96
+ };
97
+ }
98
+ function createAccessSetScript(accessSet, nonce) {
99
+ const json = JSON.stringify(accessSet);
100
+ const escaped = json.replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
101
+ const nonceAttr = nonce ? ` nonce="${escapeAttr2(nonce)}"` : "";
102
+ return `<script${nonceAttr}>window.__VERTZ_ACCESS_SET__=${escaped}</script>`;
103
+ }
104
+ function escapeAttr2(s) {
105
+ return s.replace(/[&"'<>]/g, (c) => `&#${c.charCodeAt(0)};`);
106
+ }
107
+
108
+ // src/slot-placeholder.ts
109
+ var slotCounter = 0;
110
+ function resetSlotCounter() {
111
+ slotCounter = 0;
112
+ }
113
+ function createSlotPlaceholder(fallback) {
114
+ const id = slotCounter++;
115
+ const placeholder = {
116
+ tag: "div",
117
+ attrs: { id: `v-slot-${id}` },
118
+ children: typeof fallback === "string" ? [fallback] : [fallback],
119
+ _slotId: id
120
+ };
121
+ return placeholder;
122
+ }
123
+
124
+ // src/streaming.ts
125
+ var encoder = new TextEncoder;
126
+ var decoder = new TextDecoder;
127
+ function encodeChunk(html) {
128
+ return encoder.encode(html);
129
+ }
130
+ async function streamToString(stream) {
131
+ const reader = stream.getReader();
132
+ const parts = [];
133
+ for (;; ) {
134
+ const { done, value } = await reader.read();
135
+ if (done)
136
+ break;
137
+ parts.push(decoder.decode(value, { stream: true }));
138
+ }
139
+ parts.push(decoder.decode());
140
+ return parts.join("");
141
+ }
142
+ async function collectStreamChunks(stream) {
143
+ const reader = stream.getReader();
144
+ const chunks = [];
145
+ for (;; ) {
146
+ const { done, value } = await reader.read();
147
+ if (done)
148
+ break;
149
+ chunks.push(decoder.decode(value, { stream: true }));
150
+ }
151
+ return chunks;
152
+ }
153
+
154
+ // src/template-chunk.ts
155
+ function createTemplateChunk(slotId, resolvedHtml, nonce) {
156
+ const tmplId = `v-tmpl-${slotId}`;
157
+ const slotRef = `v-slot-${slotId}`;
158
+ const nonceAttr = nonce != null ? ` nonce="${escapeAttr(nonce)}"` : "";
159
+ return `<template id="${tmplId}">${resolvedHtml}</template>` + `<script${nonceAttr}>` + `(function(){` + `var s=document.getElementById("${slotRef}");` + `var t=document.getElementById("${tmplId}");` + `if(s&&t){s.replaceWith(t.content.cloneNode(true));t.remove()}` + `})()` + "</script>";
160
+ }
161
+
162
+ // src/render-to-stream.ts
163
+ function isSuspenseNode(node) {
164
+ return typeof node === "object" && "tag" in node && node.tag === "__suspense" && "_resolve" in node;
165
+ }
166
+ function renderToStream(tree, options) {
167
+ const pendingBoundaries = [];
168
+ function walkAndSerialize(node) {
169
+ if (typeof node === "string") {
170
+ return escapeHtml(node);
171
+ }
172
+ if (isRawHtml(node)) {
173
+ return node.html;
174
+ }
175
+ if (isSuspenseNode(node)) {
176
+ const placeholder = createSlotPlaceholder(node._fallback);
177
+ pendingBoundaries.push({
178
+ slotId: placeholder._slotId,
179
+ resolve: node._resolve
180
+ });
181
+ return serializeToHtml(placeholder);
182
+ }
183
+ const { tag, attrs, children } = node;
184
+ if (tag === "fragment") {
185
+ return children.map((child) => walkAndSerialize(child)).join("");
186
+ }
187
+ const isRawText = RAW_TEXT_ELEMENTS.has(tag);
188
+ const attrStr = Object.entries(attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
189
+ if (VOID_ELEMENTS.has(tag)) {
190
+ return `<${tag}${attrStr}>`;
191
+ }
192
+ const childrenHtml = children.map((child) => {
193
+ if (typeof child === "string" && isRawText) {
194
+ return child;
195
+ }
196
+ return walkAndSerialize(child);
197
+ }).join("");
198
+ return `<${tag}${attrStr}>${childrenHtml}</${tag}>`;
199
+ }
200
+ return new ReadableStream({
201
+ async start(controller) {
202
+ const mainHtml = walkAndSerialize(tree);
203
+ controller.enqueue(encodeChunk(mainHtml));
204
+ if (pendingBoundaries.length > 0) {
205
+ const nonce = options?.nonce;
206
+ const resolutions = pendingBoundaries.map(async (boundary) => {
207
+ try {
208
+ const resolved = await boundary.resolve;
209
+ const resolvedHtml = serializeToHtml(resolved);
210
+ return createTemplateChunk(boundary.slotId, resolvedHtml, nonce);
211
+ } catch (_err) {
212
+ const errorHtml = `<div data-v-ssr-error="true" id="v-ssr-error-${boundary.slotId}">` + "<!--SSR error--></div>";
213
+ return createTemplateChunk(boundary.slotId, errorHtml, nonce);
214
+ }
215
+ });
216
+ const chunks = await Promise.all(resolutions);
217
+ for (const chunk of chunks) {
218
+ controller.enqueue(encodeChunk(chunk));
219
+ }
220
+ }
221
+ controller.close();
222
+ }
223
+ });
224
+ }
225
+
226
+ // src/ssr-streaming-runtime.ts
227
+ function safeSerialize(data) {
228
+ return JSON.stringify(data).replace(/</g, "\\u003c");
229
+ }
230
+ function getStreamingRuntimeScript(nonce) {
231
+ const nonceAttr = nonce != null ? ` nonce="${escapeAttr(nonce)}"` : "";
232
+ return `<script${nonceAttr}>` + "window.__VERTZ_SSR_DATA__=[];" + "window.__VERTZ_SSR_PUSH__=function(k,d){" + "window.__VERTZ_SSR_DATA__.push({key:k,data:d});" + 'document.dispatchEvent(new CustomEvent("vertz:ssr-data",{detail:{key:k,data:d}}))' + "};" + "</script>";
233
+ }
234
+ function createSSRDataChunk(key, data, nonce) {
235
+ const nonceAttr = nonce != null ? ` nonce="${escapeAttr(nonce)}"` : "";
236
+ const serialized = safeSerialize(data);
237
+ return `<script${nonceAttr}>window.__VERTZ_SSR_PUSH__(${safeSerialize(key)},${serialized})</script>`;
238
+ }
239
+
240
+ // src/ssr-render.ts
241
+ import { compileTheme } from "@vertz/ui";
242
+ import { EntityStore, MemoryCache, QueryEnvelopeStore } from "@vertz/ui/internals";
243
+ var compiledThemeCache = new WeakMap;
244
+ function compileThemeCached(theme, fallbackMetrics) {
245
+ const cached = compiledThemeCache.get(theme);
246
+ if (cached)
247
+ return cached;
248
+ const compiled = compileTheme(theme, { fallbackMetrics });
249
+ compiledThemeCache.set(theme, compiled);
250
+ return compiled;
251
+ }
252
+ function createRequestContext(url) {
253
+ return {
254
+ url,
255
+ adapter: createSSRAdapter(),
256
+ subscriber: null,
257
+ readValueCb: null,
258
+ cleanupStack: [],
259
+ batchDepth: 0,
260
+ pendingEffects: new Map,
261
+ contextScope: null,
262
+ entityStore: new EntityStore,
263
+ envelopeStore: new QueryEnvelopeStore,
264
+ queryCache: new MemoryCache({ maxSize: Infinity }),
265
+ inflight: new Map,
266
+ queries: [],
267
+ errors: []
268
+ };
269
+ }
270
+ var domShimInstalled = false;
271
+ function ensureDomShim() {
272
+ if (domShimInstalled && typeof document !== "undefined")
273
+ return;
274
+ domShimInstalled = true;
275
+ installDomShim();
276
+ }
277
+ function resolveAppFactory(module) {
278
+ const createApp = module.default || module.App;
279
+ if (typeof createApp !== "function") {
280
+ throw new Error("App entry must export a default function or named App function");
281
+ }
282
+ return createApp;
283
+ }
284
+ function collectCSS(themeCss, module) {
285
+ const alreadyIncluded = new Set;
286
+ if (themeCss)
287
+ alreadyIncluded.add(themeCss);
288
+ if (module.styles) {
289
+ for (const s of module.styles)
290
+ alreadyIncluded.add(s);
291
+ }
292
+ const componentCss = module.getInjectedCSS ? module.getInjectedCSS().filter((s) => !alreadyIncluded.has(s)) : [];
293
+ const themeTag = themeCss ? `<style data-vertz-css>${themeCss}</style>` : "";
294
+ const globalTag = module.styles && module.styles.length > 0 ? `<style data-vertz-css>${module.styles.join(`
295
+ `)}</style>` : "";
296
+ const componentTag = componentCss.length > 0 ? `<style data-vertz-css>${componentCss.join(`
297
+ `)}</style>` : "";
298
+ return [themeTag, globalTag, componentTag].filter(Boolean).join(`
299
+ `);
300
+ }
301
+ async function ssrRenderToString(module, url, options) {
302
+ const normalizedUrl = url.endsWith("/index.html") ? url.slice(0, -"/index.html".length) || "/" : url;
303
+ const ssrTimeout = options?.ssrTimeout ?? 300;
304
+ ensureDomShim();
305
+ const ctx = createRequestContext(normalizedUrl);
306
+ if (options?.ssrAuth) {
307
+ ctx.ssrAuth = options.ssrAuth;
308
+ }
309
+ return ssrStorage.run(ctx, async () => {
310
+ try {
311
+ setGlobalSSRTimeout(ssrTimeout);
312
+ const createApp = resolveAppFactory(module);
313
+ let themeCss = "";
314
+ let themePreloadTags = "";
315
+ if (module.theme) {
316
+ try {
317
+ const compiled = compileThemeCached(module.theme, options?.fallbackMetrics);
318
+ themeCss = compiled.css;
319
+ themePreloadTags = compiled.preloadTags;
320
+ } catch (e) {
321
+ console.error("[vertz] Failed to compile theme export. Ensure your theme is created with defineTheme().", e);
322
+ }
323
+ }
324
+ createApp();
325
+ if (ctx.ssrRedirect) {
326
+ return {
327
+ html: "",
328
+ css: "",
329
+ ssrData: [],
330
+ headTags: "",
331
+ redirect: ctx.ssrRedirect
332
+ };
333
+ }
334
+ const store = ssrStorage.getStore();
335
+ if (store) {
336
+ if (store.pendingRouteComponents?.size) {
337
+ const entries = Array.from(store.pendingRouteComponents.entries());
338
+ const results = await Promise.allSettled(entries.map(([route, promise]) => Promise.race([
339
+ promise.then((mod) => ({ route, factory: mod.default })),
340
+ new Promise((_, reject) => setTimeout(() => reject(new Error("lazy route timeout")), ssrTimeout))
341
+ ])));
342
+ store.resolvedComponents = new Map;
343
+ for (const result of results) {
344
+ if (result.status === "fulfilled") {
345
+ const { route, factory } = result.value;
346
+ store.resolvedComponents.set(route, factory);
347
+ }
348
+ }
349
+ store.pendingRouteComponents = undefined;
350
+ }
351
+ if (!store.resolvedComponents) {
352
+ store.resolvedComponents = new Map;
353
+ }
354
+ }
355
+ const queries = getSSRQueries();
356
+ const resolvedQueries = [];
357
+ if (queries.length > 0) {
358
+ await Promise.allSettled(queries.map(({ promise, timeout, resolve, key }) => Promise.race([
359
+ promise.then((data) => {
360
+ resolve(data);
361
+ resolvedQueries.push({ key, data });
362
+ return "resolved";
363
+ }),
364
+ new Promise((r) => setTimeout(r, timeout || ssrTimeout)).then(() => "timeout")
365
+ ])));
366
+ if (store)
367
+ store.queries = [];
368
+ }
369
+ const app = createApp();
370
+ const vnode = toVNode(app);
371
+ const stream = renderToStream(vnode);
372
+ const html = await streamToString(stream);
373
+ const css = collectCSS(themeCss, module);
374
+ const ssrData = resolvedQueries.length > 0 ? resolvedQueries.map(({ key, data }) => ({ key, data })) : [];
375
+ return {
376
+ html,
377
+ css,
378
+ ssrData,
379
+ headTags: themePreloadTags,
380
+ discoveredRoutes: ctx.discoveredRoutes,
381
+ matchedRoutePatterns: ctx.matchedRoutePatterns
382
+ };
383
+ } finally {
384
+ clearGlobalSSRTimeout();
385
+ }
386
+ });
387
+ }
388
+ async function ssrDiscoverQueries(module, url, options) {
389
+ const normalizedUrl = url.endsWith("/index.html") ? url.slice(0, -"/index.html".length) || "/" : url;
390
+ const ssrTimeout = options?.ssrTimeout ?? 300;
391
+ ensureDomShim();
392
+ const ctx = createRequestContext(normalizedUrl);
393
+ return ssrStorage.run(ctx, async () => {
394
+ try {
395
+ setGlobalSSRTimeout(ssrTimeout);
396
+ const createApp = resolveAppFactory(module);
397
+ createApp();
398
+ const queries = getSSRQueries();
399
+ const resolvedQueries = [];
400
+ const pendingKeys = [];
401
+ if (queries.length > 0) {
402
+ await Promise.allSettled(queries.map(({ promise, timeout, resolve, key }) => {
403
+ let settled = false;
404
+ return Promise.race([
405
+ promise.then((data) => {
406
+ if (settled)
407
+ return "late";
408
+ settled = true;
409
+ resolve(data);
410
+ resolvedQueries.push({ key, data });
411
+ return "resolved";
412
+ }),
413
+ new Promise((r) => setTimeout(r, timeout || ssrTimeout)).then(() => {
414
+ if (settled)
415
+ return "already-resolved";
416
+ settled = true;
417
+ pendingKeys.push(key);
418
+ return "timeout";
419
+ })
420
+ ]);
421
+ }));
422
+ }
423
+ return {
424
+ resolved: resolvedQueries.map(({ key, data }) => ({
425
+ key,
426
+ data: JSON.parse(JSON.stringify(data))
427
+ })),
428
+ pending: pendingKeys
429
+ };
430
+ } finally {
431
+ clearGlobalSSRTimeout();
432
+ }
433
+ });
434
+ }
435
+ async function ssrStreamNavQueries(module, url, options) {
436
+ const normalizedUrl = url.endsWith("/index.html") ? url.slice(0, -"/index.html".length) || "/" : url;
437
+ const ssrTimeout = options?.ssrTimeout ?? 300;
438
+ const navTimeout = options?.navSsrTimeout ?? 5000;
439
+ ensureDomShim();
440
+ const ctx = createRequestContext(normalizedUrl);
441
+ const queries = await ssrStorage.run(ctx, async () => {
442
+ try {
443
+ setGlobalSSRTimeout(ssrTimeout);
444
+ const createApp = resolveAppFactory(module);
445
+ createApp();
446
+ const discovered = getSSRQueries();
447
+ return discovered.map((q) => ({
448
+ promise: q.promise,
449
+ timeout: q.timeout || ssrTimeout,
450
+ resolve: q.resolve,
451
+ key: q.key
452
+ }));
453
+ } finally {
454
+ clearGlobalSSRTimeout();
455
+ }
456
+ });
457
+ if (queries.length === 0) {
458
+ const encoder3 = new TextEncoder;
459
+ return new ReadableStream({
460
+ start(controller) {
461
+ controller.enqueue(encoder3.encode(`event: done
462
+ data: {}
463
+
464
+ `));
465
+ controller.close();
466
+ }
467
+ });
468
+ }
469
+ const encoder2 = new TextEncoder;
470
+ let remaining = queries.length;
471
+ return new ReadableStream({
472
+ start(controller) {
473
+ let closed = false;
474
+ function safeEnqueue(chunk) {
475
+ if (closed)
476
+ return;
477
+ try {
478
+ controller.enqueue(chunk);
479
+ } catch {
480
+ closed = true;
481
+ }
482
+ }
483
+ function safeClose() {
484
+ if (closed)
485
+ return;
486
+ closed = true;
487
+ try {
488
+ controller.close();
489
+ } catch {}
490
+ }
491
+ function checkDone() {
492
+ if (remaining === 0) {
493
+ safeEnqueue(encoder2.encode(`event: done
494
+ data: {}
495
+
496
+ `));
497
+ safeClose();
498
+ }
499
+ }
500
+ for (const { promise, resolve, key } of queries) {
501
+ let settled = false;
502
+ promise.then((data) => {
503
+ if (settled)
504
+ return;
505
+ settled = true;
506
+ resolve(data);
507
+ const entry = { key, data };
508
+ safeEnqueue(encoder2.encode(`event: data
509
+ data: ${safeSerialize(entry)}
510
+
511
+ `));
512
+ remaining--;
513
+ checkDone();
514
+ }, () => {
515
+ if (settled)
516
+ return;
517
+ settled = true;
518
+ remaining--;
519
+ checkDone();
520
+ });
521
+ setTimeout(() => {
522
+ if (settled)
523
+ return;
524
+ settled = true;
525
+ remaining--;
526
+ checkDone();
527
+ }, navTimeout);
528
+ }
529
+ }
530
+ });
531
+ }
532
+
533
+ // src/ssr-session.ts
534
+ function createSessionScript(session, nonce) {
535
+ const json = JSON.stringify(session);
536
+ const escaped = json.replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
537
+ const nonceAttr = nonce ? ` nonce="${escapeAttr3(nonce)}"` : "";
538
+ return `<script${nonceAttr}>window.__VERTZ_SESSION__=${escaped}</script>`;
539
+ }
540
+ function escapeAttr3(s) {
541
+ return s.replace(/[&"'<>]/g, (c) => `&#${c.charCodeAt(0)};`);
542
+ }
543
+
544
+ // src/template-split.ts
545
+ function splitTemplate(template, options) {
546
+ let processed = template;
547
+ if (options?.inlineCSS) {
548
+ processed = inlineCSSAssets(processed, options.inlineCSS);
549
+ }
550
+ const outletMarker = "<!--ssr-outlet-->";
551
+ const outletIndex = processed.indexOf(outletMarker);
552
+ if (outletIndex !== -1) {
553
+ return {
554
+ headTemplate: processed.slice(0, outletIndex),
555
+ tailTemplate: processed.slice(outletIndex + outletMarker.length)
556
+ };
557
+ }
558
+ const appDivMatch = processed.match(/<div[^>]*id="app"[^>]*>/);
559
+ if (appDivMatch && appDivMatch.index != null) {
560
+ const openTag = appDivMatch[0];
561
+ const contentStart = appDivMatch.index + openTag.length;
562
+ const closingIndex = findMatchingDivClose(processed, contentStart);
563
+ return {
564
+ headTemplate: processed.slice(0, contentStart),
565
+ tailTemplate: processed.slice(closingIndex)
566
+ };
567
+ }
568
+ throw new Error('Could not find <!--ssr-outlet--> or <div id="app"> in the HTML template. ' + "The template must contain one of these markers for SSR content injection.");
569
+ }
570
+ function findMatchingDivClose(html, startAfterOpen) {
571
+ let depth = 1;
572
+ let i = startAfterOpen;
573
+ const len = html.length;
574
+ while (i < len && depth > 0) {
575
+ if (html[i] === "<") {
576
+ if (html.startsWith("</div>", i)) {
577
+ depth--;
578
+ if (depth === 0)
579
+ return i;
580
+ i += 6;
581
+ } else if (html.startsWith("<div", i) && /^<div[\s>]/.test(html.slice(i, i + 5))) {
582
+ depth++;
583
+ i += 4;
584
+ } else {
585
+ i++;
586
+ }
587
+ } else {
588
+ i++;
589
+ }
590
+ }
591
+ return len;
592
+ }
593
+ function inlineCSSAssets(html, inlineCSS) {
594
+ let result = html;
595
+ for (const [href, css] of Object.entries(inlineCSS)) {
596
+ const escapedHref = href.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
597
+ const linkPattern = new RegExp(`<link[^>]*href=["']${escapedHref}["'][^>]*>`);
598
+ const safeCss = css.replace(/<\//g, "<\\/");
599
+ result = result.replace(linkPattern, `<style data-vertz-css>${safeCss}</style>`);
600
+ }
601
+ result = result.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"[^>]*>/g, (match, href) => `<link rel="stylesheet" href="${href}" media="print" onload="this.media='all'">
602
+ <noscript>${match}</noscript>`);
603
+ return result;
604
+ }
605
+
606
+ // src/ssr-handler-shared.ts
607
+ function sanitizeLinkHref(href) {
608
+ return href.replace(/[<>,;\s"']/g, (ch) => `%${ch.charCodeAt(0).toString(16).toUpperCase()}`);
609
+ }
610
+ function sanitizeLinkParam(value) {
611
+ return value.replace(/[^a-zA-Z0-9/_.-]/g, "");
612
+ }
613
+ function buildLinkHeader(items) {
614
+ return items.map((item) => {
615
+ const parts = [
616
+ `<${sanitizeLinkHref(item.href)}>`,
617
+ "rel=preload",
618
+ `as=${sanitizeLinkParam(item.as)}`
619
+ ];
620
+ if (item.type)
621
+ parts.push(`type=${sanitizeLinkParam(item.type)}`);
622
+ if (item.crossorigin)
623
+ parts.push("crossorigin");
624
+ return parts.join("; ");
625
+ }).join(", ");
626
+ }
627
+ function buildModulepreloadTags(paths) {
628
+ return paths.map((p) => `<link rel="modulepreload" href="${escapeAttr(p)}">`).join(`
629
+ `);
630
+ }
631
+ function resolveRouteModulepreload(routeChunkManifest, matchedPatterns, fallback) {
632
+ if (routeChunkManifest && matchedPatterns?.length) {
633
+ const chunkPaths = new Set;
634
+ for (const pattern of matchedPatterns) {
635
+ const chunks = routeChunkManifest.routes[pattern];
636
+ if (chunks) {
637
+ for (const chunk of chunks) {
638
+ chunkPaths.add(chunk);
639
+ }
640
+ }
641
+ }
642
+ if (chunkPaths.size > 0) {
643
+ return buildModulepreloadTags([...chunkPaths]);
644
+ }
645
+ }
646
+ return fallback;
647
+ }
648
+ function preprocessInlineCSS(template, inlineCSS) {
649
+ let result = template;
650
+ for (const [href, css] of Object.entries(inlineCSS)) {
651
+ const escapedHref = href.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
652
+ const linkPattern = new RegExp(`<link[^>]*href=["']${escapedHref}["'][^>]*>`);
653
+ const safeCss = css.replace(/<\//g, "<\\/");
654
+ result = result.replace(linkPattern, `<style data-vertz-css>${safeCss}</style>`);
655
+ }
656
+ return result;
657
+ }
658
+ function precomputeHandlerState(options) {
659
+ const { module, inlineCSS, fallbackMetrics, modulepreload, progressiveHTML } = options;
660
+ let template = options.template;
661
+ if (inlineCSS) {
662
+ template = preprocessInlineCSS(template, inlineCSS);
663
+ }
664
+ let linkHeader;
665
+ if (module.theme) {
666
+ const compiled = compileThemeCached(module.theme, fallbackMetrics);
667
+ if (compiled.preloadItems.length > 0) {
668
+ linkHeader = buildLinkHeader(compiled.preloadItems);
669
+ }
670
+ }
671
+ const modulepreloadTags = modulepreload?.length ? buildModulepreloadTags(modulepreload) : undefined;
672
+ const splitResult = progressiveHTML ? splitTemplate(template) : undefined;
673
+ if (splitResult && module.theme) {
674
+ splitResult.headTemplate = splitResult.headTemplate.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"[^>]*>/g, (match, href) => `<link rel="stylesheet" href="${href}" media="print" onload="this.media='all'">
675
+ <noscript>${match}</noscript>`);
676
+ }
677
+ return { template, linkHeader, modulepreloadTags, splitResult };
678
+ }
679
+ async function resolveSession(request, sessionResolver, nonce) {
680
+ let sessionScript = "";
681
+ let ssrAuth;
682
+ try {
683
+ const sessionResult = await sessionResolver(request);
684
+ if (sessionResult) {
685
+ ssrAuth = {
686
+ status: "authenticated",
687
+ user: sessionResult.session.user,
688
+ expiresAt: sessionResult.session.expiresAt
689
+ };
690
+ const scripts = [];
691
+ scripts.push(createSessionScript(sessionResult.session, nonce));
692
+ if (sessionResult.accessSet != null) {
693
+ scripts.push(createAccessSetScript(sessionResult.accessSet, nonce));
694
+ }
695
+ sessionScript = scripts.join(`
696
+ `);
697
+ } else {
698
+ ssrAuth = { status: "unauthenticated" };
699
+ }
700
+ } catch (resolverErr) {
701
+ console.warn("[Server] Session resolver failed:", resolverErr instanceof Error ? resolverErr.message : resolverErr);
702
+ }
703
+ return { sessionScript, ssrAuth };
704
+ }
705
+
706
+ // src/ssr-access-evaluator.ts
707
+ function toPrefetchSession(ssrAuth, accessSet) {
708
+ if (!ssrAuth || ssrAuth.status !== "authenticated" || !ssrAuth.user) {
709
+ return { status: "unauthenticated" };
710
+ }
711
+ const roles = ssrAuth.user.role ? [ssrAuth.user.role] : undefined;
712
+ const entitlements = accessSet != null ? Object.fromEntries(Object.entries(accessSet.entitlements).map(([name, check]) => [name, check.allowed])) : undefined;
713
+ return {
714
+ status: "authenticated",
715
+ roles,
716
+ entitlements,
717
+ tenantId: ssrAuth.user.tenantId
718
+ };
719
+ }
720
+ function evaluateAccessRule(rule, session) {
721
+ switch (rule.type) {
722
+ case "public":
723
+ return true;
724
+ case "authenticated":
725
+ return session.status === "authenticated";
726
+ case "role":
727
+ if (session.status !== "authenticated")
728
+ return false;
729
+ return session.roles?.some((r) => rule.roles.includes(r)) === true;
730
+ case "entitlement":
731
+ if (session.status !== "authenticated")
732
+ return false;
733
+ return session.entitlements?.[rule.value] === true;
734
+ case "where":
735
+ return true;
736
+ case "fva":
737
+ return session.status === "authenticated";
738
+ case "deny":
739
+ return false;
740
+ case "all":
741
+ return rule.rules.every((r) => evaluateAccessRule(r, session));
742
+ case "any":
743
+ return rule.rules.some((r) => evaluateAccessRule(r, session));
744
+ default:
745
+ return false;
746
+ }
747
+ }
748
+
749
+ // src/ssr-manifest-prefetch.ts
750
+ function reconstructDescriptors(queries, routeParams, apiClient) {
751
+ if (!apiClient)
752
+ return [];
753
+ const result = [];
754
+ for (const query of queries) {
755
+ const descriptor = reconstructSingle(query, routeParams, apiClient);
756
+ if (descriptor) {
757
+ result.push(descriptor);
758
+ }
759
+ }
760
+ return result;
761
+ }
762
+ function reconstructSingle(query, routeParams, apiClient) {
763
+ const { entity, operation } = query;
764
+ if (!entity || !operation)
765
+ return;
766
+ const entitySdk = apiClient[entity];
767
+ if (!entitySdk)
768
+ return;
769
+ const method = entitySdk[operation];
770
+ if (typeof method !== "function")
771
+ return;
772
+ const args = buildFactoryArgs(query, routeParams);
773
+ if (args === undefined)
774
+ return;
775
+ try {
776
+ const descriptor = method(...args);
777
+ if (!descriptor || typeof descriptor._key !== "string" || typeof descriptor._fetch !== "function") {
778
+ return;
779
+ }
780
+ return { key: descriptor._key, fetch: descriptor._fetch };
781
+ } catch {
782
+ return;
783
+ }
784
+ }
785
+ function buildFactoryArgs(query, routeParams) {
786
+ const { operation, idParam, queryBindings } = query;
787
+ if (operation === "get") {
788
+ if (idParam) {
789
+ const id = routeParams[idParam];
790
+ if (!id)
791
+ return;
792
+ const options = resolveQueryBindings(queryBindings, routeParams);
793
+ if (options === undefined && queryBindings)
794
+ return;
795
+ return options ? [id, options] : [id];
796
+ }
797
+ return;
798
+ }
799
+ if (!queryBindings)
800
+ return [];
801
+ const resolved = resolveQueryBindings(queryBindings, routeParams);
802
+ if (resolved === undefined)
803
+ return;
804
+ return [resolved];
805
+ }
806
+ function resolveQueryBindings(bindings, routeParams) {
807
+ if (!bindings)
808
+ return;
809
+ const resolved = {};
810
+ if (bindings.where) {
811
+ const where = {};
812
+ for (const [key, value] of Object.entries(bindings.where)) {
813
+ if (value === null)
814
+ return;
815
+ if (typeof value === "string" && value.startsWith("$")) {
816
+ const paramName = value.slice(1);
817
+ const paramValue = routeParams[paramName];
818
+ if (!paramValue)
819
+ return;
820
+ where[key] = paramValue;
821
+ } else {
822
+ where[key] = value;
823
+ }
824
+ }
825
+ resolved.where = where;
826
+ }
827
+ if (bindings.select)
828
+ resolved.select = bindings.select;
829
+ if (bindings.include)
830
+ resolved.include = bindings.include;
831
+ if (bindings.orderBy)
832
+ resolved.orderBy = bindings.orderBy;
833
+ if (bindings.limit !== undefined)
834
+ resolved.limit = bindings.limit;
835
+ return resolved;
836
+ }
837
+
838
+ // src/ssr-route-matcher.ts
839
+ function matchUrlToPatterns(url, patterns) {
840
+ const path = (url.split("?")[0] ?? "").split("#")[0] ?? "";
841
+ const matches = [];
842
+ for (const pattern of patterns) {
843
+ const result = matchPattern(path, pattern);
844
+ if (result) {
845
+ matches.push(result);
846
+ }
847
+ }
848
+ matches.sort((a, b) => {
849
+ const aSegments = a.pattern.split("/").length;
850
+ const bSegments = b.pattern.split("/").length;
851
+ return aSegments - bSegments;
852
+ });
853
+ return matches;
854
+ }
855
+ function matchPattern(path, pattern) {
856
+ const pathSegments = path.split("/").filter(Boolean);
857
+ const patternSegments = pattern.split("/").filter(Boolean);
858
+ if (patternSegments.length > pathSegments.length)
859
+ return;
860
+ const params = {};
861
+ for (let i = 0;i < patternSegments.length; i++) {
862
+ const seg = patternSegments[i];
863
+ const val = pathSegments[i];
864
+ if (seg.startsWith(":")) {
865
+ params[seg.slice(1)] = val;
866
+ } else if (seg !== val) {
867
+ return;
868
+ }
869
+ }
870
+ return { pattern, params };
871
+ }
872
+
873
+ // src/ssr-single-pass.ts
874
+ async function ssrRenderSinglePass(module, url, options) {
875
+ if (options?.prefetch === false) {
876
+ return ssrRenderToString(module, url, options);
877
+ }
878
+ const normalizedUrl = url.endsWith("/index.html") ? url.slice(0, -"/index.html".length) || "/" : url;
879
+ const ssrTimeout = options?.ssrTimeout ?? 300;
880
+ ensureDomShim2();
881
+ const zeroDiscoveryData = attemptZeroDiscovery(normalizedUrl, module, options, ssrTimeout);
882
+ if (zeroDiscoveryData) {
883
+ return renderWithPrefetchedData(module, normalizedUrl, zeroDiscoveryData, options);
884
+ }
885
+ const discoveredData = await runDiscoveryPhase(normalizedUrl, ssrTimeout, module, options);
886
+ if ("redirect" in discoveredData) {
887
+ return {
888
+ html: "",
889
+ css: "",
890
+ ssrData: [],
891
+ headTags: "",
892
+ redirect: discoveredData.redirect
893
+ };
894
+ }
895
+ const renderCtx = createRequestContext(normalizedUrl);
896
+ if (options?.ssrAuth) {
897
+ renderCtx.ssrAuth = options.ssrAuth;
898
+ }
899
+ for (const { key, data } of discoveredData.resolvedQueries) {
900
+ renderCtx.queryCache.set(key, data);
901
+ }
902
+ renderCtx.resolvedComponents = discoveredData.resolvedComponents ?? new Map;
903
+ return ssrStorage.run(renderCtx, async () => {
904
+ try {
905
+ setGlobalSSRTimeout(ssrTimeout);
906
+ const createApp = resolveAppFactory2(module);
907
+ let themeCss = "";
908
+ let themePreloadTags = "";
909
+ if (module.theme) {
910
+ try {
911
+ const compiled = compileThemeCached(module.theme, options?.fallbackMetrics);
912
+ themeCss = compiled.css;
913
+ themePreloadTags = compiled.preloadTags;
914
+ } catch (e) {
915
+ console.error("[vertz] Failed to compile theme export. Ensure your theme is created with defineTheme().", e);
916
+ }
917
+ }
918
+ const app = createApp();
919
+ const vnode = toVNode(app);
920
+ const stream = renderToStream(vnode);
921
+ const html = await streamToString(stream);
922
+ const css = collectCSS2(themeCss, module);
923
+ const ssrData = discoveredData.resolvedQueries.map(({ key, data }) => ({
924
+ key,
925
+ data
926
+ }));
927
+ return {
928
+ html,
929
+ css,
930
+ ssrData,
931
+ headTags: themePreloadTags,
932
+ discoveredRoutes: renderCtx.discoveredRoutes,
933
+ matchedRoutePatterns: renderCtx.matchedRoutePatterns
934
+ };
935
+ } finally {
936
+ clearGlobalSSRTimeout();
937
+ }
938
+ });
939
+ }
940
+ async function ssrRenderProgressive(module, url, options) {
941
+ const normalizedUrl = url.endsWith("/index.html") ? url.slice(0, -"/index.html".length) || "/" : url;
942
+ const ssrTimeout = options?.ssrTimeout ?? 300;
943
+ ensureDomShim2();
944
+ const discoveryResult = await runDiscoveryPhase(normalizedUrl, ssrTimeout, module, options);
945
+ if ("redirect" in discoveryResult) {
946
+ return {
947
+ css: "",
948
+ ssrData: [],
949
+ headTags: "",
950
+ redirect: discoveryResult.redirect
951
+ };
952
+ }
953
+ const renderCtx = createRequestContext(normalizedUrl);
954
+ if (options?.ssrAuth) {
955
+ renderCtx.ssrAuth = options.ssrAuth;
956
+ }
957
+ for (const { key, data } of discoveryResult.resolvedQueries) {
958
+ renderCtx.queryCache.set(key, data);
959
+ }
960
+ renderCtx.resolvedComponents = discoveryResult.resolvedComponents ?? new Map;
961
+ return ssrStorage.run(renderCtx, () => {
962
+ try {
963
+ setGlobalSSRTimeout(ssrTimeout);
964
+ const createApp = resolveAppFactory2(module);
965
+ let themeCss = "";
966
+ let themePreloadTags = "";
967
+ if (module.theme) {
968
+ try {
969
+ const compiled = compileThemeCached(module.theme, options?.fallbackMetrics);
970
+ themeCss = compiled.css;
971
+ themePreloadTags = compiled.preloadTags;
972
+ } catch (e) {
973
+ console.error("[vertz] Failed to compile theme export. Ensure your theme is created with defineTheme().", e);
974
+ }
975
+ }
976
+ const app = createApp();
977
+ const vnode = toVNode(app);
978
+ const renderStream = renderToStream(vnode);
979
+ const css = collectCSS2(themeCss, module);
980
+ const ssrData = discoveryResult.resolvedQueries.map(({ key, data }) => ({
981
+ key,
982
+ data
983
+ }));
984
+ return {
985
+ css,
986
+ ssrData,
987
+ headTags: themePreloadTags,
988
+ matchedRoutePatterns: renderCtx.matchedRoutePatterns,
989
+ renderStream
990
+ };
991
+ } finally {
992
+ clearGlobalSSRTimeout();
993
+ }
994
+ });
995
+ }
996
+ async function runDiscoveryPhase(normalizedUrl, ssrTimeout, module, options) {
997
+ const discoveryCtx = createRequestContext(normalizedUrl);
998
+ if (options?.ssrAuth) {
999
+ discoveryCtx.ssrAuth = options.ssrAuth;
1000
+ }
1001
+ return ssrStorage.run(discoveryCtx, async () => {
1002
+ try {
1003
+ setGlobalSSRTimeout(ssrTimeout);
1004
+ const createApp = resolveAppFactory2(module);
1005
+ createApp();
1006
+ if (discoveryCtx.ssrRedirect) {
1007
+ return { redirect: discoveryCtx.ssrRedirect };
1008
+ }
1009
+ if (discoveryCtx.pendingRouteComponents?.size) {
1010
+ const entries = Array.from(discoveryCtx.pendingRouteComponents.entries());
1011
+ const results = await Promise.allSettled(entries.map(([route, promise]) => Promise.race([
1012
+ promise.then((mod) => ({ route, factory: mod.default })),
1013
+ new Promise((_, reject) => setTimeout(() => reject(new Error("lazy route timeout")), ssrTimeout))
1014
+ ])));
1015
+ discoveryCtx.resolvedComponents = new Map;
1016
+ for (const result of results) {
1017
+ if (result.status === "fulfilled") {
1018
+ const { route, factory } = result.value;
1019
+ discoveryCtx.resolvedComponents.set(route, factory);
1020
+ }
1021
+ }
1022
+ discoveryCtx.pendingRouteComponents = undefined;
1023
+ }
1024
+ const queries = getSSRQueries();
1025
+ const eligibleQueries = filterByEntityAccess(queries, options?.manifest?.entityAccess, options?.prefetchSession);
1026
+ const resolvedQueries = [];
1027
+ if (eligibleQueries.length > 0) {
1028
+ await Promise.allSettled(eligibleQueries.map(({ promise, timeout, resolve, key }) => Promise.race([
1029
+ promise.then((data) => {
1030
+ resolve(data);
1031
+ resolvedQueries.push({ key, data });
1032
+ return "resolved";
1033
+ }),
1034
+ new Promise((r) => setTimeout(r, timeout || ssrTimeout)).then(() => "timeout")
1035
+ ])));
1036
+ }
1037
+ return {
1038
+ resolvedQueries,
1039
+ resolvedComponents: discoveryCtx.resolvedComponents
1040
+ };
1041
+ } finally {
1042
+ clearGlobalSSRTimeout();
1043
+ }
1044
+ });
1045
+ }
1046
+ function attemptZeroDiscovery(url, module, options, ssrTimeout) {
1047
+ const manifest = options?.manifest;
1048
+ if (!manifest?.routeEntries || !module.api)
1049
+ return null;
1050
+ const matches = matchUrlToPatterns(url, manifest.routePatterns);
1051
+ if (matches.length === 0)
1052
+ return null;
1053
+ const allQueries = [];
1054
+ let mergedParams = {};
1055
+ for (const match of matches) {
1056
+ const entry = manifest.routeEntries[match.pattern];
1057
+ if (entry) {
1058
+ allQueries.push(...entry.queries);
1059
+ }
1060
+ mergedParams = { ...mergedParams, ...match.params };
1061
+ }
1062
+ if (allQueries.length === 0)
1063
+ return null;
1064
+ const descriptors = reconstructDescriptors(allQueries, mergedParams, module.api);
1065
+ if (descriptors.length === 0)
1066
+ return null;
1067
+ return prefetchFromDescriptors(descriptors, ssrTimeout);
1068
+ }
1069
+ async function prefetchFromDescriptors(descriptors, ssrTimeout) {
1070
+ const resolvedQueries = [];
1071
+ await Promise.allSettled(descriptors.map(({ key, fetch: fetchFn }) => Promise.race([
1072
+ fetchFn().then((result) => {
1073
+ const data = unwrapResult(result);
1074
+ resolvedQueries.push({ key, data });
1075
+ return "resolved";
1076
+ }),
1077
+ new Promise((r) => setTimeout(r, ssrTimeout)).then(() => "timeout")
1078
+ ])));
1079
+ return { resolvedQueries };
1080
+ }
1081
+ function unwrapResult(result) {
1082
+ if (result && typeof result === "object" && "ok" in result && "data" in result) {
1083
+ const r = result;
1084
+ if (r.ok)
1085
+ return r.data;
1086
+ }
1087
+ return result;
1088
+ }
1089
+ async function renderWithPrefetchedData(module, normalizedUrl, prefetchedData, options) {
1090
+ const data = await prefetchedData;
1091
+ const ssrTimeout = options?.ssrTimeout ?? 300;
1092
+ const renderCtx = createRequestContext(normalizedUrl);
1093
+ if (options?.ssrAuth) {
1094
+ renderCtx.ssrAuth = options.ssrAuth;
1095
+ }
1096
+ for (const { key, data: queryData } of data.resolvedQueries) {
1097
+ renderCtx.queryCache.set(key, queryData);
1098
+ }
1099
+ renderCtx.resolvedComponents = new Map;
1100
+ return ssrStorage.run(renderCtx, async () => {
1101
+ try {
1102
+ setGlobalSSRTimeout(ssrTimeout);
1103
+ const createApp = resolveAppFactory2(module);
1104
+ let themeCss = "";
1105
+ let themePreloadTags = "";
1106
+ if (module.theme) {
1107
+ try {
1108
+ const compiled = compileThemeCached(module.theme, options?.fallbackMetrics);
1109
+ themeCss = compiled.css;
1110
+ themePreloadTags = compiled.preloadTags;
1111
+ } catch (e) {
1112
+ console.error("[vertz] Failed to compile theme export. Ensure your theme is created with defineTheme().", e);
1113
+ }
1114
+ }
1115
+ const app = createApp();
1116
+ const vnode = toVNode(app);
1117
+ const stream = renderToStream(vnode);
1118
+ const html = await streamToString(stream);
1119
+ if (renderCtx.ssrRedirect) {
1120
+ return {
1121
+ html: "",
1122
+ css: "",
1123
+ ssrData: [],
1124
+ headTags: "",
1125
+ redirect: renderCtx.ssrRedirect,
1126
+ discoveredRoutes: renderCtx.discoveredRoutes,
1127
+ matchedRoutePatterns: renderCtx.matchedRoutePatterns
1128
+ };
1129
+ }
1130
+ const css = collectCSS2(themeCss, module);
1131
+ const ssrData = data.resolvedQueries.map(({ key, data: d }) => ({
1132
+ key,
1133
+ data: d
1134
+ }));
1135
+ return {
1136
+ html,
1137
+ css,
1138
+ ssrData,
1139
+ headTags: themePreloadTags,
1140
+ discoveredRoutes: renderCtx.discoveredRoutes,
1141
+ matchedRoutePatterns: renderCtx.matchedRoutePatterns
1142
+ };
1143
+ } finally {
1144
+ clearGlobalSSRTimeout();
1145
+ }
1146
+ });
1147
+ }
1148
+ var domShimInstalled2 = false;
1149
+ function ensureDomShim2() {
1150
+ if (domShimInstalled2 && typeof document !== "undefined")
1151
+ return;
1152
+ domShimInstalled2 = true;
1153
+ installDomShim();
1154
+ }
1155
+ function resolveAppFactory2(module) {
1156
+ const createApp = module.default || module.App;
1157
+ if (typeof createApp !== "function") {
1158
+ throw new Error("App entry must export a default function or named App function");
1159
+ }
1160
+ return createApp;
1161
+ }
1162
+ function filterByEntityAccess(queries, entityAccess, session) {
1163
+ if (!entityAccess || !session)
1164
+ return queries;
1165
+ return queries.filter(({ key }) => {
1166
+ const entity = extractEntityFromKey(key);
1167
+ const method = extractMethodFromKey(key);
1168
+ if (!entity)
1169
+ return true;
1170
+ const entityRules = entityAccess[entity];
1171
+ if (!entityRules)
1172
+ return true;
1173
+ const rule = entityRules[method];
1174
+ if (!rule)
1175
+ return true;
1176
+ return evaluateAccessRule(rule, session);
1177
+ });
1178
+ }
1179
+ function extractEntityFromKey(key) {
1180
+ const pathStart = key.indexOf(":/");
1181
+ if (pathStart === -1)
1182
+ return;
1183
+ const path = key.slice(pathStart + 2);
1184
+ const firstSlash = path.indexOf("/");
1185
+ const questionMark = path.indexOf("?");
1186
+ if (firstSlash === -1 && questionMark === -1)
1187
+ return path;
1188
+ if (firstSlash === -1)
1189
+ return path.slice(0, questionMark);
1190
+ if (questionMark === -1)
1191
+ return path.slice(0, firstSlash);
1192
+ return path.slice(0, Math.min(firstSlash, questionMark));
1193
+ }
1194
+ function extractMethodFromKey(key) {
1195
+ const pathStart = key.indexOf(":/");
1196
+ if (pathStart === -1)
1197
+ return "list";
1198
+ const path = key.slice(pathStart + 2);
1199
+ const cleanPath = path.split("?")[0] ?? "";
1200
+ const segments = cleanPath.split("/").filter(Boolean);
1201
+ return segments.length > 1 ? "get" : "list";
1202
+ }
1203
+ function collectCSS2(themeCss, module) {
1204
+ const alreadyIncluded = new Set;
1205
+ if (themeCss)
1206
+ alreadyIncluded.add(themeCss);
1207
+ if (module.styles) {
1208
+ for (const s of module.styles)
1209
+ alreadyIncluded.add(s);
1210
+ }
1211
+ const componentCss = module.getInjectedCSS ? module.getInjectedCSS().filter((s) => !alreadyIncluded.has(s)) : [];
1212
+ const themeTag = themeCss ? `<style data-vertz-css>${themeCss}</style>` : "";
1213
+ const globalTag = module.styles && module.styles.length > 0 ? `<style data-vertz-css>${module.styles.join(`
1214
+ `)}</style>` : "";
1215
+ const componentTag = componentCss.length > 0 ? `<style data-vertz-css>${componentCss.join(`
1216
+ `)}</style>` : "";
1217
+ return [themeTag, globalTag, componentTag].filter(Boolean).join(`
1218
+ `);
1219
+ }
1220
+
1221
+ // src/template-inject.ts
1222
+ function injectIntoTemplate(options) {
1223
+ const { template, appHtml, appCss, ssrData, nonce, headTags, sessionScript } = options;
1224
+ let html;
1225
+ if (template.includes("<!--ssr-outlet-->")) {
1226
+ html = template.replace("<!--ssr-outlet-->", appHtml);
1227
+ } else {
1228
+ html = replaceAppDivContent(template, appHtml);
1229
+ }
1230
+ if (headTags) {
1231
+ html = html.replace("</head>", `${headTags}
1232
+ </head>`);
1233
+ }
1234
+ if (appCss) {
1235
+ html = html.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"[^>]*>/g, (match, href) => `<link rel="stylesheet" href="${href}" media="print" onload="this.media='all'">
1236
+ <noscript>${match}</noscript>`);
1237
+ html = html.replace("</head>", `${appCss}
1238
+ </head>`);
1239
+ }
1240
+ if (sessionScript) {
1241
+ html = html.replace("</body>", `${sessionScript}
1242
+ </body>`);
1243
+ }
1244
+ if (ssrData.length > 0) {
1245
+ const nonceAttr = nonce != null ? ` nonce="${nonce}"` : "";
1246
+ const ssrDataScript = `<script${nonceAttr}>window.__VERTZ_SSR_DATA__=${safeSerialize(ssrData)};</script>`;
1247
+ html = html.replace("</body>", `${ssrDataScript}
1248
+ </body>`);
1249
+ }
1250
+ return html;
1251
+ }
1252
+ function replaceAppDivContent(template, appHtml) {
1253
+ const openMatch = template.match(/<div[^>]*id="app"[^>]*>/);
1254
+ if (!openMatch || openMatch.index == null)
1255
+ return template;
1256
+ const openTag = openMatch[0];
1257
+ const contentStart = openMatch.index + openTag.length;
1258
+ let depth = 1;
1259
+ let i = contentStart;
1260
+ const len = template.length;
1261
+ while (i < len && depth > 0) {
1262
+ if (template[i] === "<") {
1263
+ if (template.startsWith("</div>", i)) {
1264
+ depth--;
1265
+ if (depth === 0)
1266
+ break;
1267
+ i += 6;
1268
+ } else if (template.startsWith("<div", i) && /^<div[\s>]/.test(template.slice(i, i + 5))) {
1269
+ depth++;
1270
+ i += 4;
1271
+ } else {
1272
+ i++;
1273
+ }
1274
+ } else {
1275
+ i++;
1276
+ }
1277
+ }
1278
+ if (depth !== 0) {
1279
+ return template;
1280
+ }
1281
+ return template.slice(0, contentStart) + appHtml + template.slice(i);
1282
+ }
1283
+
1284
+ export { escapeHtml, escapeAttr, serializeToHtml, getAccessSetForSSR, createAccessSetScript, resetSlotCounter, createSlotPlaceholder, encodeChunk, streamToString, collectStreamChunks, createTemplateChunk, renderToStream, safeSerialize, getStreamingRuntimeScript, createSSRDataChunk, compileThemeCached, createRequestContext, ssrRenderToString, ssrDiscoverQueries, ssrStreamNavQueries, createSessionScript, resolveRouteModulepreload, precomputeHandlerState, resolveSession, toPrefetchSession, evaluateAccessRule, reconstructDescriptors, matchUrlToPatterns, ssrRenderSinglePass, ssrRenderProgressive, injectIntoTemplate };