@hamur/adapter-vue 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +32 -2
  3. package/dist/chunks/browser-index-43pdsfp6.js +69 -0
  4. package/dist/chunks/browser-index-d1bxd40m.js +320 -0
  5. package/dist/chunks/browser-index-nhft0ewv.js +161 -0
  6. package/dist/src/adapter.js +402 -0
  7. package/dist/src/index.js +1348 -0
  8. package/dist/src/keepalive.js +6 -0
  9. package/dist/src/runtime/client.js +20 -0
  10. package/dist/src/runtime/island.js +45 -0
  11. package/dist/src/runtime/server.js +238 -0
  12. package/dist/types/src/adapter.d.ts +2 -0
  13. package/dist/types/src/async-data.d.ts +14 -0
  14. package/dist/types/src/client-component.d.ts +12 -0
  15. package/dist/types/src/client-fallback.d.ts +2 -0
  16. package/dist/types/src/components/AwaitValue.d.ts +15 -0
  17. package/dist/types/src/components/ClientFallback.server.d.ts +17 -0
  18. package/dist/types/src/components/ErrorBoundary.server.d.ts +21 -0
  19. package/dist/types/src/components/error-code.d.ts +1 -0
  20. package/dist/types/src/context.d.ts +65 -0
  21. package/dist/types/src/index.d.ts +329 -0
  22. package/dist/types/src/island.d.ts +68 -0
  23. package/dist/types/src/keepalive.d.ts +22 -0
  24. package/dist/types/src/lazy-hydration.d.ts +10 -0
  25. package/dist/types/src/markdown-page.d.ts +9 -0
  26. package/dist/types/src/markdown.d.ts +45 -0
  27. package/dist/types/src/plugin.d.ts +45 -0
  28. package/dist/types/src/route-boundary.d.ts +35 -0
  29. package/dist/types/src/route-boundary.server.d.ts +5 -0
  30. package/dist/types/src/runtime/client.d.ts +11 -0
  31. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  32. package/dist/types/src/runtime/hydration.d.ts +8 -0
  33. package/dist/types/src/runtime/island.d.ts +8 -0
  34. package/dist/types/src/runtime/server.d.ts +12 -0
  35. package/dist/types/src/server-island.d.ts +33 -0
  36. package/dist/types/src/svg.d.ts +10 -0
  37. package/package.json +46 -4
  38. package/src/adapter.ts +25 -0
  39. package/src/async-data.ts +77 -0
  40. package/src/client-component.ts +39 -0
  41. package/src/client-fallback.ts +2 -0
  42. package/src/components/Await.vue +30 -0
  43. package/src/components/AwaitValue.ts +41 -0
  44. package/src/components/ClientFallback.server.ts +41 -0
  45. package/src/components/ClientFallback.vue +31 -0
  46. package/src/components/ClientOnly.vue +16 -0
  47. package/src/components/DefaultErrorPage.vue +19 -0
  48. package/src/components/DevOnly.vue +8 -0
  49. package/src/components/ErrorBoundary.server.ts +69 -0
  50. package/src/components/ErrorBoundary.vue +32 -0
  51. package/src/components/Form.vue +85 -0
  52. package/src/components/Link.vue +200 -0
  53. package/src/components/Navigate.vue +16 -0
  54. package/src/components/Outlet.vue +28 -0
  55. package/src/components/error-code.ts +7 -0
  56. package/src/context.ts +391 -0
  57. package/src/index.ts +1528 -0
  58. package/src/island.ts +53 -0
  59. package/src/keepalive.ts +92 -0
  60. package/src/lazy-hydration.ts +53 -0
  61. package/src/markdown-page.ts +21 -0
  62. package/src/markdown.ts +80 -0
  63. package/src/plugin.ts +398 -0
  64. package/src/route-boundary.server.ts +29 -0
  65. package/src/route-boundary.ts +48 -0
  66. package/src/runtime/client.ts +137 -0
  67. package/src/runtime/hydration-dev.ts +38 -0
  68. package/src/runtime/hydration.ts +7 -0
  69. package/src/runtime/island.ts +60 -0
  70. package/src/runtime/server.ts +145 -0
  71. package/src/server-island.ts +38 -0
  72. package/src/svg.ts +28 -0
  73. package/src/vue.d.ts +5 -0
  74. package/src/webmcp.d.ts +18 -0
