@jasonshimmy/vite-plugin-cer-app 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/commits.txt +1 -1
  3. package/dist/cli/commands/generate.d.ts.map +1 -1
  4. package/dist/cli/commands/generate.js +2 -0
  5. package/dist/cli/commands/generate.js.map +1 -1
  6. package/dist/cli/commands/preview.d.ts.map +1 -1
  7. package/dist/cli/commands/preview.js +21 -2
  8. package/dist/cli/commands/preview.js.map +1 -1
  9. package/dist/cli/index.js +1 -1
  10. package/dist/cli/index.js.map +1 -1
  11. package/dist/plugin/build-ssg.d.ts.map +1 -1
  12. package/dist/plugin/build-ssg.js +10 -21
  13. package/dist/plugin/build-ssg.js.map +1 -1
  14. package/dist/plugin/build-ssr.d.ts.map +1 -1
  15. package/dist/plugin/build-ssr.js +150 -27
  16. package/dist/plugin/build-ssr.js.map +1 -1
  17. package/dist/plugin/virtual/routes.d.ts.map +1 -1
  18. package/dist/plugin/virtual/routes.js +11 -1
  19. package/dist/plugin/virtual/routes.js.map +1 -1
  20. package/dist/runtime/app-template.d.ts +1 -1
  21. package/dist/runtime/app-template.d.ts.map +1 -1
  22. package/dist/runtime/app-template.js +6 -0
  23. package/dist/runtime/app-template.js.map +1 -1
  24. package/dist/runtime/composables/use-page-data.d.ts +15 -6
  25. package/dist/runtime/composables/use-page-data.d.ts.map +1 -1
  26. package/dist/runtime/composables/use-page-data.js +30 -9
  27. package/dist/runtime/composables/use-page-data.js.map +1 -1
  28. package/dist/runtime/entry-server-template.d.ts +1 -1
  29. package/dist/runtime/entry-server-template.d.ts.map +1 -1
  30. package/dist/runtime/entry-server-template.js +137 -16
  31. package/dist/runtime/entry-server-template.js.map +1 -1
  32. package/docs/data-loading.md +7 -6
  33. package/docs/getting-started.md +1 -1
  34. package/docs/rendering-modes.md +1 -1
  35. package/docs/server-api.md +9 -0
  36. package/package.json +1 -1
  37. package/src/__tests__/index.test.ts +21 -0
  38. package/src/__tests__/plugin/build-ssg.test.ts +265 -0
  39. package/src/__tests__/plugin/build-ssr.test.ts +180 -0
  40. package/src/__tests__/plugin/cer-app-plugin.test.ts +409 -0
  41. package/src/__tests__/plugin/dts-generator.test.ts +246 -0
  42. package/src/__tests__/plugin/resolve-config.test.ts +158 -0
  43. package/src/__tests__/plugin/virtual/error.test.ts +71 -0
  44. package/src/__tests__/plugin/virtual/loading.test.ts +72 -0
  45. package/src/__tests__/plugin/virtual/server-middleware.test.ts +102 -0
  46. package/src/__tests__/runtime/use-page-data.test.ts +81 -5
  47. package/src/__tests__/types/config.test.ts +23 -0
  48. package/src/cli/commands/generate.ts +2 -0
  49. package/src/cli/commands/preview.ts +21 -2
  50. package/src/cli/index.ts +1 -1
  51. package/src/plugin/build-ssg.ts +9 -22
  52. package/src/plugin/build-ssr.ts +149 -27
  53. package/src/plugin/virtual/routes.ts +12 -1
  54. package/src/runtime/app-template.ts +6 -0
  55. package/src/runtime/composables/use-page-data.ts +31 -9
  56. package/src/runtime/entry-server-template.ts +137 -16
  57. package/tsconfig.build.json +1 -1
  58. package/dist/__tests__/plugin/path-utils.test.d.ts +0 -2
  59. package/dist/__tests__/plugin/path-utils.test.d.ts.map +0 -1
  60. package/dist/__tests__/plugin/path-utils.test.js +0 -305
  61. package/dist/__tests__/plugin/path-utils.test.js.map +0 -1
  62. package/dist/__tests__/plugin/scanner.test.d.ts +0 -2
  63. package/dist/__tests__/plugin/scanner.test.d.ts.map +0 -1
  64. package/dist/__tests__/plugin/scanner.test.js +0 -143
  65. package/dist/__tests__/plugin/scanner.test.js.map +0 -1
  66. package/dist/__tests__/plugin/transforms/auto-import.test.d.ts +0 -2
  67. package/dist/__tests__/plugin/transforms/auto-import.test.d.ts.map +0 -1
  68. package/dist/__tests__/plugin/transforms/auto-import.test.js +0 -151
  69. package/dist/__tests__/plugin/transforms/auto-import.test.js.map +0 -1
  70. package/dist/__tests__/plugin/transforms/head-inject.test.d.ts +0 -2
  71. package/dist/__tests__/plugin/transforms/head-inject.test.d.ts.map +0 -1
  72. package/dist/__tests__/plugin/transforms/head-inject.test.js +0 -151
  73. package/dist/__tests__/plugin/transforms/head-inject.test.js.map +0 -1
  74. package/dist/__tests__/plugin/virtual/components.test.d.ts +0 -2
  75. package/dist/__tests__/plugin/virtual/components.test.d.ts.map +0 -1
  76. package/dist/__tests__/plugin/virtual/components.test.js +0 -47
  77. package/dist/__tests__/plugin/virtual/components.test.js.map +0 -1
  78. package/dist/__tests__/plugin/virtual/composables.test.d.ts +0 -2
  79. package/dist/__tests__/plugin/virtual/composables.test.d.ts.map +0 -1
  80. package/dist/__tests__/plugin/virtual/composables.test.js +0 -48
  81. package/dist/__tests__/plugin/virtual/composables.test.js.map +0 -1
  82. package/dist/__tests__/plugin/virtual/layouts.test.d.ts +0 -2
  83. package/dist/__tests__/plugin/virtual/layouts.test.d.ts.map +0 -1
  84. package/dist/__tests__/plugin/virtual/layouts.test.js +0 -59
  85. package/dist/__tests__/plugin/virtual/layouts.test.js.map +0 -1
  86. package/dist/__tests__/plugin/virtual/middleware.test.d.ts +0 -2
  87. package/dist/__tests__/plugin/virtual/middleware.test.d.ts.map +0 -1
  88. package/dist/__tests__/plugin/virtual/middleware.test.js +0 -58
  89. package/dist/__tests__/plugin/virtual/middleware.test.js.map +0 -1
  90. package/dist/__tests__/plugin/virtual/plugins.test.d.ts +0 -2
  91. package/dist/__tests__/plugin/virtual/plugins.test.d.ts.map +0 -1
  92. package/dist/__tests__/plugin/virtual/plugins.test.js +0 -73
  93. package/dist/__tests__/plugin/virtual/plugins.test.js.map +0 -1
  94. package/dist/__tests__/plugin/virtual/routes.test.d.ts +0 -2
  95. package/dist/__tests__/plugin/virtual/routes.test.d.ts.map +0 -1
  96. package/dist/__tests__/plugin/virtual/routes.test.js +0 -167
  97. package/dist/__tests__/plugin/virtual/routes.test.js.map +0 -1
  98. package/dist/__tests__/plugin/virtual/server-api.test.d.ts +0 -2
  99. package/dist/__tests__/plugin/virtual/server-api.test.d.ts.map +0 -1
  100. package/dist/__tests__/plugin/virtual/server-api.test.js +0 -72
  101. package/dist/__tests__/plugin/virtual/server-api.test.js.map +0 -1
  102. package/dist/__tests__/runtime/use-head.test.d.ts +0 -2
  103. package/dist/__tests__/runtime/use-head.test.d.ts.map +0 -1
  104. package/dist/__tests__/runtime/use-head.test.js +0 -202
  105. package/dist/__tests__/runtime/use-head.test.js.map +0 -1
  106. package/dist/__tests__/runtime/use-page-data.test.d.ts +0 -2
  107. package/dist/__tests__/runtime/use-page-data.test.d.ts.map +0 -1
  108. package/dist/__tests__/runtime/use-page-data.test.js +0 -41
  109. package/dist/__tests__/runtime/use-page-data.test.js.map +0 -1
