void-plugin-hono-jsx 0.1.0-alpha.1 → 0.1.0-alpha.3

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 (61) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +42 -12
  3. package/dist/browser/client.d.ts +1 -0
  4. package/dist/browser/client.d.ts.map +1 -0
  5. package/dist/browser/client.js +1 -0
  6. package/dist/browser/client.js.map +1 -0
  7. package/dist/browser/deferred.d.ts +1 -0
  8. package/dist/browser/deferred.d.ts.map +1 -0
  9. package/dist/browser/deferred.js +1 -0
  10. package/dist/browser/deferred.js.map +1 -0
  11. package/dist/browser/document-head.d.ts +1 -0
  12. package/dist/browser/document-head.d.ts.map +1 -0
  13. package/dist/browser/document-head.js +1 -0
  14. package/dist/browser/document-head.js.map +1 -0
  15. package/dist/browser/form.d.ts +1 -0
  16. package/dist/browser/form.d.ts.map +1 -0
  17. package/dist/browser/form.js +1 -0
  18. package/dist/browser/form.js.map +1 -0
  19. package/dist/browser/pages.d.ts +1 -0
  20. package/dist/browser/pages.d.ts.map +1 -0
  21. package/dist/browser/pages.js +1 -0
  22. package/dist/browser/pages.js.map +1 -0
  23. package/dist/plugins/compatibility.d.ts +13 -1
  24. package/dist/plugins/compatibility.d.ts.map +1 -0
  25. package/dist/plugins/compatibility.js +66 -22
  26. package/dist/plugins/compatibility.js.map +1 -0
  27. package/dist/plugins/hono-islands.d.ts +1 -0
  28. package/dist/plugins/hono-islands.d.ts.map +1 -0
  29. package/dist/plugins/hono-islands.js +1 -0
  30. package/dist/plugins/hono-islands.js.map +1 -0
  31. package/dist/plugins/hono-jsx.d.ts +1 -0
  32. package/dist/plugins/hono-jsx.d.ts.map +1 -0
  33. package/dist/plugins/hono-jsx.js +1 -0
  34. package/dist/plugins/hono-jsx.js.map +1 -0
  35. package/dist/plugins/hono-pages.d.ts +2 -1
  36. package/dist/plugins/hono-pages.d.ts.map +1 -0
  37. package/dist/plugins/hono-pages.js +5 -3
  38. package/dist/plugins/hono-pages.js.map +1 -0
  39. package/dist/plugins/runtime-paths.d.ts +1 -0
  40. package/dist/plugins/runtime-paths.d.ts.map +1 -0
  41. package/dist/plugins/runtime-paths.js +13 -6
  42. package/dist/plugins/runtime-paths.js.map +1 -0
  43. package/dist/server/form.d.ts +1 -0
  44. package/dist/server/form.d.ts.map +1 -0
  45. package/dist/server/form.js +1 -0
  46. package/dist/server/form.js.map +1 -0
  47. package/dist/server/pages.d.ts +1 -0
  48. package/dist/server/pages.d.ts.map +1 -0
  49. package/dist/server/pages.js +1 -0
  50. package/dist/server/pages.js.map +1 -0
  51. package/package.json +6 -5
  52. package/src/plugins/compatibility.ts +64 -0
  53. package/src/plugins/hono-islands.ts +105 -0
  54. package/src/plugins/hono-jsx.ts +20 -0
  55. package/src/plugins/hono-pages.ts +143 -0
  56. package/src/plugins/runtime-paths.ts +14 -0
  57. package/src/runtime/client.tsx +83 -0
  58. package/src/runtime/deferred.ts +34 -0
  59. package/src/runtime/document-head.ts +44 -0
  60. package/src/runtime/form.ts +71 -0
  61. package/src/runtime/pages.tsx +45 -0
@@ -1,7 +1,14 @@
1
1
  import { fileURLToPath } from 'node:url';
2
- export const pagesRuntimePath = fileURLToPath(new URL('../server/pages.js', import.meta.url));
3
- export const clientRuntimePath = fileURLToPath(new URL('../browser/client.js', import.meta.url));
4
- export const publicRuntimeModules = {
5
- "void-plugin-hono-jsx/pages": { server: fileURLToPath(new URL('../server/pages.js', import.meta.url)), client: fileURLToPath(new URL('../browser/pages.js', import.meta.url)) },
6
- "void-plugin-hono-jsx/form": { server: fileURLToPath(new URL('../server/form.js', import.meta.url)), client: fileURLToPath(new URL('../browser/form.js', import.meta.url)) },
7
- };
2
+ // Source fixtures use TSX; npm consumers use the precompiled environment entries.
3
+ // Keep this adaptation in TypeScript so both emitted maps describe the actual code.
4
+ const compiled = new URL(import.meta.url).pathname.endsWith('.js');
5
+ export const pagesRuntimePath = fileURLToPath(new URL(compiled ? '../server/pages.js' : '../runtime/pages.tsx', import.meta.url));
6
+ export const clientRuntimePath = fileURLToPath(new URL(compiled ? '../browser/client.js' : '../runtime/client.tsx', import.meta.url));
7
+ export const publicRuntimeModules = compiled ? {
8
+ 'void-plugin-hono-jsx/pages': { server: pagesRuntimePath, client: fileURLToPath(new URL('../browser/pages.js', import.meta.url)) },
9
+ 'void-plugin-hono-jsx/form': {
10
+ server: fileURLToPath(new URL('../server/form.js', import.meta.url)),
11
+ client: fileURLToPath(new URL('../browser/form.js', import.meta.url)),
12
+ },
13
+ } : {};
14
+ //# sourceMappingURL=runtime-paths.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-paths.js","sourceRoot":"","sources":["../../src/plugins/runtime-paths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,kFAAkF;AAClF,oFAAoF;AACpF,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AACnE,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,sBAAsB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAClI,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,uBAAuB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACtI,MAAM,CAAC,MAAM,oBAAoB,GAAuD,QAAQ,CAAC,CAAC,CAAC;IACjG,4BAA4B,EAAE,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,aAAa,CAAC,IAAI,GAAG,CAAC,qBAAqB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE;IAClI,2BAA2B,EAAE;QAC3B,MAAM,EAAE,aAAa,CAAC,IAAI,GAAG,CAAC,mBAAmB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACpE,MAAM,EAAE,aAAa,CAAC,IAAI,GAAG,CAAC,oBAAoB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;KACtE;CACF,CAAC,CAAC,CAAC,EAAE,CAAC","sourcesContent":["import { fileURLToPath } from 'node:url';\n\n// Source fixtures use TSX; npm consumers use the precompiled environment entries.\n// Keep this adaptation in TypeScript so both emitted maps describe the actual code.\nconst compiled = new URL(import.meta.url).pathname.endsWith('.js');\nexport const pagesRuntimePath = fileURLToPath(new URL(compiled ? '../server/pages.js' : '../runtime/pages.tsx', import.meta.url));\nexport const clientRuntimePath = fileURLToPath(new URL(compiled ? '../browser/client.js' : '../runtime/client.tsx', import.meta.url));\nexport const publicRuntimeModules: Record<string, { server: string; client: string }> = compiled ? {\n 'void-plugin-hono-jsx/pages': { server: pagesRuntimePath, client: fileURLToPath(new URL('../browser/pages.js', import.meta.url)) },\n 'void-plugin-hono-jsx/form': {\n server: fileURLToPath(new URL('../server/form.js', import.meta.url)),\n client: fileURLToPath(new URL('../browser/form.js', import.meta.url)),\n },\n} : {};\n"]}
@@ -14,3 +14,4 @@ export declare function useForm<T extends Record<string, unknown>>(initialData:
14
14
  patch: (url: string) => Promise<void>;
15
15
  delete: (url: string) => Promise<void>;
16
16
  };