package/src/plugin.ts ADDED
@@ -0,0 +1,398 @@
1
+ import type { BunPlugin } from "bun"
2
+ import { compileScript, compileStyleAsync, compileTemplate, parse, type SFCStyleBlock } from "vue/compiler-sfc"
3
+ import { readFile } from "node:fs/promises"
4
+ import { realpathSync } from "node:fs"
5
+ import { dirname, extname, join, relative, resolve } from "node:path"
6
+ import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
7
+ import { DiagnosticError } from "hamur/kit"
8
+ import { mergeMappings, type MapPiece } from "hamur/adapter/dev"
9
+
10
+ const STYLE_NAMESPACE = "hamur-vue-style"
11
+
12
+ /**
13
+ * SFC hot hashes. Every version of the module shares one class-map object, so the registered component sees a new map;
14
+ * a block turned `scoped` reloads, since Vue patches an existing element without adding its scope attribute; a block added or
15
+ * removed loads the document again, since Bun 1.4.4 does not link a CSS import added to a self-accepting module.
16
+ */
17
+ function hmrFooter(
18
+ id: string,
19
+ hashes: { script: string; template: string; cssModules: string },
20
+ styleCount: number,
21
+ compileId: string,
22
+ ): string {
23
+ const hmrId = JSON.stringify(id)
24
+ const script = JSON.stringify(hashes.script)
25
+ const template = JSON.stringify(hashes.template)
26
+ const cssModules = JSON.stringify(hashes.cssModules)
27
+ const compile = JSON.stringify(compileId)
28
+ return `
29
+ _sfc_main.__hmrId = ${hmrId};
30
+ _sfc_main.__scriptHash = ${script};
31
+ _sfc_main.__templateHash = ${template};
32
+ _sfc_main.__cssModulesHash = ${cssModules};
33
+ _sfc_main.__styleCount = ${styleCount};
34
+ _sfc_main.__compileId = ${compile};
35
+ globalThis.__VUE_HMR_RUNTIME__?.createRecord(${hmrId}, _sfc_main);
36
+ import.meta.hot.accept((mod) => {
37
+ const hmr = globalThis.__VUE_HMR_RUNTIME__;
38
+ if (!mod || !hmr) return;
39
+ const next = mod.default;
40
+ if (next.__styleCount !== ${styleCount}) return location.reload();
41
+ const maps = _sfc_main.__cssModules;
42
+ for (const name of Object.keys(maps)) delete maps[name];
43
+ next.__cssModules = Object.assign(maps, next.__cssModules);
44
+ if (next.__compileId === ${compile} || next.__scriptHash !== ${script} || (next.__scopeId && !_sfc_main.__scopeId)) hmr.reload(${hmrId}, next);
45
+ else if (next.__templateHash !== ${template} || next.__cssModulesHash !== ${cssModules}) hmr.rerender(${hmrId}, next.render);
46
+ });`
47
+ }
48
+
49
+ const PREPROCESSED: Record<string, string> = {
50
+ scss: "sass",
51
+ sass: "sass",
52
+ less: "less",
53
+ styl: "stylus",
54
+ stylus: "stylus",
55
+ }
56
+ const PLAIN_LANGS = ["css", "postcss"]
57
+ const SUPPORTED_LANGS = "css, postcss, scss, sass, less, styl, stylus"
58
+
59
+ const langOf = (style: SFCStyleBlock): string =>
60
+ style.lang ?? (style.src ? extname(style.src).slice(1) || "css" : "css")
61
+
62
+ function resolveSrc(src: string, dir: string): string {
63
+ try {
64
+ return Bun.resolveSync(src, dir)
65
+ } catch {
66
+ return resolve(dir, src)
67
+ }
68
+ }
69
+
70
+ const scopeIdOf = (path: string) => `data-v-${Bun.hash(path).toString(16).slice(0, 8)}`
71
+ const moduleIdOf = (path: string, index: number) => Bun.hash(`${path}?${index}`).toString(36).slice(0, 6)
72
+
73
+ const SESSION = Date.now().toString(36)
74
+ let compiles = 0
75
+
76
+ interface TemplateNode {
77
+ type: number
78
+ tag?: string
79
+ tagType?: number
80
+ content?: unknown
81
+ props?: Array<{ type: number; name?: string; arg?: unknown; nameLoc?: unknown; value?: unknown; loc?: unknown }>
82
+ children?: unknown[]
83
+ loc?: { start: { line: number; column: number } }
84
+ }
85
+
86
+ const ROOT = 0
87
+ const ELEMENT = 1
88
+ const TEXT = 2
89
+ const ATTRIBUTE = 6
90
+ const DIRECTIVE = 7
91
+ const PLAIN_ELEMENT = 0
92
+ const LOCATOR_ATTRIBUTE = "data-hamur-src"
93
+
94
+ /** The module's path relative to `rootDir` when it is an app source (not under `node_modules` or the build dir). */
95
+ export function appModuleId(rootDir: string, buildDir: string): (path: string) => string | undefined {
96
+ let real = rootDir
97
+ try {
98
+ real = realpathSync(rootDir)
99
+ } catch {}
100
+ const roots = [...new Set([rootDir, real])]
101
+ const build = relative(rootDir, buildDir)
102
+ const inBuild = (id: string) =>
103
+ build !== "" && !build.startsWith("..") && (id === build || id.startsWith(`${build}/`))
104
+ return (path) => {
105
+ if (path.includes("/node_modules/")) return undefined
106
+ for (const root of roots) {
107
+ const id = relative(root, path)
108
+ if (!id.startsWith("..") && !id.startsWith("/")) return inBuild(id) ? undefined : id
109
+ }
110
+ return undefined
111
+ }
112
+ }
113
+
114
+ /**
115
+ * The source locator, dev only: a node transform that gives the template's single root element, when it is a plain
116
+ * HTML element, `data-hamur-src="<file>:<line>:<column>"`; `origin` is where the template's content starts in the file.
117
+ */
118
+ export function locateRootElement(
119
+ file: string,
120
+ origin: { line: number; column: number },
121
+ ): (node: TemplateNode, context: { parent: TemplateNode | null }) => void {
122
+ return (node, { parent }) => {
123
+ if (node.type !== ELEMENT || node.tagType !== PLAIN_ELEMENT || !node.loc || parent?.type !== ROOT) return
124
+ const significant = (parent.children ?? []).filter((child) => {
125
+ const { type, content } = child as TemplateNode
126
+ return type === TEXT ? String(content).trim() !== "" : type === ELEMENT || type === 5
127
+ })
128
+ if (significant.length !== 1 || significant[0] !== node) return
129
+ const { line, column } = node.loc.start
130
+ const at = `${file}:${origin.line + line - 1}:${line === 1 ? origin.column + column - 1 : column}`
131
+ const loc = node.loc
132
+ ;(node.props ??= []).push({
133
+ type: ATTRIBUTE,
134
+ name: LOCATOR_ATTRIBUTE,
135
+ nameLoc: loc,
136
+ value: { type: TEXT, content: at, loc },
137
+ loc,
138
+ })
139
+ }
140
+ }
141
+
142
+ /** The tags under which a script imports `DevOnly` from this adapter, as written and in kebab-case. */
143
+ export function devOnlyTags(script: string): Set<string> {
144
+ const tags = new Set<string>()
145
+ for (const found of script.matchAll(/import\s*\{([^}]*)\}\s*from\s*["']@hamur\/adapter-vue["']/g)) {
146
+ for (const part of found[1]!.split(",")) {
147
+ const [imported, local = imported] = part
148
+ .trim()
149
+ .split(/\s+as\s+/)
150
+ .map((name) => name.trim())
151
+ if (imported !== "DevOnly" || !local) continue
152
+ tags.add(local)
153
+ tags.add(local.replace(/\B([A-Z])/g, "-$1").toLowerCase())
154
+ }
155
+ }
156
+ return tags
157
+ }
158
+
159
+ const isFallbackSlot = (child: unknown): boolean => {
160
+ const node = child as TemplateNode
161
+ return (
162
+ node.type === ELEMENT &&
163
+ node.tag === "template" &&
164
+ (node.props ?? []).some(
165
+ (prop) =>
166
+ prop.type === DIRECTIVE &&
167
+ prop.name === "slot" &&
168
+ (prop.arg as { content?: string } | undefined)?.content === "fallback",
169
+ )
170
+ )
171
+ }
172
+
173
+ /** Production: a node transform that keeps only the `#fallback` slot among the children of a `DevOnly` element. */
174
+ export function dropDevOnlyChildren(tags: ReadonlySet<string>): (node: TemplateNode) => void {
175
+ return (node) => {
176
+ if (node.type !== ELEMENT || !node.tag || !tags.has(node.tag) || !node.children) return
177
+ node.children = node.children.filter(isFallbackSlot)
178
+ }
179
+ }
180
+
181
+ /** `__VUE_PROD_DEVTOOLS__` is true in `hamur dev` and false in a build. */
182
+ const featureFlags = (dev: boolean) => ({
183
+ __VUE_OPTIONS_API__: "true",
184
+ __VUE_PROD_DEVTOOLS__: String(dev),
185
+ __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: "false",
186
+ })
187
+
188
+ /** Bun.serve's dev bundler ignores `define` changed in a plugin, so the flags are replaced in Vue's own modules. */
189
+ export function vueFeatureFlags(): AdapterTransform {
190
+ return {
191
+ name: "hamur-vue-feature-flags",
192
+ filter: { id: /[\\/]node_modules[\\/](?:vue|@vue[\\/][^\\/]+)[\\/]dist[\\/][^\\/]*esm-bundler\.js$/ },
193
+ transform(code) {
194
+ let contents = code
195
+ for (const [flag, value] of Object.entries(featureFlags(true))) contents = contents.replaceAll(flag, value)
196
+ return contents === code ? undefined : contents
197
+ },
198
+ }
199
+ }
200
+
201
+ export function vuePlugin(ctx: AdapterBuildContext): BunPlugin {
202
+ const blocks = new Map<string, { style: SFCStyleBlock; scopeId: string; moduleId: string; first?: string }>()
203
+ const ssr = ctx.target === "server"
204
+ const appModule = ctx.dev ? appModuleId(ctx.rootDir, ctx.buildDir) : () => undefined
205
+ return {
206
+ name: `hamur-vue-${ctx.target}`,
207
+ setup(build) {
208
+ build.config.define = { ...featureFlags(ctx.dev), ...build.config.define }
209
+
210
+ if (ssr) {
211
+ const runtime = Bun.resolveSync("vue/dist/vue.runtime.esm-bundler.js", ctx.rootDir)
212
+ const serverRenderer = Bun.resolveSync("@vue/server-renderer/dist/server-renderer.esm-bundler.js", runtime)
213
+ build.onResolve({ filter: /^vue$/ }, () => ({ path: runtime }))
214
+ build.onResolve({ filter: /^vue\/server-renderer$/ }, () => ({ path: serverRenderer }))
215
+ }
216
+
217
+ build.onLoad({ filter: /\.vue$/, namespace: "file" }, async ({ path }) => {
218
+ const source = await Bun.file(path).text()
219
+ const { descriptor, errors } = parse(source, { filename: path })
220
+ if (errors.length > 0) throw errors[0]
221
+
222
+ const scopeId = scopeIdOf(path)
223
+ const id = scopeId.slice("data-v-".length)
224
+ const scoped = descriptor.styles.some((style) => style.scoped)
225
+
226
+ const script =
227
+ descriptor.script || descriptor.scriptSetup
228
+ ? compileScript(descriptor, { id, isProd: !ctx.dev, genDefaultAs: "_sfc_main", sourceMap: true })
229
+ : { content: "const _sfc_main = {};", bindings: undefined, lang: undefined, map: undefined }
230
+ const parts: Array<{ text: string; map?: MapPiece["map"]; sourceLine?: number; sourceColumn?: number }> = [
231
+ { text: script.content, map: script.map },
232
+ ]
233
+ const hot = ctx.hmr && !ssr
234
+ let templateCode = ""
235
+
236
+ if (descriptor.template) {
237
+ const devOnly = ctx.dev
238
+ ? new Set<string>()
239
+ : devOnlyTags(`${descriptor.scriptSetup?.content ?? ""}\n${descriptor.script?.content ?? ""}`)
240
+ const located = appModule(path)
241
+ const nodeTransforms = [
242
+ ...(devOnly.size ? [dropDevOnlyChildren(devOnly)] : []),
243
+ ...(located === undefined ? [] : [locateRootElement(located, descriptor.template.loc.start)]),
244
+ ]
245
+ const template = compileTemplate({
246
+ source: descriptor.template.content,
247
+ filename: path,
248
+ id: scopeId,
249
+ scoped,
250
+ ssr,
251
+ ssrCssVars: descriptor.cssVars,
252
+ compilerOptions: {
253
+ scopeId: scoped ? scopeId : undefined,
254
+ bindingMetadata: script.bindings,
255
+ sourceMap: true,
256
+ ...(nodeTransforms.length ? { nodeTransforms } : {}),
257
+ },
258
+ })
259
+ if (template.errors.length > 0) throw template.errors[0]
260
+ templateCode = template.code
261
+ const renderName = ssr ? "ssrRender" : "render"
262
+ const { start } = descriptor.template.loc
263
+ parts.push(
264
+ { text: template.code, map: template.map, sourceLine: start.line - 1, sourceColumn: start.column - 1 },
265
+ { text: `_sfc_main.${renderName} = ${renderName};` },
266
+ )
267
+ }
268
+ if (scoped) parts.push({ text: `_sfc_main.__scopeId = ${JSON.stringify(scopeId)};` })
269
+
270
+ const cssModules: Record<string, Record<string, string>> = {}
271
+ for (const [index, style] of descriptor.styles.entries()) {
272
+ const lang = langOf(style)
273
+ if (!PLAIN_LANGS.includes(lang) && !(lang in PREPROCESSED))
274
+ throw new DiagnosticError("HAMUR_E4101", `<style lang="${lang}"> is not supported (${SUPPORTED_LANGS})`)
275
+ if (lang in PREPROCESSED && !ctx.preprocessStyle) {
276
+ throw new DiagnosticError(
277
+ "HAMUR_E4102",
278
+ `<style lang="${lang}"> needs the @hamur/css module: install @hamur/css and ${PREPROCESSED[lang]} and add "@hamur/css" to modules`,
279
+ )
280
+ }
281
+ const block: { style: SFCStyleBlock; scopeId: string; moduleId: string; first?: string } = {
282
+ style,
283
+ scopeId,
284
+ moduleId: moduleIdOf(path, index),
285
+ }
286
+ if (ssr && !style.module) continue
287
+ if (!ssr) parts.unshift({ text: `import ${JSON.stringify(`${STYLE_NAMESPACE}:${path}.${index}.css`)};` })
288
+ if (ctx.dev && !ssr && !style.module) continue
289
+ const css = await compileBlock(path, block)
290
+ if (style.module) cssModules[style.module === true ? "$style" : style.module] = css.modules ?? {}
291
+ if (ssr || ctx.dev) continue
292
+ block.first = css.code
293
+ blocks.set(`${path}.${index}.css`, block)
294
+ }
295
+ if (Object.keys(cssModules).length > 0 || hot)
296
+ parts.push({ text: `_sfc_main.__cssModules = ${JSON.stringify(cssModules)};` })
297
+ if (hot) {
298
+ const hash = (text: string) => Bun.hash(text).toString(16)
299
+ const hashes = {
300
+ script: hash(`${descriptor.script?.content ?? ""}\0${descriptor.scriptSetup?.content ?? ""}`),
301
+ template: hash(templateCode),
302
+ cssModules: hash(JSON.stringify(cssModules)),
303
+ }
304
+ parts.push({ text: hmrFooter(id, hashes, descriptor.styles.length, `${SESSION}.${++compiles}`) })
305
+ }
306
+
307
+ parts.push({ text: "export default _sfc_main;" })
308
+ const pieces: MapPiece[] = []
309
+ let line = 0
310
+ for (const { text, map, sourceLine, sourceColumn } of parts) {
311
+ if (map) pieces.push({ map, line, sourceLine, sourceColumn })
312
+ line += text.split("\n").length
313
+ }
314
+ let contents = parts.map(({ text }) => text).join("\n")
315
+ if (pieces.length > 0) {
316
+ const inline = {
317
+ version: 3,
318
+ sources: [relative(ctx.rootDir, path).split("\\").join("/")],
319
+ sourcesContent: [source],
320
+ names: [],
321
+ mappings: mergeMappings(pieces),
322
+ }
323
+ contents += `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(inline)).toString("base64")}`
324
+ }
325
+ return { contents, loader: script.lang === "ts" || script.lang === "tsx" ? "ts" : "js" }
326
+ })
327
+
328
+ build.onResolve({ filter: new RegExp(`^${STYLE_NAMESPACE}:`) }, ({ path }) => ({
329
+ path: path.slice(STYLE_NAMESPACE.length + 1),
330
+ namespace: STYLE_NAMESPACE,
331
+ }))
332
+ build.onLoad({ filter: /.*/, namespace: STYLE_NAMESPACE }, async ({ path }) => {
333
+ if (ctx.dev) return { contents: await devBlock(path), loader: "css" }
334
+ const block = blocks.get(path)
335
+ const first = block?.first
336
+ if (block) block.first = undefined
337
+ return {
338
+ contents: first ?? (block ? (await compileBlock(path.replace(/\.\d+\.css$/, ""), block)).code : ""),
339
+ loader: "css",
340
+ }
341
+ })
342
+ },
343
+ }
344
+
345
+ /** Dev: the `.vue` is parsed from disk on every load, since this load can run before the `.vue`'s own `onLoad` sees an edit. */
346
+ async function devBlock(path: string): Promise<string> {
347
+ const sfc = path.replace(/\.\d+\.css$/, "")
348
+ const index = Number(path.slice(sfc.length + 1, -".css".length))
349
+ const style = parse(
350
+ await Bun.file(sfc)
351
+ .text()
352
+ .catch(() => ""),
353
+ { filename: sfc },
354
+ ).descriptor.styles[index]
355
+ return style
356
+ ? (await compileBlock(sfc, { style, scopeId: scopeIdOf(sfc), moduleId: moduleIdOf(sfc, index) })).code
357
+ : ""
358
+ }
359
+
360
+ async function compileBlock(
361
+ path: string,
362
+ { style, scopeId, moduleId }: { style: SFCStyleBlock; scopeId: string; moduleId: string },
363
+ ) {
364
+ const lang = langOf(style)
365
+ const file = style.src ? resolveSrc(style.src, dirname(path)) : path
366
+ let source = style.content
367
+ if (style.src) {
368
+ source = await readFile(file, "utf8").catch(() => {
369
+ throw new DiagnosticError("HAMUR_E4103", `<style src="${style.src}"> was not found (looked for ${file})`)
370
+ })
371
+ }
372
+ if (lang in PREPROCESSED) source = (await ctx.preprocessStyle!({ lang, code: source, file })).code
373
+ const css = await compileStyleAsync({
374
+ source,
375
+ filename: path,
376
+ id: scopeId,
377
+ scoped: style.scoped,
378
+ isProd: !ctx.dev,
379
+ ...(style.module
380
+ ? { modules: true, modulesOptions: { generateScopedName: (name: string) => `_${name}_${moduleId}` } }
381
+ : {}),
382
+ })
383
+ if (css.errors.length > 0) throw css.errors[0]
384
+ return css
385
+ }
386
+ }
387
+
388
+ const CLIENT_RUNTIME = join(import.meta.dir, "runtime/client.ts")
389
+ const HYDRATION_DEV = join(import.meta.dir, "runtime/hydration-dev.ts")
390
+
391
+ /** In `hamur dev` the client runtime imports `runtime/hydration-dev.ts` first, which feeds the hydration mismatch report; a build adds nothing. */
392
+ export function vueHydrationPlugin(): AdapterTransform {
393
+ return {
394
+ name: "hamur-vue-hydration",
395
+ filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
396
+ transform: (code) => `import ${JSON.stringify(HYDRATION_DEV)}; ${code}`,
397
+ }
398
+ }
@@ -0,0 +1,29 @@
1
+ import type { ComponentInternalInstance } from "vue"
2
+ import { ssrRenderSlotInner, ssrRenderVNode } from "vue/server-renderer"
3
+ import { flatten, toVNode } from "./components/ErrorBoundary.server.ts"
4
+ import { caught } from "./route-boundary.ts"
5
+
6
+ /** Vue's server renderer writes output as it goes, so the slot is rendered into a buffer and kept only if nothing in it failed. */
7
+ export function ssrRender(
8
+ _ctx: unknown,
9
+ push: (item: unknown) => void,
10
+ instance: ComponentInternalInstance,
11
+ _attrs: unknown,
12
+ props: { fallback: (error: unknown) => unknown },
13
+ ): void {
14
+ const items: unknown[] = []
15
+ ssrRenderSlotInner(instance.slots, "default", {}, null, (item) => items.push(item), instance)
16
+ push(
17
+ (async () => {
18
+ let failure: { error: unknown } | undefined
19
+ const html = await flatten(items).catch((error: unknown) => {
20
+ failure = { error }
21
+ })
22
+ failure ??= caught.get(instance)
23
+ if (!failure) return `<!--[-->${html}<!--]-->`
24
+ const buffer: unknown[] = []
25
+ ssrRenderVNode((item) => buffer.push(item), toVNode(props.fallback(failure.error)), instance)
26
+ return flatten(buffer)
27
+ })(),
28
+ )
29
+ }
@@ -0,0 +1,48 @@
1
+ import { defineComponent, getCurrentInstance, onErrorCaptured, shallowRef, watch } from "vue"
2
+ import type { ComponentInternalInstance, PropType } from "vue"
3
+
4
+ /** `onErrorCaptured` also runs while Vue renders on the server, and swallows the error there; `ssrRender` reads what it caught. */
5
+ export const caught = new WeakMap<ComponentInternalInstance, { error: unknown }>()
6
+
7
+ /** Errors a route boundary's own render threw, which no route boundary above may catch. */
8
+ export const rethrown = new WeakSet<object>()
9
+
10
+ /** Wraps a boundary's render: what comes up from it is marked, and goes on to the app's error handler. */
11
+ export const Guard = defineComponent({
12
+ name: "HamurBoundaryGuard",
13
+ setup(_, { slots }) {
14
+ onErrorCaptured((thrown) => {
15
+ if (typeof thrown === "object" && thrown !== null) rethrown.add(thrown)
16
+ })
17
+ return () => slots.default?.()[0]
18
+ },
19
+ })
20
+
21
+ /** Shows its fallback for an error below it until `resetOn` is another object, which every navigation and update builds. */
22
+ export const RouteBoundary = defineComponent({
23
+ name: "HamurRouteBoundary",
24
+ props: {
25
+ resetOn: { type: null, default: null },
26
+ fallback: { type: Function as PropType<(error: unknown) => unknown>, required: true },
27
+ },
28
+ setup(props, { slots }) {
29
+ const failed = shallowRef(false)
30
+ const error = shallowRef<unknown>()
31
+ watch(
32
+ () => props.resetOn,
33
+ () => {
34
+ failed.value = false
35
+ error.value = undefined
36
+ },
37
+ )
38
+ const instance = getCurrentInstance()!
39
+ onErrorCaptured((thrown) => {
40
+ if (typeof thrown === "object" && thrown !== null && rethrown.has(thrown)) return
41
+ error.value = thrown
42
+ failed.value = true
43
+ caught.set(instance, { error: thrown })
44
+ return false
45
+ })
46
+ return () => (failed.value ? (props.fallback(error.value) as never) : slots.default?.())
47
+ },
48
+ })
@@ -0,0 +1,137 @@
1
+ import {
2
+ createApp,
3
+ createSSRApp,
4
+ defineComponent,
5
+ h,
6
+ inject,
7
+ onBeforeUnmount,
8
+ onMounted,
9
+ onUpdated,
10
+ shallowRef,
11
+ useId,
12
+ } from "vue"
13
+ import type { AppConfig, Component } from "vue"
14
+ import { setAdapterInstance } from "hamur/adapter"
15
+ import type { ClientContext } from "hamur/adapter"
16
+ import {
17
+ fetchServerComponent,
18
+ reportClientError,
19
+ serverComponentAttributes,
20
+ serverComponentProps,
21
+ takeServerHTML,
22
+ } from "hamur/adapter"
23
+ import type { ServerComponentView } from "hamur/adapter"
24
+ import type { HeadEntry } from "hamur/app"
25
+ import { clientFallbackIds } from "../client-fallback.ts"
26
+ import { AppKey, createRoot } from "../context.ts"
27
+ import type { HamurRoot } from "../context.ts"
28
+ import { devHydration } from "./hydration.ts"
29
+
30
+ export { installKeepAlive } from "../context.ts"
31
+
32
+ let root: HamurRoot | undefined
33
+
34
+ // `ErrorCodes` 0 and 1 of @vue/runtime-core 3.5.44: dev strings, then the production reference links.
35
+ const RENDER_INFO = new Set([
36
+ "setup function",
37
+ "render function",
38
+ "https://vuejs.org/error-reference/#runtime-0",
39
+ "https://vuejs.org/error-reference/#runtime-1",
40
+ ])
41
+
42
+ /** A setup or render throw is a render failure; anything else shows the error page only when fatal. In dev the others reach the overlay; `import.meta.dev` is not defined in the dev client, `import.meta.hot` is. */
43
+ export function rootErrorHandler(app: ClientContext["app"]): NonNullable<AppConfig["errorHandler"]> {
44
+ return (error, _instance, info) => {
45
+ const render = RENDER_INFO.has(info)
46
+ if (!render) {
47
+ if (import.meta.hot && typeof reportError === "function") reportError(error)
48
+ else console.error(error)
49
+ }
50
+ reportClientError(app, error, { render })
51
+ }
52
+ }
53
+
54
+ async function start(create: typeof createSSRApp, ctx: ClientContext): Promise<void> {
55
+ root = createRoot(ctx)
56
+ for (const id of create === createSSRApp && Array.isArray(ctx.payload.clientFallback)
57
+ ? ctx.payload.clientFallback
58
+ : [])
59
+ clientFallbackIds.add(String(id))
60
+ const app = create(root.component)
61
+ app.config.errorHandler = rootErrorHandler(ctx.app)
62
+ root.install(app)
63
+ await setAdapterInstance(ctx.app, app)
64
+ const watch = create === createSSRApp ? devHydration.watch?.(ctx.root) : undefined
65
+ try {
66
+ app.mount(ctx.root)
67
+ } finally {
68
+ watch?.done()
69
+ }
70
+ }
71
+
72
+ export function hydrate(ctx: ClientContext): Promise<void> {
73
+ return start(createSSRApp, ctx)
74
+ }
75
+
76
+ export function mount(ctx: ClientContext): Promise<void> {
77
+ return start(createApp, ctx)
78
+ }
79
+
80
+ export function update(ctx: ClientContext): Promise<void> {
81
+ if (!root) throw new Error("update() called before hydrate() or mount()")
82
+ return root.update(ctx)
83
+ }
84
+
85
+ export { clientComponent } from "../client-component.ts"
86
+
87
+ /** The client side of a server-only component: the server HTML, never hydrated; a new props text fetches it anew. */
88
+ export function serverComponent(name: string): Component {
89
+ return defineComponent({
90
+ name: `${name}.server`,
91
+ inheritAttrs: false,
92
+ setup(_, { attrs, slots }) {
93
+ const app = inject(AppKey)!
94
+ const uid = useId()
95
+ const textOf = () => serverComponentProps(name, { ...attrs }, slots.default !== undefined)
96
+ const initial = takeServerHTML(app, uid, name)
97
+ const view = shallowRef<ServerComponentView>({ html: initial ?? "" })
98
+ const failed = shallowRef<{ error: unknown }>()
99
+ let requested = initial === undefined ? undefined : textOf()
100
+ let controller: AbortController | undefined
101
+ let head: HeadEntry | undefined
102
+ const sync = () => {
103
+ const text = textOf()
104
+ if (text === requested) return
105
+ requested = text
106
+ controller?.abort()
107
+ const current = (controller = new AbortController())
108
+ fetchServerComponent(app, name, text, current.signal)
109
+ .then((next) => {
110
+ if (current.signal.aborted) return
111
+ head?.dispose()
112
+ head = next.head ? app.head.push(next.head) : undefined
113
+ view.value = next
114
+ })
115
+ .catch((error: unknown) => {
116
+ if (!current.signal.aborted) failed.value = { error }
117
+ })
118
+ }
119
+ onMounted(sync)
120
+ onUpdated(sync)
121
+ onBeforeUnmount(() => {
122
+ controller?.abort()
123
+ head?.dispose()
124
+ })
125
+ return () => {
126
+ if (failed.value) throw failed.value.error
127
+ textOf()
128
+ return h("hamur-component", {
129
+ name,
130
+ uid,
131
+ ...serverComponentAttributes(name),
132
+ innerHTML: view.value.html as string,
133
+ })
134
+ }
135
+ },
136
+ })
137
+ }
@@ -0,0 +1,38 @@
1
+ import { snapshotHydration } from "hamur/adapter/dev"
2
+ import { devHydration } from "./hydration.ts"
3
+
4
+ // @vue/runtime-core 3.5 prints each hydration warning so: "[Vue warn]: Hydration text content mismatch on", <element>, …, " at <Name", …
5
+ const MISMATCH = "[Vue warn]: Hydration "
6
+ const TRACE = /^\s*at <([^\s>]+)/
7
+
8
+ /**
9
+ * Vue hands the differing element to `console.warn` only: `app.config.warnHandler` gets it as a string. So `console.warn` is
10
+ * watched while the root hydrates, and Vue prints its warnings itself as before.
11
+ */
12
+ devHydration.watch = (root) => {
13
+ const snapshot = snapshotHydration(root)
14
+ const warn = console.warn
15
+ let signalled = false
16
+ let component: string | undefined
17
+ let node: Element | undefined
18
+ console.warn = (...args: unknown[]) => {
19
+ if (typeof args[0] === "string" && args[0].startsWith(MISMATCH)) {
20
+ signalled = true
21
+ node ??= args.find((arg): arg is Element => typeof Element !== "undefined" && arg instanceof Element)
22
+ for (const arg of args) {
23
+ const name = typeof arg === "string" ? TRACE.exec(arg)?.[1] : undefined
24
+ if (name) {
25
+ component ??= name
26
+ break
27
+ }
28
+ }
29
+ }
30
+ warn.apply(console, args)
31
+ }
32
+ return {
33
+ done() {
34
+ console.warn = warn
35
+ if (signalled) snapshot.compare(component, undefined, true, node)
36
+ },
37
+ }
38
+ }
@@ -0,0 +1,7 @@
1
+ /** What `hydration-dev.ts` hands the client runtime in `hamur dev`; a production client never sets it. */
2
+ export interface HydrationWatch {
3
+ /** `app.mount` returned: the hydration's warnings are in. */
4
+ done(): void
5
+ }
6
+
7
+ export const devHydration: { watch?: (root: Element) => HydrationWatch } = {}