@@ -3,66 +3,189 @@ import { join, resolve } from 'pathe'
3
3
  import { existsSync } from 'node:fs'
4
4
  import type { ResolvedCerConfig } from './dev-server.js'
5
5
 
6
+ /**
7
+ * Resolves the client build entry point for an SSR/SSG build.
8
+ *
9
+ * Priority order:
10
+ * 1. `index.html` at the project root — preferred because Vite writes a
11
+ * processed `index.html` to `dist/client/` with correct asset references,
12
+ * which `renderPath` then uses as the shell template for SSG pages.
13
+ * 2. `app/entry-client.ts` — fallback for projects that handle HTML injection
14
+ * themselves (e.g. a custom Express server).
15
+ * 3. `app/app.ts` — last resort (same bundle, no DSD hydration preamble).
16
+ */
17
+ function resolveClientEntry(config: ResolvedCerConfig): string {
18
+ const indexHtml = resolve(config.root, 'index.html')
19
+ if (existsSync(indexHtml)) return indexHtml
20
+ const entryClient = resolve(config.srcDir, 'entry-client.ts')
21
+ if (existsSync(entryClient)) return entryClient
22
+ return resolve(config.srcDir, 'app.ts')
23
+ }
24
+
6
25
  /**
7
26
  * The server entry template that wires all virtual modules together and
8
27
  * exports a request handler for Node.js (Express-compatible).
9
28
  */