17
+ //# sourceMappingURL=form.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../../src/runtime/form.ts"],"names":[],"mappings":"AACA,OAAO,EAA+C,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AASjG,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,CAAC;;;;;;;qBAmBzC,UAAU,OAAO,MAAM;;;gBAoCvC,MAAM;eACP,MAAM;iBACJ,MAAM;kBACL,MAAM;EAEvB"}
@@ -78,3 +78,4 @@ export function useForm(initialData) {
78
78
  delete: (url) => submit('delete', url),
79
79
  };
80
80
  }
81
+ //# sourceMappingURL=form.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form.js","mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,UAAU;AACvD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAoC,MAAM,mBAAmB;AAChG,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,4BAAa;AAEjE,SAAS,WAAW,CAAC,KAAsB;IACzC,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI;IACvB,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,IAAI,IAAI,CAAC,IAAI,OAAO,IAAI,CAAC,MAAM,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI;QAAE,OAAO,EAAE;IAC1I,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAA6B,EAAE,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,CAAC;AACnI;AAEA,MAAM,UAAU,OAAO,CAAoC,WAAc;IACvE,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,4FAA4F,CAAC;IAC7I,MAAM,MAAM,GAAG,SAAS,EAAE;IAC1B,MAAM,aAAa,GAAG,SAAS,EAAE;IACjC,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC;IAChD,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAC,aAAa,CAAC;IACnD,MAAM,CA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,OAAO,EAAE,GAAG,CAAC;QAC5C,MAAM,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC;KAC/C;AACH","names":[],"ignoreList":[],"sources":["../../src/runtime/form.ts"],"sourcesContent":["import { useContext, useRef, useState } from 'hono/jsx';\nimport { isAbortError, submitAction, VoidActionError, type FormMethod } from 'void/pages-client';\nimport { RouterContext, useErrors, useRouter } from './pages.tsx';\n\nfunction fieldErrors(error: VoidActionError): Record<string, string> {\n const body = error.body;\n if (typeof body !== 'object' || body === null || !('errors' in body) || typeof body.errors !== 'object' || body.errors === null) return {};\n return Object.fromEntries(Object.entries(body.errors).filter((entry): entry is [string, string] => typeof entry[1] === 'string'));\n}\n\nexport function useForm<T extends Record<string, unknown>>(initialData: T) {\n if (!useContext(RouterContext)) throw new Error('Hono Pages: useForm requires the full Pages renderer; island form helpers are unsupported.');\n const router = useRouter();\n const initialErrors = useErrors();\n const [data, updateData] = useState(initialData);\n const [errors, setErrors] = useState(initialErrors);\n const [pending, setPending] = useState(false);\n const [wasSuccessful, setSuccessful] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const active = useRef(false);\n const generation = useRef(0);\n\n const setData: typeof updateData = (next) => {\n updateData(next);\n setSuccessful(false);\n setErrors({});\n setError(null);\n };\n\n async function submit(method: FormMethod, url: string) {\n if (active.current) return;\n active.current = true;\n const id = ++generation.current;\n setPending(true);\n setSuccessful(false);\n setError(null);\n setErrors({});\n try {\n const result = await submitAction(router, url, { method: method.toUpperCase(), data, preserveScroll: true });\n if (id !== generation.current) return;\n if (result.ok) setSuccessful(true);\n else { setError(result.error); setErrors(fieldErrors(result.error)); }\n } catch (failure) {\n if (id === generation.current && !isAbortError(failure)) {\n setError(failure instanceof Error ? failure : new Error(String(failure)));\n }\n } finally {\n if (id === generation.current) { active.current = false; setPending(false); }\n }\n }\n\n function cancel() {\n if (!active.current) return;\n const id = ++generation.current;\n active.current = false;\n setPending(false);\n setSuccessful(false);\n void router.refresh().catch((failure: unknown) => {\n if (id === generation.current) setError(failure instanceof Error ? failure : new Error(String(failure)));\n });\n }\n\n return {\n data, setData, errors, pending, wasSuccessful, error, submit, cancel,\n reset() { setData(initialData); },\n post: (url: string) => submit('post', url),\n put: (url: string) => submit('put', url),\n patch: (url: string) => submit('patch', url),\n delete: (url: string) => submit('delete', url),\n };\n}\n"]}
@@ -15,3 +15,4 @@ type LinkProps = Omit<JSX.IntrinsicElements['a'], 'href' | 'onClick'> & {
15
15
  onClick?: (event: MouseEvent) => void;
16
16
  };
