@hamur/adapter-html 0.0.0-stage → 0.0.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 (54) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +31 -2
  3. package/dist/chunks/browser-index-2h1699xv.js +148 -0
  4. package/dist/chunks/browser-index-n6x04zrf.js +28 -0
  5. package/dist/chunks/browser-index-naq02zzj.js +4 -0
  6. package/dist/chunks/browser-index-qx74bd1y.js +302 -0
  7. package/dist/src/adapter.js +141 -0
  8. package/dist/src/error-page.js +335 -0
  9. package/dist/src/index.js +1241 -0
  10. package/dist/src/runtime/client.js +330 -0
  11. package/dist/src/runtime/island.js +40 -0
  12. package/dist/src/runtime/server.js +59 -0
  13. package/dist/types/src/adapter.d.ts +2 -0
  14. package/dist/types/src/async-data.d.ts +13 -0
  15. package/dist/types/src/context.d.ts +109 -0
  16. package/dist/types/src/error-page.d.ts +1 -0
  17. package/dist/types/src/index.d.ts +343 -0
  18. package/dist/types/src/island-html.d.ts +13 -0
  19. package/dist/types/src/island.d.ts +40 -0
  20. package/dist/types/src/lazy-hydration.d.ts +11 -0
  21. package/dist/types/src/markdown-page.d.ts +9 -0
  22. package/dist/types/src/markdown.d.ts +11 -0
  23. package/dist/types/src/plugin.d.ts +11 -0
  24. package/dist/types/src/runtime/client.d.ts +15 -0
  25. package/dist/types/src/runtime/hmr.d.ts +8 -0
  26. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  27. package/dist/types/src/runtime/hydration.d.ts +10 -0
  28. package/dist/types/src/runtime/island.d.ts +8 -0
  29. package/dist/types/src/runtime/server.d.ts +8 -0
  30. package/dist/types/src/runtime/svg-id.d.ts +2 -0
  31. package/dist/types/src/server-component.d.ts +4 -0
  32. package/dist/types/src/svg.d.ts +10 -0
  33. package/package.json +62 -4
  34. package/src/adapter.ts +25 -0
  35. package/src/async-data.ts +65 -0
  36. package/src/context.ts +445 -0
  37. package/src/env.d.ts +3 -0
  38. package/src/error-page.ts +1 -0
  39. package/src/index.ts +1620 -0
  40. package/src/island-html.ts +58 -0
  41. package/src/island.ts +126 -0
  42. package/src/lazy-hydration.ts +56 -0
  43. package/src/markdown-page.ts +17 -0
  44. package/src/markdown.ts +29 -0
  45. package/src/plugin.ts +70 -0
  46. package/src/runtime/client.ts +363 -0
  47. package/src/runtime/hmr.ts +38 -0
  48. package/src/runtime/hydration-dev.ts +12 -0
  49. package/src/runtime/hydration.ts +11 -0
  50. package/src/runtime/island.ts +52 -0
  51. package/src/runtime/server.ts +56 -0
  52. package/src/runtime/svg-id.ts +12 -0
  53. package/src/server-component.ts +30 -0
  54. package/src/svg.ts +54 -0