10
- function generateServerEntryCode(config: ResolvedCerConfig): string {
29
+ function generateServerEntryCode(): string {
11
30
  return `// AUTO-GENERATED server entry by @jasonshimmy/vite-plugin-cer-app
31
+ import { readFileSync, existsSync } from 'node:fs'
32
+ import { dirname, join } from 'node:path'
33
+ import { fileURLToPath } from 'node:url'
12
34
  import 'virtual:cer-components'
13
35
  import routes from 'virtual:cer-routes'
14
36
  import layouts from 'virtual:cer-layouts'
15
37
  import plugins from 'virtual:cer-plugins'
16
38
  import apiRoutes from 'virtual:cer-server-api'
17
- import { html, registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
39
+ import { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
40
+ import { registerEntityMap, renderToStringWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
41
+ import entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'
18
42
  import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
19
- import { createStreamingSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware'
20
43
 
21
44
  registerBuiltinComponents()
22
45
 
23
- // Per-request VNode factory: initialize a fresh router at the request URL,
24
- // resolve the active layout from the matched route's meta, wrap the router-view
25
- // in that layout element, and call the route's data loader so the result is
26
- // serialized as window.__CER_DATA__ for client-side hydration.
46
+ // Pre-load the full HTML entity map so named entities like — decode
47
+ // correctly during SSR. Without this the bundled runtime falls back to a
48
+ // minimal set (<, >, & …) and re-escapes everything else.
49
+ registerEntityMap(entitiesJson)
50
+
51
+ // Load the Vite-built client index.html (dist/client/index.html) so every SSR
52
+ // response includes the client-side scripts needed for hydration and routing.
53
+ // The server bundle lives at dist/server/server.js, so ../client resolves correctly.
54
+ const _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')
55
+ const _clientTemplate = existsSync(_clientTemplatePath)
56
+ ? readFileSync(_clientTemplatePath, 'utf-8')
57
+ : null
58
+
59
+ // Merge the SSR rendered body with the Vite client shell so the final page
60
+ // contains both pre-rendered DSD content and the client bundle scripts.
61
+ function _mergeWithClientTemplate(ssrHtml, clientTemplate) {
62
+ const headTag = '<head>', headCloseTag = '</head>'
63
+ const bodyTag = '<body>', bodyCloseTag = '</body>'
64
+ const headStart = ssrHtml.indexOf(headTag)
65
+ const headEnd = ssrHtml.indexOf(headCloseTag)
66
+ const bodyStart = ssrHtml.indexOf(bodyTag)
67
+ const bodyEnd = ssrHtml.lastIndexOf(bodyCloseTag)
68
+ const ssrHead = headStart >= 0 && headEnd > headStart
69
+ ? ssrHtml.slice(headStart + headTag.length, headEnd).trim() : ''
70
+ const ssrBody = bodyStart >= 0 && bodyEnd > bodyStart
71
+ ? ssrHtml.slice(bodyStart + bodyTag.length, bodyEnd).trim() : ssrHtml
72
+ // Hoist <style> elements from the SSR body into the document <head> so
73
+ // JIT CSS rules are applied before the layout paints.
74
+ const headParts = ssrHead ? [ssrHead] : []
75
+ let ssrBodyContent = ssrBody
76
+ let pos = 0
77
+ while (pos < ssrBodyContent.length) {
78
+ const styleOpen = ssrBodyContent.indexOf('<style', pos)
79
+ if (styleOpen < 0) break
80
+ const styleClose = ssrBodyContent.indexOf('</style>', styleOpen)
81
+ if (styleClose < 0) break
82
+ headParts.push(ssrBodyContent.slice(styleOpen, styleClose + 8))
83
+ ssrBodyContent = ssrBodyContent.slice(0, styleOpen) + ssrBodyContent.slice(styleClose + 8)
84
+ pos = styleOpen
85
+ }
86
+ ssrBodyContent = ssrBodyContent.trim()
87
+ // Inject the pre-rendered layout+page as light DOM of the app mount element
88
+ // so it is visible before JS boots, then the client router takes over.
89
+ let merged = clientTemplate
90
+ if (merged.includes('<cer-layout-view></cer-layout-view>')) {
91
+ merged = merged.replace('<cer-layout-view></cer-layout-view>',
92
+ '<cer-layout-view>' + ssrBodyContent + '</cer-layout-view>')
93
+ } else if (merged.includes('<div id="app"></div>')) {
94
+ merged = merged.replace('<div id="app"></div>',
95
+ '<div id="app">' + ssrBodyContent + '</div>')
96
+ }
97
+ const headAdditions = headParts.filter(Boolean).join('\\n')
98
+ if (headAdditions) merged = merged.replace('</head>', headAdditions + '\\n</head>')
99
+ return merged
100
+ }
101
+
102
+ // Per-request async setup: initialize a fresh router, resolve the matched
103
+ // route and layout, pre-load the page module, and call the data loader.
104
+ // Returns the vnode tree, router, head additions, and the raw loader data.
27
105
  //
28
- // createStreamingSSRHandler threads the router through each component's SSR
29
- // context so concurrent renders never share state.
30
- const vnodeFactory = async (req) => {
106
+ // loaderData is returned (not set on globalThis) so the handler can assign it
107
+ // synchronously right before renderToStringWithJITCSS guaranteeing that
108
+ // concurrent renders (SSG concurrency > 1) never race on a shared global.
109
+ const _prepareRequest = async (req) => {
31
110
  const router = initRouter({ routes, initialUrl: req.url ?? '/' })
32
111
  const current = router.getCurrent()
33
112
  const { route, params } = router.matchRoute(current.path)
34
113
  const layoutName = route?.meta?.layout ?? 'default'
35
114
  const layoutTag = layouts[layoutName]
36
- const inner = html\`<router-view></router-view>\`
37
- const vnode = layoutTag
38
- ? { tag: layoutTag, props: {}, children: [inner] }
39
- : inner
40
115
 
41
- // Call the route's data loader (if present) and serialize for client hydration.
116
+ // Pre-load the page module so we can embed the component tag directly.
117
+ // This avoids the async router-view (which injects content via script tags
118
+ // and breaks Declarative Shadow DOM on initial parse).
119
+ let pageVnode = { tag: 'div', props: {}, children: [] }
42
120
  let head
121
+ let loaderData = null
43
122
  if (route?.load) {
44
123
  try {
45
124
  const mod = await route.load()
125
+ const pageTag = mod.default
126
+ if (pageTag) {
127
+ pageVnode = { tag: pageTag, props: { attrs: { ...params } }, children: [] }
128
+ }
46
129
  if (typeof mod.loader === 'function') {
47
130
  const query = current.query ?? {}
48
131
  const data = await mod.loader({ params, query, req })
49
132
  if (data !== undefined && data !== null) {
133
+ loaderData = data
50
134
  head = \`<script>window.__CER_DATA__ = \${JSON.stringify(data)}</script>\`
51
135
  }
52
136
  }
53
137
  } catch {
54
- // Loader errors are non-fatal during SSR; the client will refetch.
138
+ // Non-fatal: loader errors fall back to an empty page; client will refetch.
55
139
  }
56
140
  }
57
141
 
58
- return { vnode, router, head }
142
+ const vnode = layoutTag
143
+ ? { tag: layoutTag, props: {}, children: [pageVnode] }
144
+ : pageVnode
145
+
146
+ return { vnode, router, head, loaderData }
59
147
  }
60
148
 
61
- export const handler = createStreamingSSRHandler(vnodeFactory, {
62
- render: {
63
- dsd: ${config.ssr.dsd},
64
- },
65
- })
149
+ export const handler = async (req, res) => {
150
+ const { vnode, router, head, loaderData } = await _prepareRequest(req)
151
+
152
+ // Set loader data on globalThis synchronously before the render so
153
+ // usePageData() can read it. Because renderToStringWithJITCSSDSD is entirely
154
+ // synchronous and JavaScript is single-threaded, no concurrent request can
155
+ // overwrite __CER_DATA__ between this assignment and the read inside setup().
156
+ if (loaderData !== null) {
157
+ ;(globalThis).__CER_DATA__ = loaderData
158
+ }
159
+
160
+ // dsdPolyfill: false — we inject the polyfill manually after merging so it
161
+ // lands at the end of <body>, not inside <cer-layout-view> light DOM where
162
+ // scripts may not execute.
163
+ const { htmlWithStyles } = renderToStringWithJITCSSDSD(vnode, {
164
+ dsdPolyfill: false,
165
+ router,
166
+ })
167
+
168
+ // Clear immediately after the synchronous render so the value never leaks
169
+ // to the next request on this same server process.
170
+ delete (globalThis).__CER_DATA__
171
+
172
+ // Wrap the rendered body in a full HTML document and inject the head additions
173
+ // (loader data script, useHead() tags, JIT styles). No polyfill in body yet.
174
+ const ssrHtml = \`<!DOCTYPE html><html><head>\${head ?? ''}</head><body>\${htmlWithStyles}</body></html>\`
175
+
176
+ let finalHtml = _clientTemplate
177
+ ? _mergeWithClientTemplate(ssrHtml, _clientTemplate)
178
+ : ssrHtml
179
+
180
+ // Inject DSD polyfill at end of <body>, outside <cer-layout-view>, so the
181
+ // browser runs it after parsing the declarative shadow roots.
182
+ finalHtml = finalHtml.includes('</body>')
183
+ ? finalHtml.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')
184
+ : finalHtml + DSD_POLYFILL_SCRIPT
185
+
186
+ res.setHeader('Content-Type', 'text/html; charset=utf-8')
187
+ res.end(finalHtml)
188
+ }
66
189
 
67
190
  export { apiRoutes, plugins, layouts }
68
191
  export default handler
@@ -82,10 +205,9 @@ export async function buildSSR(
82
205
  const clientOutDir = join(config.root, 'dist/client')
83
206
  const serverOutDir = join(config.root, 'dist/server')
84
207
 
85
- // Determine client entry — prefer entry-client.ts, fall back to app.ts
86
- const clientEntry = existsSync(resolve(config.srcDir, 'entry-client.ts'))
87
- ? resolve(config.srcDir, 'entry-client.ts')
88
- : resolve(config.srcDir, 'app.ts')
208
+ // Resolve the client entry — index.html is preferred so Vite writes a
209
+ // processed index.html to dist/client/ for use as the SSG shell template.
210
+ const clientEntry = resolveClientEntry(config)
89
211
 
90
212
  // Build the client bundle
91
213
  console.log('[cer-app] Building client bundle...')
@@ -103,7 +225,7 @@ export async function buildSSR(
103
225
  })
104
226
 
105
227
  // Generate server entry source inline via a virtual plugin
106
- const serverEntryCode = generateServerEntryCode(config)
228
+ const serverEntryCode = generateServerEntryCode()
107
229
  const VIRTUAL_SERVER_ENTRY = 'virtual:cer-server-entry'
108
230
  const RESOLVED_SERVER_ENTRY = '\0virtual:cer-server-entry'
109
231
 
@@ -60,7 +60,7 @@ export async function generateRoutesCode(pagesDir: string): Promise<string> {
60
60
  return `// AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app\nconst routes = []\nexport default routes\n`
61
61
  }
62
62
 
63
- const entries = files.map((f) => {
63
+ const rawEntries = files.map((f) => {
64
64
  const entry = buildRouteEntry(f, pagesDir)
65
65
  // 404.ts convention: treat as catch-all not-found route
66
66
  if (basename(f) === '404.ts') {
@@ -68,6 +68,17 @@ export async function generateRoutesCode(pagesDir: string): Promise<string> {
68
68
  }
69
69
  return entry
70
70
  })
71
+
72
+ // Deduplicate by routePath — keep the first occurrence after sorting to
73
+ // avoid "Duplicate route path detected" warnings (e.g. when both 404.ts
74
+ // and [...all].ts resolve to the same /:all* catch-all route).
75
+ const seen = new Set<string>()
76
+ const entries = rawEntries.filter((e) => {
77
+ if (seen.has(e.routePath)) return false
78
+ seen.add(e.routePath)
79
+ return true
80
+ })
81
+
71
82
  const sorted = sortRoutes(entries)
72
83
 
73
84
  // Read each file's source once to extract static metadata (middleware + layout)
@@ -135,6 +135,12 @@ for (const plugin of plugins) {
135
135
 
136
136
  if (typeof window !== 'undefined') {
137
137
  await router.replace(window.location.pathname + window.location.search + window.location.hash)
138
+ // Clear SSR loader data after the initial navigation so that subsequent
139
+ // client-side navigations don't accidentally reuse it. We wait until after
140
+ // router.replace() so both the pre-rendered element (upgraded during
141
+ // component registration) and the new element from router.replace() can
142
+ // both call usePageData() and receive the hydration data.
143
+ delete (globalThis as any).__CER_DATA__
138
144
  createDOMJITCSS().mount()
139
145
  }
140
146
 
@@ -1,13 +1,22 @@
1
1
  /**
2
2
  * usePageData — reads SSR-injected loader data for the current page.
3
3
  *
4
- * During SSR/SSG the server calls the matched route's `loader()` function,
5
- * serializes the result as `window.__CER_DATA__`, and injects it into the
6
- * HTML `<head>`. On client hydration this composable reads that payload so
7
- * the page component can skip the initial data fetch.
4
+ * During SSR/SSG the server calls the matched route's `loader()` function
5
+ * and makes the result available in two ways:
8
6
  *
9
- * The data is cleared after the first call so subsequent client-side
10
- * navigations don't accidentally serve stale SSR data.
7
+ * 1. **Server render pass** the data is stored in a per-request
8
+ * `AsyncLocalStorage` context (set via `_cerDataStore.enterWith(data)`
9
+ * in the entry-server template). `usePageData()` reads this store so the
10
+ * component renders with real data in the initial SSR/SSG HTML.
11
+ *
12
+ * 2. **Client hydration** — the server also serializes the data as
13
+ * `window.__CER_DATA__` in the page `<head>`. The client entry captures
14
+ * this into `globalThis.__CER_DATA__` before the app boots. On first
15
+ * component instantiation `usePageData()` returns that value so the client
16
+ * starts with the correct state without an extra network round-trip.
17
+ *
18
+ * The client-side value is cleared after the first read so subsequent
19
+ * client-side navigations don't accidentally reuse stale SSR data.
11
20
  *
12
21
  * @returns The serialized loader result, or `null` if no SSR data is present.
13
22
  *
@@ -29,11 +38,24 @@
29
38
  * ```
30
39
  */
31
40
  export function usePageData<T = unknown>(): T | null {
32
- // Works in both SSR (globalThis) and browser (window) contexts.
33
41
  const g = globalThis as Record<string, unknown>
42
+
43
+ // Server-side: read from the per-request AsyncLocalStorage context.
44
+ // __CER_DATA_STORE__ is set by the entry-server template and is only present
45
+ // in Node.js, so this branch is tree-shaken out of the client bundle.
46
+ const store = g['__CER_DATA_STORE__'] as { getStore(): unknown } | undefined
47
+ if (store) {
48
+ const ssrData = store.getStore() as T | null | undefined
49
+ if (ssrData !== undefined && ssrData !== null) return ssrData
50
+ }
51
+
52
+ // Client-side: read from window.__CER_DATA__ captured by the client entry.
53
+ // Do NOT clear here — the data is cleared by app-template.ts after the
54
+ // initial router.replace() completes. This ensures both the pre-rendered
55
+ // element (upgraded during component registration) and the new element
56
+ // created by router.replace() can both access the SSR data without a
57
+ // race where the first read consumes it before the second can use it.
34
58
  const data = g['__CER_DATA__'] as T | undefined
35
59
  if (data === undefined || data === null) return null
36
- // Clear so that subsequent client navigations don't reuse stale SSR data.
37
- delete g['__CER_DATA__']
38
60
  return data
39
61
  }
@@ -6,26 +6,97 @@
6
6
  * Express/Fastify/Node http.
7
7
  */
8
8
  export const ENTRY_SERVER_TEMPLATE = `// Server-side entry — AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app
9
+ import { readFileSync, existsSync } from 'node:fs'
10
+ import { dirname, join } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { AsyncLocalStorage } from 'node:async_hooks'
9
13
  import 'virtual:cer-components'
10
14
  import routes from 'virtual:cer-routes'
11
15
  import layouts from 'virtual:cer-layouts'
12
16
  import plugins from 'virtual:cer-plugins'
13
17
  import apiRoutes from 'virtual:cer-server-api'
14
- import { html, registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
18
+ import { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
19
+ import { registerEntityMap, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
20
+ import entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'
15
21
  import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
16
- import { createStreamingSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware'
22
+ import { createSSRHandler } from '@jasonshimmy/custom-elements-runtime/ssr-middleware'
17
23
 
18
24
  registerBuiltinComponents()
19
25
 
26
+ // Pre-load the full HTML entity map so named entities like &mdash; decode
27
+ // correctly during SSR. Without this the bundled runtime falls back to a
28
+ // minimal set (&lt;, &gt;, &amp; …) and re-escapes everything else.
29
+ registerEntityMap(entitiesJson)
30
+
31
+ // Async-local storage for request-scoped SSR loader data.
32
+ // Using AsyncLocalStorage ensures concurrent SSR renders (e.g. SSG with
33
+ // concurrency > 1) never see each other's data — each request's async chain
34
+ // carries its own store value, so usePageData() is always race-condition-free.
35
+ const _cerDataStore = new AsyncLocalStorage()
36
+ // Expose the store so the usePageData() composable can read it server-side.
37
+ ;(globalThis).__CER_DATA_STORE__ = _cerDataStore
38
+
39
+ // Load the Vite-built client index.html (dist/client/index.html) so every SSR
40
+ // response includes the client-side scripts needed for hydration and routing.
41
+ // The server bundle lives at dist/server/server.js, so ../client resolves correctly.
42
+ const _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')
43
+ const _clientTemplate = existsSync(_clientTemplatePath)
44
+ ? readFileSync(_clientTemplatePath, 'utf-8')
45
+ : null
46
+
47
+ // Merge the SSR handler's full HTML document with the Vite client shell so the
48
+ // final page contains both pre-rendered DSD content and the client bundle scripts.
49
+ function _mergeWithClientTemplate(ssrHtml, clientTemplate) {
50
+ const headTag = '<head>', headCloseTag = '</head>'
51
+ const bodyTag = '<body>', bodyCloseTag = '</body>'
52
+ const headStart = ssrHtml.indexOf(headTag)
53
+ const headEnd = ssrHtml.indexOf(headCloseTag)
54
+ const bodyStart = ssrHtml.indexOf(bodyTag)
55
+ const bodyEnd = ssrHtml.lastIndexOf(bodyCloseTag)
56
+ const ssrHead = headStart >= 0 && headEnd > headStart
57
+ ? ssrHtml.slice(headStart + headTag.length, headEnd).trim() : ''
58
+ const ssrBody = bodyStart >= 0 && bodyEnd > bodyStart
59
+ ? ssrHtml.slice(bodyStart + bodyTag.length, bodyEnd).trim() : ssrHtml
60
+ // Hoist <style> elements from the SSR body into the document <head> so
61
+ // JIT CSS rules are applied before the layout paints.
62
+ const headParts = ssrHead ? [ssrHead] : []
63
+ let ssrBodyContent = ssrBody
64
+ let pos = 0
65
+ while (pos < ssrBodyContent.length) {
66
+ const styleOpen = ssrBodyContent.indexOf('<style', pos)
67
+ if (styleOpen < 0) break
68
+ const styleClose = ssrBodyContent.indexOf('</style>', styleOpen)
69
+ if (styleClose < 0) break
70
+ headParts.push(ssrBodyContent.slice(styleOpen, styleClose + 8))
71
+ ssrBodyContent = ssrBodyContent.slice(0, styleOpen) + ssrBodyContent.slice(styleClose + 8)
72
+ pos = styleOpen
73
+ }
74
+ ssrBodyContent = ssrBodyContent.trim()
75
+ // Inject the pre-rendered layout+page as light DOM of the app mount element
76
+ // so it is visible before JS boots, then the client router takes over.
77
+ let merged = clientTemplate
78
+ if (merged.includes('<cer-layout-view></cer-layout-view>')) {
79
+ merged = merged.replace('<cer-layout-view></cer-layout-view>',
80
+ '<cer-layout-view>' + ssrBodyContent + '</cer-layout-view>')
81
+ } else if (merged.includes('<div id="app"></div>')) {
82
+ merged = merged.replace('<div id="app"></div>',
83
+ '<div id="app">' + ssrBodyContent + '</div>')
84
+ }
85
+ const headAdditions = headParts.filter(Boolean).join('\\n')
86
+ if (headAdditions) merged = merged.replace('</head>', headAdditions + '\\n</head>')
87
+ return merged
88
+ }
89
+
20
90
  /**
21
91
  * Per-request VNode factory — initializes a fresh router at the request URL,
22
- * resolves the active layout from the matched route's meta, calls the matched
23
- * route's data loader (if any), and injects the serialized result into the
24
- * document head as window.__CER_DATA__ for client-side hydration.
92
+ * resolves the active layout from the matched route's meta, pre-loads the
93
+ * matched page component (bypassing the async router-view so DSD renders
94
+ * synchronously), calls the route's data loader (if any), and injects the
95
+ * serialized result into the document head as window.__CER_DATA__ for
96
+ * client-side hydration.
25
97
  *
26
98
  * createStreamingSSRHandler threads the router through each component's SSR
27
- * context so router-view reads from the per-request instance instead of the
28
- * shared activeRouterProxy singleton. This makes concurrent SSR requests safe.
99
+ * context so concurrent renders never share state.
29
100
  */
30
101
  const vnodeFactory = async (req) => {
31
102
  const router = initRouter({ routes, initialUrl: req.url ?? '/' })
@@ -33,38 +104,88 @@ const vnodeFactory = async (req) => {
33
104
  const { route, params } = router.matchRoute(current.path)
34
105
  const layoutName = route?.meta?.layout ?? 'default'
35
106
  const layoutTag = layouts[layoutName]
36
- const inner = html\`<router-view></router-view>\`
37
- const vnode = layoutTag
38
- ? { tag: layoutTag, props: {}, children: [inner] }
39
- : inner
40
107
 
41
- // Call the route's data loader (if present) and serialize for client hydration.
108
+ // Pre-load the page module so we can embed the component tag directly.
109
+ // This avoids the async router-view (which injects content via script tags
110
+ // and breaks Declarative Shadow DOM on initial parse).
111
+ let pageVnode = { tag: 'div', props: {}, children: [] }
42
112
  let head
43
113
  if (route?.load) {
44
114
  try {
45
115
  const mod = await route.load()
116
+ const pageTag = mod.default
117
+ if (pageTag) {
118
+ pageVnode = { tag: pageTag, props: { attrs: { ...params } }, children: [] }
119
+ }
46
120
  if (typeof mod.loader === 'function') {
47
121
  const query = current.query ?? {}
48
122
  const data = await mod.loader({ params, query, req })
49
123
  if (data !== undefined && data !== null) {
124
+ // Make data available to usePageData() during the SSR render pass.
125
+ // enterWith() scopes the value to the current async context so
126
+ // concurrent renders (SSG concurrency > 1) never share data.
127
+ _cerDataStore.enterWith(data)
50
128
  head = \`<script>window.__CER_DATA__ = \${JSON.stringify(data)}</script>\`
51
129
  }
52
130
  }
53
131
  } catch {
54
- // Loader errors are non-fatal during SSR; the client will refetch.
132
+ // Non-fatal: loader errors fall back to an empty page; client will refetch.
55
133
  }
56
134
  }
57
135
 
136
+ const vnode = layoutTag
137
+ ? { tag: layoutTag, props: {}, children: [pageVnode] }
138
+ : pageVnode
139
+
58
140
  return { vnode, router, head }
59
141
  }
60
142
 
143
+ // Capture the raw SSR handler and wrap it to merge the response with the
144
+ // Vite client template before sending — this injects the JS/CSS asset bundles
145
+ // so the browser can hydrate and enable client-side routing.
146
+ const _rawHandler = createSSRHandler(vnodeFactory, {
147
+ render: { dsd: true, dsdPolyfill: false },
148
+ })
149
+
61
150
  /**
62
151
  * The main request handler.
63
152
  * Compatible with Express, Fastify, and Node's raw http.createServer.
153
+ *
154
+ * Each request is run inside a fresh _cerDataStore.run() context so that
155
+ * concurrent renders (e.g. SSG with concurrency > 1) get isolated stores.
156
+ * vnodeFactory calls _cerDataStore.enterWith(loaderData) from within this
157
+ * context, making the data visible to usePageData() during SSR rendering
158
+ * without any global-state races.
64
159
  */
65
- export const handler = createStreamingSSRHandler(vnodeFactory, {
66
- render: { dsd: true },
67
- })
160
+ export const handler = async (req, res) => {
161
+ if (!_clientTemplate) {
162
+ // No client template — run handler normally, then inject DSD polyfill.
163
+ let _html = ''
164
+ await _cerDataStore.run(null, async () => {
165
+ await _rawHandler(req, { setHeader: () => {}, end: (body) => { _html = body } })
166
+ })
167
+ // Inject DSD polyfill at end of <body>, outside any custom element light DOM.
168
+ const _final = _html.includes('</body>')
169
+ ? _html.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')
170
+ : _html + DSD_POLYFILL_SCRIPT
171
+ res.setHeader('Content-Type', 'text/html; charset=utf-8')
172
+ return res.end(_final)
173
+ }
174
+ let _capturedHtml = ''
175
+ // Wrap _rawHandler in an isolated async-local-storage context so that
176
+ // vnodeFactory's enterWith() call is scoped to this request only.
177
+ await _cerDataStore.run(null, async () => {
178
+ // Omit write() to force the non-streaming collect-then-end code path.
179
+ await _rawHandler(req, { setHeader: () => {}, end: (body) => { _capturedHtml = body } })
180
+ })
181
+ let _merged = _mergeWithClientTemplate(_capturedHtml, _clientTemplate)
182
+ // Inject DSD polyfill at end of <body>, outside <cer-layout-view> light DOM.
183
+ _merged = _merged.includes('</body>')
184
+ ? _merged.replace('</body>', DSD_POLYFILL_SCRIPT + '</body>')
185
+ : _merged + DSD_POLYFILL_SCRIPT
186
+ res.setHeader('Content-Type', 'text/html; charset=utf-8')
187
+ res.end(_merged)
188
+ }
68
189
 
69
190
  export { apiRoutes, plugins, layouts, routes }
70
191
  export default handler
@@ -6,5 +6,5 @@
6
6
  "outDir": "dist",
7
7
  "rootDir": "src"
8
8
  },
9
- "exclude": ["node_modules", "dist", "src/cli/create/templates"]
9
+ "exclude": ["node_modules", "dist", "src/cli/create/templates", "src/__tests__"]
10
10
  }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=path-utils.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"path-utils.test.d.ts","sourceRoot":"","sources":["../../../src/__tests__/plugin/path-utils.test.ts"],"names":[],"mappings":""}