17
17
  export declare function Link({ href, reloadDocument, replace, onClick, ...attributes }: LinkProps): import("hono/jsx/jsx-dev-runtime").JSX.Element;
18
+ //# sourceMappingURL=pages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pages.d.ts","sourceRoot":"","sources":["../../src/runtime/pages.tsx"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtD,YAAY,EAAE,aAAa,IAAI,QAAQ,EAAE,MAAM,MAAM,CAAC;AAEtD,eAAO,MAAM,aAAa,+CAAyC,CAAC;AACpE,eAAO,MAAM,WAAW,+CAAyC,CAAC;AAQlE,wBAAgB,SAAS,4BAA+B;AACxD,wBAAgB,SAAS,2BAA+B;AACxD,wBAAgB,SAAS,2BAAqC;AAE9D,wBAAgB,SAAS,IAAI,UAAU,CAItC;AAED,KAAK,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;CACvC,CAAC;AAEF,wBAAgB,IAAI,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,UAAU,EAAE,EAAE,SAAS,kDAaxF"}
@@ -34,3 +34,4 @@ export function Link({ href, reloadDocument, replace, onClick, ...attributes })
34
34
  });
35
35
  } });
36
36
  }
37
+ //# sourceMappingURL=pages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pages.js","sourceRoot":"","sources":["../../src/runtime/pages.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAY,MAAM,UAAU,CAAC;AAK/D,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAoB,IAAI,CAAC,CAAC;AACpE,MAAM,CAAC,MAAM,WAAW,GAAG,aAAa,CAAoB,IAAI,CAAC,CAAC;AAElE,SAAS,OAAO;IACd,MAAM,IAAI,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;IACrC,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAC9E,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,SAAS,KAAK,OAAO,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;AACxD,MAAM,UAAU,SAAS,KAAK,OAAO,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;AACxD,MAAM,UAAU,SAAS,KAAK,OAAO,OAAO,EAAE,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC;AAE9D,MAAM,UAAU,SAAS;IACvB,MAAM,MAAM,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;IACzC,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAChF,OAAO,MAAM,CAAC;AAChB,CAAC;AASD,MAAM,UAAU,IAAI,CAAC,EAAE,IAAI,EAAE,cAAc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import { createContext, useContext, type JSX } from 'hono/jsx';\nimport type { VoidRouter } from 'void/pages-client';\nimport type { PageObject } from 'void/pages-protocol';\nexport type { DeferredState as Deferred } from 'void';\n\nexport const RouterContext = createContext<VoidRouter | null>(null);\nexport const PageContext = createContext<PageObject | null>(null);\n\nfunction usePage() {\n const page = useContext(PageContext);\n if (!page) throw new Error('Hono Pages: page data requires a page provider.');\n return page;\n}\n\nexport function useShared() { return usePage().shared; }\nexport function useParams() { return usePage().params; }\nexport function useErrors() { return usePage().errors ?? {}; }\n\nexport function useRouter(): VoidRouter {\n const router = useContext(RouterContext);\n if (!router) throw new Error('Hono Pages: useRouter requires a page provider.');\n return router;\n}\n\ntype LinkProps = Omit<JSX.IntrinsicElements['a'], 'href' | 'onClick'> & {\n href: string;\n reloadDocument?: boolean;\n replace?: boolean;\n onClick?: (event: MouseEvent) => void;\n};\n\nexport function Link({ href, reloadDocument, replace, onClick, ...attributes }: LinkProps) {\n const router = useRouter();\n return <a {...attributes} href={href} onClick={(event: MouseEvent) => {\n onClick?.(event);\n if (event.defaultPrevented || reloadDocument || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n if (attributes.download !== undefined || (attributes.target && attributes.target !== '_self') || attributes.rel?.split(/\\s+/).includes('external')) return;\n const url = new URL(href, window.location.href);\n if (url.origin !== window.location.origin || !['http:', 'https:'].includes(url.protocol)) return;\n event.preventDefault();\n void router.visit(url, { replace }).catch((error: unknown) => {\n window.dispatchEvent(new CustomEvent('hono-pages:navigation-error', { detail: error }));\n });\n }} />;\n}\n"]}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "void-plugin-hono-jsx",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "private": false,
5
- "description": "Experimental Hono JSX Pages adapter for Void 0.26.1",
5
+ "description": "Experimental Hono JSX Pages adapter for Void",
6
6
  "type": "module",
7
7
  "license": "MIT",
8
8
  "engines": {
@@ -10,6 +10,7 @@
10
10
  },
11
11
  "files": [
12
12
  "dist",
13
+ "src",
13
14
  "README.md",
14
15
  "THIRD_PARTY_NOTICES.md",
15
16
  "LICENSE",
@@ -30,9 +31,9 @@
30
31
  }
31
32
  },
32
33
  "peerDependencies": {
33
- "hono": "4.13.13",
34
- "void": "0.26.1",
35
- "vite": "8.3.3"
34
+ "hono": ">=4.13.13 <5.0.0",
35
+ "void": ">=0.26.1 <0.28.0",
36
+ "vite": ">=8.0.16 <9.0.0"
36
37
  },