@@ -0,0 +1,58 @@
1
+ import { markWaiting } from "hamur/adapter"
2
+ import type { AppContext } from "hamur/app"
3
+
4
+ type Outcome = { value: unknown } | { error: unknown }
5
+
6
+ const outcomes = new WeakMap<Promise<unknown>, Outcome>()
7
+ let current: Promise<void>[] | undefined
8
+
9
+ /**
10
+ * The HTML of an island whose root has finished rendering (or the attributes of a server island), or `undefined` while it renders, recorded in `pending`
11
+ * so the render is done again once it has settled. A failed island throws where its `Island` renders, so the nearest
12
+ * route boundary shows the error. An island's HTML is always rendered in its place, never spliced into the markup.
13
+ */
14
+ export function settledIsland<T = string>(
15
+ promise: Promise<T>,
16
+ pending: Promise<void>[] | undefined = current,
17
+ ): T | undefined {
18
+ const outcome = outcomes.get(promise)
19
+ if (outcome) {
20
+ if ("error" in outcome) throw outcome.error
21
+ return outcome.value as T
22
+ }
23
+ pending?.push(
24
+ promise.then(
25
+ (value) => void outcomes.set(promise, { value }),
26
+ (error: unknown) => void outcomes.set(promise, { error }),
27
+ ),
28
+ )
29
+ return undefined
30
+ }
31
+
32
+ /** Runs a synchronous render whose `Island`s record the islands still rendering in `pending`. */
33
+ export function collectingIslands<T>(pending: Promise<void>[], render: () => T): T {
34
+ const outer = current
35
+ current = pending
36
+ try {
37
+ return render()
38
+ } finally {
39
+ current = outer
40
+ }
41
+ }
42
+
43
+ /** A pass of `renderInPasses` that met islands still rendering waits for them and is dropped, so the next pass renders them in place. */
44
+ export async function islandsSettled(app: AppContext, pending: Promise<void>[]): Promise<void> {
45
+ if (!pending.length) return
46
+ await Promise.all(pending)
47
+ markWaiting(app.asyncData)
48
+ }
49
+
50
+ /** An island's own root, rendered again until every island inside it has settled. */
51
+ export async function renderSettled<T>(render: (pending: Promise<void>[]) => T | Promise<T>): Promise<T> {
52
+ for (;;) {
53
+ const pending: Promise<void>[] = []
54
+ const result = await collectingIslands(pending, () => render(pending))
55
+ if (!pending.length) return result
56
+ await Promise.all(pending)
57
+ }
58
+ }
package/src/island.ts ADDED
@@ -0,0 +1,126 @@
1
+ import {
2
+ ISLAND_ELEMENT,
3
+ SERVER_ISLAND_ELEMENT,
4
+ renderIsland,
5
+ renderServerIsland,
6
+ serverIslandProps,
7
+ type IslandOn,
8
+ } from "hamur/adapter"
9
+ import type { ComponentRenderContext } from "hamur/adapter"
10
+ import type { AppContext } from "hamur/app"
11
+ import { currentState } from "./context.ts"
12
+ import { settledIsland } from "./island-html.ts"
13
+
14
+ /** An html island: the string it renders on the server and the function that makes it live in the browser, which may return its cleanup. */
15
+ export interface HtmlIsland<P extends object = Record<string, unknown>> {
16
+ render(props: P): string
17
+ hydrate(el: Element, props: P): void | (() => void)
18
+ /** Gives the live island new props when a swap keeps it; without it the island's HTML is written again from `render` and `hydrate` runs anew. */
19
+ update?(el: Element, props: P): void
20
+ }
21
+
22
+ export interface IslandOptions {
23
+ /** The island directive: when the island hydrates, `"only"` to mount it in the browser alone, or a directive a module adds; default `"load"`. */
24
+ on?: IslandOn
25
+ /** The island's id across swaps; a swap to a page with the same id keeps its element and state. */
26
+ persist?: string
27
+ /** With `persist`, a swap keeps the island's old props. */
28
+ persistProps?: boolean
29
+ /** What the server writes in place of the island under `on: "only"`. */
30
+ fallback?: string
31
+ }
32
+
33
+ interface Scope {
34
+ app: AppContext
35
+ prefix: string
36
+ next: number
37
+ }
38
+
39
+ export interface ServerIslandOptions {
40
+ /** What the server writes inside the element until the browser has the island's HTML. */
41
+ fallback?: string
42
+ }
43
+
44
+ const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }
45
+ const counters = new WeakMap<object, number>()
46
+ let scope: Scope | undefined
47
+
48
+ function pageId(ids: object): string {
49
+ const next = counters.get(ids) ?? 0
50
+ counters.set(ids, next + 1)
51
+ return String(next)
52
+ }
53
+
54
+ /** The default export of a file under `app/islands/`. */
55
+ export function defineIsland<P extends object>(island: HtmlIsland<P>): HtmlIsland<P> {
56
+ return island
57
+ }
58
+
59
+ /** Runs `render` for the island root `ctx.idPrefix`: the islands it writes count their ids from this root, so a render done again gives them the same ones. */
60
+ export function inIslandRoot<T>(ctx: Pick<ComponentRenderContext, "app" | "idPrefix"> | undefined, render: () => T): T {
61
+ const outer = scope
62
+ scope = ctx ? { app: ctx.app, prefix: ctx.idPrefix, next: 0 } : outer
63
+ try {
64
+ return render()
65
+ } finally {
66
+ scope = outer
67
+ }
68
+ }
69
+
70
+ function target(caller: string): { app: AppContext; id: string } {
71
+ const state = scope ? undefined : currentState()
72
+ const app = scope?.app ?? state?.app
73
+ if (!app) throw new Error(`${caller}() must be called inside a Hamur app`)
74
+ return { app, id: scope ? `${scope.prefix}.${scope.next++}` : pageId(state!.ids) }
75
+ }
76
+
77
+ const attributesOf = (attributes: Record<string, string>): string =>
78
+ Object.entries(attributes)
79
+ .map(([name, value]) =>
80
+ value === "" ? ` ${name}` : ` ${name}="${value.replace(/[&<>"]/g, (char) => ESCAPES[char]!)}"`,
81
+ )
82
+ .join("")
83
+
84
+ /** The default export of an `app/islands/**` file of a library in `experimental.islands.libraries`: a component of that library. */
85
+ export type LibraryComponent = object
86
+
87
+ /**
88
+ * On an island page, `component` rendered as a root of its own inside `<hamur-island>` and hydrated on its own in the browser.
89
+ * A component of a library in `experimental.islands.libraries` is rendered and hydrated by that library's adapter.
90
+ */
91
+ export function island<P extends object>(component: HtmlIsland<P>, props?: P, options?: IslandOptions): string
92
+ export function island(component: LibraryComponent, props?: Record<string, unknown>, options?: IslandOptions): string
93
+ export function island(component: object, props?: object, options: IslandOptions = {}): string {
94
+ const { app, id } = target("island")
95
+ const rendered = renderIsland(
96
+ app,
97
+ id,
98
+ component,
99
+ (props ?? {}) as Record<string, unknown>,
100
+ options.on,
101
+ undefined,
102
+ options,
103
+ )
104
+ const body = rendered.html ? (settledIsland(rendered.html) ?? "") : (options.fallback ?? "")
105
+ return `<${ISLAND_ELEMENT}${attributesOf(rendered.attributes)}>${body}</${ISLAND_ELEMENT}>`
106
+ }
107
+
108
+ /**
109
+ * The server island `name` with `props`, rendered on the server in its own request: the page holds `fallback`, the core swaps the
110
+ * answer in, and the page's own paints never see it. A browser render has no seal for the props, so the element carries them in the clear.
111
+ */
112
+ export function serverIsland(
113
+ name: string,
114
+ props: Record<string, unknown> = {},
115
+ options: ServerIslandOptions = {},
116
+ ): string {
117
+ const fallback = options.fallback ?? ""
118
+ if (typeof document !== "undefined") {
119
+ const attributes: Record<string, string> = { name }
120
+ if (Object.keys(props).length) attributes.props = serverIslandProps(name, props)
121
+ return `<${SERVER_ISLAND_ELEMENT}${attributesOf(attributes)}>${fallback}</${SERVER_ISLAND_ELEMENT}>`
122
+ }
123
+ const { app, id } = target("serverIsland")
124
+ const attributes = settledIsland(renderServerIsland(app, id, name, props).attributes) ?? {}
125
+ return `<${SERVER_ISLAND_ELEMENT}${attributesOf(attributes)}>${fallback}</${SERVER_ISLAND_ELEMENT}>`
126
+ }
@@ -0,0 +1,56 @@
1
+ import { hydrateOnAttribute, hydrateWrapper, markWaiting } from "hamur/adapter"
2
+ import type { HydrateOn, HydrateOnOptions } from "hamur/adapter"
3
+ import { currentState, repaintPage } from "./context.ts"
4
+
5
+ type Module<P> = { default: (props: P) => string }
6
+
7
+ const isServer = typeof document === "undefined"
8
+ const pending = new Set<Promise<unknown>>()
9
+
10
+ /** Pages render synchronously, so `render` awaits the lazy modules still loading before each pass. */
11
+ export function lazyModules(): Promise<unknown> | undefined {
12
+ return pending.size ? Promise.allSettled(pending) : undefined
13
+ }
14
+
15
+ /** An html page has no client components, so the component renders inline inside `<hamur-hydrate>` and `on` only names the attribute. */
16
+ export function defineLazyHydrationComponent<P extends object>(
17
+ on: HydrateOn,
18
+ loader: () => Promise<Module<P>>,
19
+ options?: Omit<HydrateOnOptions, "signal">,
20
+ ): (props: P & { onHydrated?: () => void }) => string {
21
+ hydrateOnAttribute(on)
22
+ let resolved: Module<P> | undefined
23
+ let failed: { error: unknown } | undefined
24
+ let loading: Promise<Module<P>> | undefined
25
+ const load = (): Promise<Module<P>> => {
26
+ if (loading) return loading
27
+ const current = (loading = loader().then(
28
+ (loaded) => (resolved = loaded),
29
+ (error: unknown) => {
30
+ if (isServer) failed = { error }
31
+ loading = undefined
32
+ throw error
33
+ },
34
+ ))
35
+ if (isServer) {
36
+ pending.add(current)
37
+ void current.then(
38
+ () => pending.delete(current),
39
+ () => pending.delete(current),
40
+ )
41
+ }
42
+ return current
43
+ }
44
+ if (isServer) void load().catch(() => {})
45
+ return ({ onHydrated: _, ...props }) => {
46
+ if (resolved) return hydrateWrapper(on, resolved.default(props as P))
47
+ if (failed) throw failed.error
48
+ const promise = load()
49
+ if (isServer) {
50
+ const app = currentState()?.app
51
+ if (app) markWaiting(app.asyncData)
52
+ void promise.catch(() => {})
53
+ } else void promise.then(repaintPage, () => {})
54
+ return hydrateWrapper(on, "")
55
+ }
56
+ }
@@ -0,0 +1,17 @@
1
+ import { markdownPageCode } from "hamur/adapter/build"
2
+ import type { MarkdownSource } from "hamur/adapter"
3
+
4
+ function module(source: MarkdownSource): { contents: string; extension: string } {
5
+ const { imports, value, props, head } = markdownPageCode(source)
6
+ const contents = `${imports}import { MarkdownRenderer, useHead } from "@hamur/adapter-html";
7
+
8
+ const value = ${value};
9
+
10
+ export default function MarkdownPage() {
11
+ ${head ? ` useHead(${head});\n` : ""} return MarkdownRenderer(${props});
12
+ }
13
+ `
14
+ return { contents, extension: ".js" }
15
+ }
16
+
17
+ export const markdownComponent = { module }
@@ -0,0 +1,29 @@
1
+ import { markdownProse, markdownView, writeMarkdownView } from "hamur/adapter"
2
+ import type { MarkdownDocument, MdNode } from "hamur/markdown"
3
+ import { Link } from "./index.ts"
4
+
5
+ export interface MarkdownRendererProps {
6
+ /** A Markdown AST node, a list of nodes, or a document, which renders its `ast`. */
7
+ value: MdNode | MdNode[] | MarkdownDocument
8
+ /** Components by Markdown component name (kebab case), each called with the node's props, `children` and a string argument per named slot. */
9
+ components?: Record<string, (props: Record<string, any>) => string>
10
+ /** Renders `html` nodes, writing what it returns as their inner HTML; without it they are left out. A Markdown page under config `markdown.html` passes the core's Trusted Types writer. */
11
+ raw?: (html: string) => string
12
+ }
13
+
14
+ /** Renders the Markdown AST as an HTML string, an internal link through `Link`, a component node through its function in `components`. */
15
+ export function MarkdownRenderer({ value, components: given = {}, raw }: MarkdownRendererProps): string {
16
+ const { value: nodes, components } = markdownProse(value, given)
17
+ const writers = Object.fromEntries(
18
+ Object.entries(components).map(([name, component]) => [
19
+ name,
20
+ (props: Record<string, unknown>, children: string, slots: Record<string, string>) =>
21
+ component({ ...props, ...slots, ...(children === "" ? {} : { children }) }),
22
+ ]),
23
+ )
24
+ return writeMarkdownView(markdownView(nodes, { html: raw !== undefined, components }), {
25
+ components: writers,
26
+ link: (to, attrs, children) => Link({ ...attrs, to, children } as Parameters<typeof Link>[0]),
27
+ raw: (html) => `<hamur-html style="display:contents">${raw!(html)}</hamur-html>`,
28
+ })
29
+ }
package/src/plugin.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { join, relative } from "node:path"
2
+ import type { AdapterBuildContext, AdapterTransform } from "hamur/adapter"
3
+ import { dropDevOnly } from "hamur/adapter/build"
4
+
5
+ const HMR_RUNTIME = join(import.meta.dir, "runtime/hmr.ts")
6
+ const CLIENT_RUNTIME = join(import.meta.dir, "runtime/client.ts")
7
+ const HYDRATION_DEV = join(import.meta.dir, "runtime/hydration-dev.ts")
8
+ const ROUTE_MODULE = /(^|\/)((pages|layouts)\/|app\.[jt]s$)/
9
+ const DEFAULT_FUNCTION = /^export default function\s+([A-Za-z_$][\w$]*)/m
10
+ const DEFAULT_ANY = /^export default /m
11
+
12
+ /**
13
+ * Wraps a route module's default export in a stable function and self-accepts, so a re-evaluated module
14
+ * swaps the implementation behind it and renders the tree again. A module without a default export is left alone.
15
+ */
16
+ export function hotTransform(source: string, id: string): string {
17
+ if (!DEFAULT_ANY.test(source)) return source
18
+ const named = source.match(DEFAULT_FUNCTION)?.[1]
19
+ const body = named
20
+ ? source.replace(DEFAULT_FUNCTION, `function ${named}`)
21
+ : source.replace(DEFAULT_ANY, "const __hamurImpl = ")
22
+ return [
23
+ body,
24
+ // The import follows the body so the module's lines keep their numbers in client error reports.
25
+ `import { hot as __hamurHot, rerender as __hamurRerender } from ${JSON.stringify(HMR_RUNTIME)};`,
26
+ `const __hamurDefault = __hamurHot(${JSON.stringify(id)}, ${named ?? "__hamurImpl"});`,
27
+ `export default __hamurDefault;`,
28
+ `if (import.meta.hot) import.meta.hot.accept(() => __hamurRerender());`,
29
+ ].join("\n")
30
+ }
31
+
32
+ export function htmlPlugin(ctx: AdapterBuildContext): AdapterTransform {
33
+ const build = relative(ctx.rootDir, ctx.buildDir)
34
+ return {
35
+ name: `hamur-html-${ctx.target}`,
36
+ filter: { id: /\.[jt]s$/ },
37
+ transform(code, { id: path }) {
38
+ const id = relative(ctx.rootDir, path)
39
+ if (
40
+ path.includes("/node_modules/") ||
41
+ !ROUTE_MODULE.test(id) ||
42
+ (build !== "" && !build.startsWith("..") && id.startsWith(`${build}/`))
43
+ )
44
+ return undefined
45
+ return hotTransform(code, id)
46
+ },
47
+ }
48
+ }
49
+
50
+ /** A production build turns the children of every `DevOnly(fn, …)` imported from `@hamur/adapter-html` into `undefined`. */
51
+ export function htmlProductionPlugin(ctx: AdapterBuildContext): AdapterTransform {
52
+ return {
53
+ name: `hamur-html-production-${ctx.target}`,
54
+ filter: { id: /\.[jt]s$/ },
55
+ transform(code, { id }) {
56
+ if (id.includes("/node_modules/")) return undefined
57
+ const contents = dropDevOnly(code, "@hamur/adapter-html", "call")
58
+ return contents === code ? undefined : contents
59
+ },
60
+ }
61
+ }
62
+
63
+ /** In `hamur dev` the client runtime imports `runtime/hydration-dev.ts` first, which feeds the hydration mismatch report; a build adds nothing. */
64
+ export function htmlHydrationPlugin(): AdapterTransform {
65
+ return {
66
+ name: "hamur-html-hydration",
67
+ filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
68
+ transform: (code) => `import ${JSON.stringify(HYDRATION_DEV)}; ${code}`,
69
+ }
70
+ }