37
38
  "repository": {
38
39
  "type": "git",
@@ -0,0 +1,64 @@
1
+ import { createRequire } from 'node:module';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { version as helperViteVersion } from 'vite';
5
+
6
+ export const supportedFrameworkRanges = {
7
+ void: '>=0.26.1 <0.28.0',
8
+ hono: '>=4.13.13 <5.0.0',
9
+ vite: '>=8.0.16 <9.0.0',
10
+ };
11
+ export const supportedViteRange = supportedFrameworkRanges.vite;
12
+
13
+ // Only stable releases are admitted. Void is pre-1.0, so its next minor
14
+ // requires explicit validation; Hono and Vite use their current major lines.
15
+ export function supportsFramework(name: keyof typeof supportedFrameworkRanges, version: unknown): boolean {
16
+ if (typeof version !== 'string') return false;
17
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version);
18
+ if (!match) return false;
19
+ const [major, minor, patch] = match.slice(1).map(Number);
20
+ if (![major, minor, patch].every(Number.isSafeInteger)) return false;
21
+ if (name === 'void') return major === 0 && ((minor === 26 && patch >= 1) || minor === 27);
22
+ if (name === 'hono') return major === 4 && (minor > 13 || (minor === 13 && patch >= 13));
23
+ return major === 8 && (minor > 0 || patch >= 16);
24
+ }
25
+ export const supportsVite = (version: unknown): boolean => supportsFramework('vite', version);
26
+
27
+ type PackageInfo = { version: string; path: string };
28
+ function packageInfo(name: string, require: NodeRequire): PackageInfo {
29
+ let directory = dirname(require.resolve(name));
30
+ while (true) {
31
+ const path = join(directory, 'package.json');
32
+ if (existsSync(path)) {
33
+ const metadata: unknown = JSON.parse(readFileSync(path, 'utf8'));
34
+ if (typeof metadata === 'object' && metadata !== null && 'name' in metadata && (metadata.name === name || (name === 'vite' && metadata.name === '@voidzero-dev/vite-plus-core'))) {
35
+ if (!('version' in metadata) || typeof metadata.version !== 'string') throw new Error(`Hono Pages: ${name} package version is missing (${path}).`);
36
+ return { version: metadata.version, path };
37
+ }
38
+ }
39
+ const parent = dirname(directory);
40
+ if (parent === directory) throw new Error(`Hono Pages: cannot locate ${name} package metadata from ${require.resolve(name)}.`);
41
+ directory = parent;
42
+ }
43
+ }
44
+ function describe(name: string, require: NodeRequire): string {
45
+ try { const info = packageInfo(name, require); return `${info.path} (metadata ${info.version})`; }
46
+ catch { return `not resolved from ${require.resolve.paths(name)?.join(', ') ?? 'this context'}`; }
47
+ }
48
+
49
+ export function assertSupportedFrameworks({ root, viteVersion }: { root: string; viteVersion: unknown }) {
50
+ const adapter = createRequire(import.meta.url);
51
+ const project = createRequire(join(root, 'package.json'));
52
+ const diagnostic = () => `Running Vite from hook context: ${typeof viteVersion === 'string' ? viteVersion : 'unavailable'}. Adapter helper Vite: ${helperViteVersion}; package.json: ${describe('vite', adapter)}. Project Vite package.json: ${describe('vite', project)}. Package paths are diagnostics, not the running Vite identity.`;
53
+ if (!supportsVite(viteVersion)) {
54
+ throw new Error(`Hono Pages: running Vite ${typeof viteVersion === 'string' ? viteVersion : 'unavailable'} is unsupported; expected ${supportedViteRange}. ${diagnostic()} Update the CLI/launcher that executes Vite. For bundled launchers such as vp, installing project vite alone does not update the running Vite. For standard Vite, install vite@^8.3.4 and run vite directly.`);
55
+ }
56
+ if (!supportsVite(helperViteVersion)) {
57
+ throw new Error(`Hono Pages: adapter helper Vite ${helperViteVersion} is unsupported; expected ${supportedViteRange}. ${diagnostic()} Inspect the adapter's resolved peer copy; install vite@^8.3.4 and refresh the adapter's peer resolution/lockfile if a stale copy remains.`);
58
+ }
59
+ for (const name of ['void', 'hono'] as const) {
60
+ const expected = supportedFrameworkRanges[name];
61
+ const info = packageInfo(name, adapter);
62
+ if (!supportsFramework(name, info.version)) throw new Error(`Hono Pages: ${name} ${info.version} is unsupported; install ${name}@"${expected}". Resolved package.json: ${info.path}. Project package.json: ${describe(name, project)}. ${diagnostic()}`);
63
+ }
64
+ }
@@ -0,0 +1,105 @@
1
+ import { readFileSync, realpathSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { normalizePath, parseSync, type Plugin } from 'vite';
4
+ import { scanPages, resolvePagesDir, type PageScanResult } from 'void/pages';
5
+ import { findIslandImports, editIslandSource, resolveSpecifier, computePagesNeedingClientJS, ISLANDS_RENDERER_ID, ISLANDS_CLIENT_ENTRY_ID } from 'void/pages-islands-plugin';
6
+
7
+ /** Narrow adapter for Void's load-on-page-load island convention. */
8
+ export function honoIslands(): Plugin {
9
+ const root = process.cwd();
10
+ const pagesDir = resolvePagesDir(root);
11
+ const islands = new Map<string, string>();
12
+ const pageFiles = new Set<string>();
13
+ let scan: PageScanResult | undefined;
14
+
15
+ function islandImports(code: string, filename: string) {
16
+ const found = findIslandImports(code, filename);
17
+ const attributed = parseSync(filename, code).program.body.filter((node) => node.type === 'ImportDeclaration' && node.attributes?.some(({ key }) => ('name' in key && key.name === 'island') || ('value' in key && key.value === 'island')));
18
+ if (attributed.length !== found.length) throw new Error(`Hono islands: use one default import with exactly one island: 'load' attribute in ${filename}.`);
19
+ return found;
20
+ }
21
+
22
+ function imports(code: string, filename: string) {
23
+ const found = islandImports(code, filename);
24
+ for (const entry of found) {
25
+ if (entry.hydrate !== 'load') throw new Error(`Hono islands: unsupported policy '${entry.hydrate}' in ${filename}; use island: 'load'.`);
26
+ if (!entry.specifier.startsWith('.')) throw new Error(`Hono islands: use a relative TSX/JSX component import in ${filename}.`);
27
+ const path = resolveSpecifier(entry.specifier, join(filename, '..'), ['.tsx', '.jsx']);
28
+ if (!path || !/\.[jt]sx$/.test(path)) throw new Error(`Hono islands: cannot resolve TSX/JSX component ${entry.specifier} in ${filename}.`);
29
+ const canonical = realpathSync(path);
30
+ const id = normalizePath(relative(root, canonical));
31
+ islands.set(id, canonical);
32
+ }
33
+ return found;
34
+ }
35
+
36
+ async function rescan() {
37
+ scan = await scanPages(root, { pagesDir });
38
+ islands.clear();
39
+ pageFiles.clear();
40
+ for (const page of scan.pages.filter((page) => page.island)) {
41
+ const filename = realpathSync(join(pagesDir, page.componentPath));
42
+ pageFiles.add(filename);
43
+ imports(readFileSync(filename, 'utf8'), filename);
44
+ }
45
+ }
46
+
47
+ return {
48
+ name: 'void-hono:islands',
49
+ enforce: 'pre',
50
+ buildStart: rescan,
51
+ async hotUpdate({ file }) {
52
+ if (normalizePath(file).startsWith(normalizePath(pagesDir) + '/')) await rescan();
53
+ },
54
+ config() {
55
+ return { build: { rollupOptions: { input: { 'islands-client': ISLANDS_CLIENT_ENTRY_ID } } } };
56
+ },
57
+ resolveId(id) {
58
+ if (id === ISLANDS_RENDERER_ID || id === ISLANDS_CLIENT_ENTRY_ID) return `\0${id}`;
59
+ },
60
+ transform(code, id) {
61
+ const filename = id.split('?')[0];
62
+ if (!/\.[jt]sx$/.test(filename) || filename.includes('/node_modules/')) return;
63
+ const canonical = realpathSync(filename);
64
+ if ((pageFiles.has(canonical) || [...islands.values()].includes(canonical)) && parseSync(filename, code).program.body.some((node) => node.type === 'ImportDeclaration' && node.source.value === 'void-plugin-hono-jsx/form')) {
65
+ throw new Error('Hono islands: form helpers are unsupported; use a full Pages component.');
66
+ }
67
+ const found = islandImports(code, filename);
68
+ if (!found.length) return;
69
+ if (!pageFiles.has(realpathSync(filename))) throw new Error('Hono islands: attributed imports are supported only directly in .island.tsx/.island.jsx pages.');
70
+ imports(code, filename);
71
+ return editIslandSource(code, found.map((entry) => {
72
+ const path = resolveSpecifier(entry.specifier, join(filename, '..'), ['.tsx', '.jsx']);
73
+ if (!path) throw new Error(`Hono islands: missing component ${entry.specifier}.`);
74
+ const islandId = normalizePath(relative(root, realpathSync(path)));
75
+ const component = `__honoIslandComponent${entry.start}`;
76
+ return { start: entry.start, end: entry.end, text: `import ${component} from ${entry.specifierRaw};
77
+ const ${entry.importName} = (props) => __honoIslandJsx('div', { 'data-island': ${JSON.stringify(islandId)}, 'data-hydrate': 'load', 'data-props': JSON.stringify(props), children: __honoIslandJsx(${component}, props) });` };
78
+ }), { prepend: "import { jsx as __honoIslandJsx } from 'hono/jsx/jsx-runtime';\n" });
79
+ },
80
+ load(id) {
81
+ if (id === `\0${ISLANDS_RENDERER_ID}`) {
82
+ if (!scan) throw new Error('Hono islands: page discovery has not completed.');
83
+ const interactive = [...computePagesNeedingClientJS(scan, pagesDir, null)];
84
+ return `import { renderPage } from 'virtual:void-pages-renderer';
85
+ const interactive = new Set(${JSON.stringify(interactive)});
86
+ export function renderIslandPage(page, assets) {
87
+ if (page.deferred?.length || page.deferredKeys) throw new Error('Hono islands: deferred props are unsupported.');
88
+ return renderPage(page, interactive.has(page.component) ? assets : { ...assets, preloads: '', body: '' });
89
+ }`;
90
+ }
91
+ if (id === `\0${ISLANDS_CLIENT_ENTRY_ID}`) {
92
+ if (!islands.size) return 'export {};';
93
+ const loaders = [...islands].map(([name, path]) => `${JSON.stringify(name)}: () => import(${JSON.stringify(path)})`).join(',\n');
94
+ return `import { initIslands } from 'void/pages-client';
95
+ import { jsx } from 'hono/jsx/dom/jsx-runtime';
96
+ import { render } from 'hono/jsx/dom';
97
+ initIslands({ ${loaders} }, (element, module, props) => {
98
+ if (typeof module.default !== 'function') throw new Error('Hono islands: a component must export a default function.');
99
+ render(jsx(module.default, props), element);
100
+ element.setAttribute('data-hono-island', 'mounted');
101
+ });`;
102
+ }
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,20 @@
1
+ import { transformWithOxc, type Plugin } from 'vite';
2
+
3
+ /** JSX factories differ by Vite environment; hooks can be shared via hono/jsx. */
4
+ export function honoJsx(): Plugin {
5
+ return {
6
+ name: 'poc:hono-jsx',
7
+ enforce: 'pre',
8
+ async transform(code, id) {
9
+ const filename = id.split('?')[0];
10
+ if (!/\.[jt]sx$/.test(filename) || filename.includes('/node_modules/')) return;
11
+ return transformWithOxc(code, filename, {
12
+ jsx: {
13
+ runtime: 'automatic',
14
+ importSource: this.environment.config.consumer === 'client' ? 'hono/jsx/dom' : 'hono/jsx',
15
+ development: this.environment.mode === 'dev',
16
+ },
17
+ });
18
+ },
19
+ };
20
+ }
@@ -0,0 +1,143 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { normalizePath } from 'vite';
4
+ import { pagesRuntimePath, clientRuntimePath, publicRuntimeModules } from './runtime-paths.ts';
5
+ import { generateComponentManifest, resolvePagesDir, resolveStaticPageDataBuildOptions, scanPages, type PageScanResult } from 'void/pages';
6
+ import type { Plugin } from 'vite';
7
+ import { honoJsx } from './hono-jsx.ts';
8
+ import { honoIslands } from './hono-islands.ts';
9
+ import { assertSupportedFrameworks } from './compatibility.ts';
10
+
11
+ const rendererId = 'virtual:void-pages-renderer';
12
+ const clientId = 'virtual:void-pages-client';
13
+
14
+ /** Experimental Pages contract verified against Void 0.26.1 and 0.27.0. */
15
+ export function voidHonoPages(): Plugin[] {
16
+ const root = process.cwd();
17
+ const pagesDir = resolvePagesDir(root);
18
+ const staticData = resolveStaticPageDataBuildOptions(root);
19
+ let scan: PageScanResult | undefined;
20
+
21
+ async function rescan() {
22
+ scan = await scanPages(root, { pagesDir });
23
+ for (const layout of [...scan.layouts, ...scan.namedLayouts]) {
24
+ if (layout.island || !/\.[jt]sx$/.test(layout.filePath)) throw new Error('Hono Pages: only standard TSX/JSX layouts are supported.');
25
+ }
26
+ for (const page of scan.pages) {
27
+ if (!/\.[jt]sx$/.test(page.componentPath)) {
28
+ throw new Error(`Hono Pages: only standard TSX/JSX pages are supported: ${page.componentPath}.`);
29
+ }
30
+ if (staticData.enabled && page.methods.some((method) => method === 'action' || method === 'actions')) {
31
+ throw new Error(`Hono Pages: actions require a server and cannot be used with static output: ${page.componentPath}.`);
32
+ }
33
+ }
34
+ return scan;
35
+ }
36
+
37
+ return [honoIslands(), honoJsx(), {
38
+ name: 'void-hono:pages',
39
+ enforce: 'pre',
40
+ config(config) {
41
+ assertSupportedFrameworks({ root: resolve(config.root ?? root), viteVersion: this?.meta?.viteVersion });
42
+ return {
43
+ resolve: { dedupe: ['hono'] },
44
+ build: { manifest: true, rollupOptions: { input: { 'pages-client': clientId } } },
45
+ };
46
+ },
47
+ configEnvironment() {
48
+ const modules = Object.keys(publicRuntimeModules);
49
+ const packages = [...new Set(modules.map((id) => id.slice(0, id.lastIndexOf('/'))))];
50
+ return { optimizeDeps: { exclude: ['hono', ...modules] }, resolve: { noExternal: ['hono', ...packages] } };
51
+ },
52
+ async buildStart() {
53
+ await rescan();
54
+ },
55
+ configureServer(server) {
56
+ const clear = (file: string) => {
57
+ if (normalizePath(file).startsWith(normalizePath(pagesDir) + '/')) scan = undefined;
58
+ };
59
+ server.watcher.on('add', clear);
60
+ server.watcher.on('unlink', clear);
61
+ server.httpServer?.once('close', () => { server.watcher.off('add', clear); server.watcher.off('unlink', clear); });
62
+ },
63
+ async hotUpdate({ file, type, modules, timestamp }) {
64
+ if (!normalizePath(file).startsWith(normalizePath(pagesDir) + '/')) return;
65
+ await rescan();
66
+ if (type !== 'update') return [];
67
+ const invalidated = new Set<(typeof modules)[number]>();
68
+ for (const module of modules) this.environment.moduleGraph.invalidateModule(module, invalidated, timestamp, true);
69
+ for (const id of [rendererId, clientId]) {
70
+ const module = this.environment.moduleGraph.getModuleById(`\0${id}`);
71
+ if (module) this.environment.moduleGraph.invalidateModule(module, invalidated, timestamp, true);
72
+ }
73
+ this.environment.hot.send({ type: 'full-reload' });
74
+ return [];
75
+ },
76
+ resolveId(id) {
77
+ if (id === rendererId || id === clientId) return `\0${id}`;
78
+ if (id === pagesRuntimePath || id === clientRuntimePath) return { id: realpathSync(id), external: false };
79
+ const runtime = publicRuntimeModules[id];
80
+ if (runtime) return { id: realpathSync(this.environment.config.consumer === 'client' ? runtime.client : runtime.server), external: false };
81
+ },
82
+ async load(id) {
83
+ if (id !== `\0${rendererId}` && id !== `\0${clientId}`) return;
84
+ const currentScan = scan ?? await rescan();
85
+ const serverSnapshot = id === `\0${rendererId}` && this.environment.mode === 'dev';
86
+ const manifestScan = id === `\0${clientId}`
87
+ ? { ...currentScan, pages: currentScan.pages.filter((page) => !page.island) }
88
+ : serverSnapshot ? { ...currentScan, pages: currentScan.pages.filter((page) => page.renderMode !== 'client') } : currentScan;
89
+ let manifest = generateComponentManifest(manifestScan, pagesDir);
90
+ if (serverSnapshot) {
91
+ // A request can retain the old renderer while the worker module runner
92
+ // reloads. Capture components with its providers instead of importing
93
+ // a new generation into an in-flight render. Browser-only pages remain
94
+ // absent from this server graph; production keeps lazy imports.
95
+ const imports: string[] = [];
96
+ manifest = manifest.replace(/\(\) => import\(("(?:[^"\\]|\\.)*")\)/g, (_, path: string) => {
97
+ const name = `__honoPageSnapshot${imports.length}`;
98
+ imports.push(`import * as ${name} from ${path};`);
99
+ return `() => ${name}`;
100
+ });
101
+ manifest = imports.join('\n') + '\n' + manifest;
102
+ }
103
+ if (id === `\0${clientId}` && !currentScan.pages.some((page) => !page.island)) return 'export {};';
104
+ if (id === `\0${rendererId}`) {
105
+ return `
106
+ import { jsx } from 'hono/jsx';
107
+ import { createSsrRouter } from 'void/pages-client';
108
+ import { PageContext, RouterContext } from ${JSON.stringify(pagesRuntimePath)};
109
+ import { serializePageData } from 'void/pages-server';
110
+ import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from 'void/pages-head';
111
+ ${manifest}
112
+ export async function renderPage(pageObj, assetTags) {
113
+ if (${JSON.stringify(staticData.enabled)} && pageObj.deferredKeys) throw new Error('Hono Pages: deferred props cannot be statically prerendered; remove defer().');
114
+ const load = components[pageObj.component];
115
+ if (!load) throw new Error('Hono Pages: unknown page component ' + pageObj.component);
116
+ const { default: Page } = await load();
117
+ if (typeof Page !== 'function') throw new Error('Hono Pages: a page must export a component function.');
118
+ let content = jsx(Page, pageObj.props);
119
+ const ids = layoutTree[pageObj.component] ?? [];
120
+ const layouts = await Promise.all(ids.map(async (id) => (await components[id]()).default));
121
+ for (const Layout of layouts.reverse()) {
122
+ if (typeof Layout !== 'function') throw new Error('Hono Pages: a layout must export a component function.');
123
+ content = jsx(Layout, { children: content });
124
+ }
125
+ const markup = await jsx(RouterContext.Provider, { value: createSsrRouter(pageObj.url, pageObj.params), children: jsx(PageContext.Provider, { value: pageObj, children: content }) }).toString();
126
+ const head = pageObj.head;
127
+ const body = pageObj.deferredKeys ? assetTags.body.replaceAll('<script type="module"', '<script async type="module"') : assetTags.body;
128
+ return '<!doctype html><html' + (head ? renderHtmlAttrs(head) : '') + '><head>'
129
+ + (head ? renderHeadToString(head) : '') + assetTags.css + assetTags.preloads
130
+ + '</head><body' + (head ? renderBodyAttrs(head) : '') + '>'
131
+ + '<script id="__VOID_PAGE_DATA__" type="application/json">' + serializePageData(pageObj) + '</script>'
132
+ + '<div id="app">' + markup + '</div>' + body + '</body></html>';
133
+ }
134
+ `;
135
+ }
136
+ return `
137
+ import { startHonoPages } from ${JSON.stringify(clientRuntimePath)};
138
+ ${manifest}
139
+ await startHonoPages({ components, layoutTree, routeMeta, matchRoute, staticPageData: ${JSON.stringify(staticData.enabled)}, staticPageDataFastPath: ${JSON.stringify(staticData.fastPath)} });
140
+ `;
141
+ },
142
+ }];
143
+ }
@@ -0,0 +1,14 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ // Source fixtures use TSX; npm consumers use the precompiled environment entries.
4
+ // Keep this adaptation in TypeScript so both emitted maps describe the actual code.
5
+ const compiled = new URL(import.meta.url).pathname.endsWith('.js');
6
+ export const pagesRuntimePath = fileURLToPath(new URL(compiled ? '../server/pages.js' : '../runtime/pages.tsx', import.meta.url));
7
+ export const clientRuntimePath = fileURLToPath(new URL(compiled ? '../browser/client.js' : '../runtime/client.tsx', import.meta.url));
8
+ export const publicRuntimeModules: Record<string, { server: string; client: string }> = compiled ? {
9
+ 'void-plugin-hono-jsx/pages': { server: pagesRuntimePath, client: fileURLToPath(new URL('../browser/pages.js', import.meta.url)) },
10
+ 'void-plugin-hono-jsx/form': {
11
+ server: fileURLToPath(new URL('../server/form.js', import.meta.url)),
12
+ client: fileURLToPath(new URL('../browser/form.js', import.meta.url)),
13
+ },
14
+ } : {};
@@ -0,0 +1,83 @@
1
+ import { render } from 'hono/jsx/dom';
2
+ import { jsx } from 'hono/jsx/dom/jsx-runtime';
3
+ import { useLayoutEffect, useState } from 'hono/jsx';
4
+ import { createVoidRouter, type VoidRouterConfig } from 'void/pages-client';
5
+ import { parseCacheFor } from 'void/pages-prefetch';
6
+ import { PageContext, RouterContext } from './pages.tsx';
7
+ import { createDocumentHead } from './document-head.ts';
8
+ import { createDeferred, resolveDeferred, rejectDeferred, isLoading, bufferInitialDeferred } from './deferred.ts';
9
+
10
+ type Manifest = Pick<VoidRouterConfig, 'components' | 'layoutTree' | 'routeMeta' | 'matchRoute' | 'staticPageData' | 'staticPageDataFastPath'>;
11
+
12
+ function pageComponent(component: unknown) {
13
+ if (typeof component !== 'function') throw new Error('Hono Pages: a page must export a component function.');
14
+ return component;
15
+ }
16
+
17
+ export async function startHonoPages(manifest: Manifest) {
18
+ const root = document.getElementById('app');
19
+ if (!root) throw new Error('Hono Pages: app root is missing.');
20
+ type Frame = { page: Awaited<ReturnType<typeof createVoidRouter>>['initialPageData']; component: unknown; layouts: unknown[]; revision: number };
21
+ let update: ((frame: Frame) => void) | undefined;
22
+ let revision = 0;
23
+ let applyDocumentHead: ReturnType<typeof createDocumentHead> | undefined;
24
+ let renderedProps: Record<string, unknown> | undefined;
25
+ let updateDeferred: ((props: Record<string, unknown>) => void) | undefined;
26
+ const initialization = createVoidRouter({
27
+ ...manifest,
28
+ adapter: {
29
+ createDeferred, resolveDeferred, rejectDeferred, isLoading,
30
+ onDeferredUpdate(props) {
31
+ if (props === renderedProps) updateDeferred?.({ ...props });
32
+ },
33
+ async applyUpdate(page, component, layouts, options) {
34
+ layouts.forEach(pageComponent);
35
+ pageComponent(component);
36
+ if (!update) throw new Error('Hono Pages: page rendering has not started.');
37
+ if (!options.preserveState) revision++;
38
+ renderedProps = page.props;
39
+ update({ page: { ...page, props: { ...page.props } }, component, layouts, revision });
40
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
41
+ applyDocumentHead?.(page.head);
42
+ },
43
+ },
44
+ viewTransitions: false,
45
+ prefetchHoverDelay: 75,
46
+ prefetchDefaultCacheFor: parseCacheFor('30s'),
47
+ cacheVisitedPageData: false,
48
+ onNavigationChange(state) { root.dataset.navigation = state.state; },
49
+ });
50
+ const releaseBuffer = bufferInitialDeferred();
51
+ const navigation = await initialization.finally(releaseBuffer);
52
+ renderedProps = navigation.initialPageData.props;
53
+ applyDocumentHead = createDocumentHead(navigation.initialPageData.head);
54
+
55
+ function App() {
56
+ const [frame, setFrame] = useState<Frame>({ page: { ...navigation.initialPageData, props: { ...navigation.initialPageData.props } }, component: navigation.initialComponent, layouts: navigation.initialLayouts, revision });
57
+ const [failed, setFailed] = useState(false);
58
+ useLayoutEffect(() => {
59
+ updateDeferred = (props) => setFrame((frame) => ({ ...frame, page: { ...frame.page, props } }));
60
+ update = (next) => { setFailed(false); setFrame(next); };
61
+ const onError = () => setFailed(true);
62
+ window.addEventListener('hono-pages:navigation-error', onError);
63
+ return () => { update = undefined; updateDeferred = undefined; window.removeEventListener('hono-pages:navigation-error', onError); };
64
+ }, []);
65
+ let content = jsx(pageComponent(frame.component), frame.page.props, String(frame.revision));
66
+ const ids = manifest.layoutTree[frame.page.component] ?? [];
67
+ for (let index = frame.layouts.length - 1; index >= 0; index--) {
68
+ content = jsx(pageComponent(frame.layouts[index]), { children: content }, ids[index]);
69
+ }
70
+ return <RouterContext.Provider value={navigation.router}>
71
+ <PageContext.Provider value={frame.page}>
72
+ {failed && <p role="alert">The page could not be loaded. Please try again.</p>}
73
+ {content}
74
+ </PageContext.Provider>
75
+ </RouterContext.Provider>;
76
+ }
77
+
78
+ render(<App />, root);
79
+ navigation.start();
80
+ navigation.commitInitialRender();
81
+ root.dataset.navigation = 'idle';
82
+ root.dataset.honoPages = 'mounted';
83
+ }
@@ -0,0 +1,34 @@
1
+ import type { DeferredState } from 'void';
2
+
3
+ export function createDeferred(): DeferredState<never> {
4
+ return { loading: true, value: null, error: null };
5
+ }
6
+ export function resolveDeferred(_ref: unknown, value: unknown): DeferredState<unknown> {
7
+ return { loading: false, value, error: null };
8
+ }
9
+ export function rejectDeferred(_ref: unknown, message: string): DeferredState<never> {
10
+ return { loading: false, value: null, error: new Error(message) };
11
+ }
12
+ export function isLoading(ref: unknown): boolean {
13
+ return typeof ref === 'object' && ref !== null && 'loading' in ref && ref.loading === true;
14
+ }
15
+
16
+ // Void installs its HTML callbacks before awaiting component imports. Keep early
17
+ // messages in its existing queue until the initial deferred registry is ready.
18
+ declare global {
19
+ interface Window {
20
+ __resolveDeferred?: (group: string, data: unknown) => void;
21
+ __rejectDeferred?: (group: string, error: string) => void;
22
+ __deferredQueue?: Array<[string, unknown] | [string, 0, string]>;
23
+ }
24
+ }
25
+ export function bufferInitialDeferred() {
26
+ const resolve = window.__resolveDeferred;
27
+ const reject = window.__rejectDeferred;
28
+ window.__resolveDeferred = (group, data) => (window.__deferredQueue ??= []).push([group, data]);
29
+ window.__rejectDeferred = (group, error) => (window.__deferredQueue ??= []).push([group, 0, error]);
30
+ return () => {
31
+ window.__resolveDeferred = resolve;
32
+ window.__rejectDeferred = reject;
33
+ };
34
+ }
@@ -0,0 +1,44 @@
1
+ import { renderHeadToString } from 'void/pages-head';
2
+ import type { HeadDescriptor } from 'void';
3
+
4
+ function scriptSignature(script: HTMLScriptElement) {
5
+ return JSON.stringify([Array.from(script.attributes, ({ name, value }) => [name, value]).sort(), script.textContent]);
6
+ }
7
+
8
+ function scriptElements(head: HeadDescriptor | undefined) {
9
+ const template = document.createElement('template');
10
+ template.innerHTML = renderHeadToString({ script: head?.script });
11
+ return Array.from(template.content.querySelectorAll('script'));
12
+ }
13
+
14
+ /** Complements Void's title/meta/link updates without executing navigation scripts. */
15
+ export function createDocumentHead(initial: HeadDescriptor | undefined) {
16
+ let htmlKeys = Object.keys(initial?.htmlAttrs ?? {});
17
+ let bodyKeys = Object.keys(initial?.bodyAttrs ?? {});
18
+ let scripts: HTMLScriptElement[] = [];
19
+ const existing = Array.from(document.head.querySelectorAll('script'));
20
+ for (const desired of scriptElements(initial)) {
21
+ const index = existing.findIndex((script) => scriptSignature(script) === scriptSignature(desired));
22
+ if (index >= 0) scripts.push(...existing.splice(index, 1));
23
+ }
24
+
25
+ function attributes(element: HTMLElement, previous: string[], next: Record<string, string> = {}) {
26
+ for (const key of previous) if (!(key in next)) element.removeAttribute(key);
27
+ for (const [key, value] of Object.entries(next)) element.setAttribute(key, value);
28
+ return Object.keys(next);
29
+ }
30
+
31
+ return (head: HeadDescriptor | undefined) => {
32
+ htmlKeys = attributes(document.documentElement, htmlKeys, head?.htmlAttrs);
33
+ bodyKeys = attributes(document.body, bodyKeys, head?.bodyAttrs);
34
+ const remaining = [...scripts];
35
+ scripts = scriptElements(head).map((desired) => {
36
+ const index = remaining.findIndex((script) => scriptSignature(script) === scriptSignature(desired));
37
+ if (index >= 0) return remaining.splice(index, 1)[0];
38
+ // Template-parsed scripts remain inert when inserted. Head changes are metadata, not script execution.
39
+ document.head.appendChild(desired);
40
+ return desired;
41
+ });
42
+ for (const script of remaining) script.remove();
43
+ };
44
+ }