prunelle 0.7.7 → 0.9.0

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 (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
@@ -0,0 +1,132 @@
1
+ // The fetch cache core `<Region>` swaps and `@prunellejs/spa` share: a link inside `[data-pru-prefetch]` is fetched on hover or focus, and the swap that follows takes the answer from here.
2
+
3
+ export interface PrefetchEntry {
4
+ html: string
5
+ url: string
6
+ ts: number
7
+ /** The `x-pru-region` the server answered with: the region's HTML alone, not a whole page. */
8
+ region: string | null
9
+ /** The percent-encoded `x-pru-title` of a region answer: the title the page has at this URL. */
10
+ title: string | null
11
+ /** The `x-pru-build` of a region answer: the build whose scripts and stylesheets its markup expects. */
12
+ build?: string | null | undefined
13
+ /** Response Content-Security-Policy header, used by `spa()` to detect blocked destination `<style>` tags. */
14
+ csp?: string | null | undefined
15
+ /** The `x-pru-view` the server answered a prefetch with: where to post the page when the visitor opens it, since a cache hit makes no request for the server to count. */
16
+ view?: string | null | undefined
17
+ }
18
+
19
+ export const HTML_ACCEPT = 'text/html'
20
+ const PREFETCH_TTL = 15_000
21
+ const PREFETCH_MAX = 8
22
+ // A prefetch past this many in flight is dropped: the click fetches the page as usual.
23
+ const PREFETCH_PARALLEL = 3
24
+ const HOVER_INTENT = 80
25
+ export const prefetchCache = new Map<string, PrefetchEntry>()
26
+ export const inflightPrefetch = new Map<string, Promise<PrefetchEntry | undefined>>()
27
+
28
+ // Document generation counter shared by core `<Region>` swaps and `spa()` so popstate separates same-doc region swaps from cross-doc page navigations.
29
+ function initialDocId(): number {
30
+ const st = typeof history === 'undefined' ? undefined : history.state as { __pruDoc?: unknown } | null
31
+ return typeof st?.__pruDoc === 'number' ? st.__pruDoc : 0
32
+ }
33
+
34
+ let currentDocId = initialDocId()
35
+ let maxDocId = currentDocId
36
+
37
+ export function getDocId(): number {
38
+ return currentDocId
39
+ }
40
+
41
+ export function setDocId(id: number): void {
42
+ currentDocId = id
43
+ if (id > maxDocId)
44
+ maxDocId = id
45
+ }
46
+
47
+ export function nextDocId(): number {
48
+ return ++maxDocId
49
+ }
50
+
51
+ export function isSameDocRegionState(state: unknown): boolean {
52
+ if (typeof state !== 'object' || state === null)
53
+ return false
54
+ const s = state as { __pruIdx?: unknown, __pruDoc?: unknown }
55
+ return typeof s.__pruIdx === 'number' && (s.__pruDoc === undefined || s.__pruDoc === currentDocId)
56
+ }
57
+
58
+ /** The cache key of a page, or of one region of it, given by its path from the outermost region (`results/sets`). */
59
+ export function fetchKeyOf(url: URL, region?: string): string {
60
+ const key = `${url.origin}${url.pathname}${url.search}`
61
+ return region === undefined ? key : `${region} ${key}`
62
+ }
63
+
64
+ export function getCachedHtml(href: string): PrefetchEntry | undefined {
65
+ const hit = prefetchCache.get(href)
66
+ if (hit === undefined)
67
+ return undefined
68
+ if (Date.now() - hit.ts > PREFETCH_TTL) {
69
+ prefetchCache.delete(href)
70
+ return undefined
71
+ }
72
+ return hit
73
+ }
74
+
75
+ function putCachedHtml(href: string, entry: PrefetchEntry): void {
76
+ prefetchCache.delete(href)
77
+ prefetchCache.set(href, entry)
78
+ if (prefetchCache.size > PREFETCH_MAX) {
79
+ const oldest = prefetchCache.keys().next()
80
+ if (!oldest.done)
81
+ prefetchCache.delete(oldest.value)
82
+ }
83
+ }
84
+
85
+ /** Tells the server a page was opened from the cache, when it asked to be told. */
86
+ export function countView(view: string | null | undefined, url: URL): void {
87
+ if (view)
88
+ navigator.sendBeacon(view, `${url.pathname}${url.search}`)
89
+ }
90
+
91
+ export async function prefetch(url: string, region?: string): Promise<void> {
92
+ const clean = new URL(url, location.href)
93
+ clean.hash = ''
94
+ const key = fetchKeyOf(clean, region)
95
+ if (getCachedHtml(key) !== undefined || inflightPrefetch.has(key) || inflightPrefetch.size >= PREFETCH_PARALLEL)
96
+ return
97
+ const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection
98
+ if (conn?.saveData)
99
+ return
100
+
101
+ const task = (async (): Promise<PrefetchEntry | undefined> => {
102
+ try {
103
+ const res = await fetch(clean.href, { headers: { ...(region === undefined ? { 'x-pru-spa': '1' } : { 'x-pru-region': region }), 'accept': HTML_ACCEPT, 'purpose': 'prefetch' } })
104
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
105
+ void res.body?.cancel()
106
+ return undefined
107
+ }
108
+ const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), build: res.headers.get('x-pru-build'), csp: res.headers.get('content-security-policy'), view: res.headers.get('x-pru-view') }
109
+ putCachedHtml(key, entry)
110
+ return entry
111
+ }
112
+ catch {
113
+ return undefined
114
+ }
115
+ finally {
116
+ inflightPrefetch.delete(key)
117
+ }
118
+ })()
119
+ inflightPrefetch.set(key, task)
120
+ await task
121
+ }
122
+
123
+ /** Runs `run` on keyboard focus at once, and on a pointer that rests 80 ms over a target, not on one sweeping across. */
124
+ export function listenIntent(run: (event: Event) => void): void {
125
+ let timer: ReturnType<typeof setTimeout> | undefined
126
+ document.addEventListener('pointerover', (event) => {
127
+ clearTimeout(timer)
128
+ timer = setTimeout(run, HOVER_INTENT, event)
129
+ }, { passive: true })
130
+ document.addEventListener('pointerout', () => clearTimeout(timer), { passive: true })
131
+ document.addEventListener('focusin', run, { passive: true })
132
+ }
@@ -0,0 +1,498 @@
1
+ // Core `<Region>` client runtime: a link or form with `data-pru-target` swaps one `<Region>` of the page, fetched alone.
2
+ // - a[data-pru-target] replaces the region; with data-pru-append the response is added to it and the clicked link goes (Load more)
3
+ // - form[data-pru-target] swaps on submit; with data-pru-live also while typing: one history entry per typing burst
4
+ // - [data-pru-sync="a b"] copies those query params of the current URL into links and fields outside the region
5
+ // - form[method=post][data-pru-target] posts through fetch, follows redirects, and swaps 4xx validation HTML in place
6
+ // - history push and back/forward re-fetch the region the entry changed; aria-busy while a fetch is slow
7
+ // - [data-persist="<key>"] inside the region survives the swap in the place of the new element of that key via `moveBefore`
8
+ // - loads the island runtime lazily if a swap delivers `<pru-island>` onto an initially island-less page
9
+
10
+ import type { PrefetchEntry } from './prefetch'
11
+ import type { EntryScroll } from './swap'
12
+ import { countView, fetchKeyOf, getCachedHtml, getDocId, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
13
+ import { announce, entryScroll, persistedIn, readScrolls, replaceKeeping, restoreScroll, saveScroll, swapInTransition, trackScroll, trustedHtml, writeScrolls } from './swap'
14
+
15
+ const BUSY_DELAY = 150
16
+ const LIVE_DEBOUNCE = 200
17
+ const BURST_PAUSE = 1000
18
+ const BUILD = 'script[data-pru-build]'
19
+ const RUNTIME = 'script[data-pru-runtime]'
20
+
21
+ interface RegionState { __pruIdx: number, __pruDoc?: number | undefined, __pruRegion?: string | undefined }
22
+
23
+ function safeGetAttribute(el: Element, name: string): string | null {
24
+ return Element.prototype.getAttribute.call(el, name)
25
+ }
26
+
27
+ interface Swap {
28
+ url: URL
29
+ region: string
30
+ append?: boolean
31
+ /** `burst`: pushed by the first change of a typing burst, replaced by the rest. */
32
+ history: 'push' | 'replace' | 'burst' | 'none'
33
+ /** Moves focus into the region (a link did it), not for a form the user is typing in. */
34
+ focus?: boolean
35
+ trigger?: Element
36
+ /** Skips the prefetch cache: the region is redrawn because the server's state changed. */
37
+ fresh?: boolean
38
+ /** A form posted to `url`: the swap shows the page its redirect lands on, or swaps 4xx validation HTML in place. */
39
+ post?: { form: HTMLFormElement, body: FormData }
40
+ /** Where the post's redirect ended, once it redirected. */
41
+ landed?: string
42
+ /** The scroll a back or forward entry had, put back after the swap. */
43
+ restore?: EntryScroll
44
+ /** Set when the answer came from another build than the page's: its markup expects stylesheets and scripts the tab does not have. */
45
+ stale?: boolean
46
+ }
47
+
48
+ function stateOf(state: unknown): RegionState | undefined {
49
+ return typeof state === 'object' && state !== null && typeof (state as RegionState).__pruIdx === 'number' ? state as RegionState : undefined
50
+ }
51
+
52
+ const controllers = new Map<string, AbortController>()
53
+ let idx = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruIdx ?? 0
54
+ let lastRegion = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruRegion
55
+ // The page and query the document shows: an entry that differs from it only in its hash needs no fetch.
56
+ let shown = typeof location === 'undefined' ? '' : location.pathname + location.search
57
+ // The pages Load more added to the document since its last swap, beside the one it shows: their #hash links scroll too.
58
+ const appended = new Set<string>()
59
+ let burstOpen = false
60
+ let burstTimer: ReturnType<typeof setTimeout> | undefined
61
+ let liveTimer: ReturnType<typeof setTimeout> | undefined
62
+ const loadedRuntimes = new Set<string>()
63
+
64
+ function findRegion(name: string): HTMLElement | null {
65
+ return document.querySelector<HTMLElement>(`[data-pru-region="${name.replace(/["\\]/g, '\\$&')}"]`)
66
+ }
67
+
68
+ // A region's path from the outermost one around it: `results/sets` for `sets` inside `results`. The server renders through the outer ones.
69
+ function pathOf(region: HTMLElement): string {
70
+ const names: string[] = []
71
+ for (let el: Element | null = region; el !== null; el = el.parentElement?.closest('[data-pru-region]') ?? null)
72
+ names.unshift(el.getAttribute('data-pru-region')!)
73
+ return names.join('/')
74
+ }
75
+
76
+ /** Loads the island runtime lazily when a region swap introduces `<pru-island>` onto an initially island-less page. */
77
+ function ensureIslandRuntime(root: ParentNode): void {
78
+ if (root.querySelector('pru-island') === null)
79
+ return
80
+ if (typeof customElements !== 'undefined' && customElements.get('pru-island') !== undefined)
81
+ return
82
+ const src = document.querySelector<HTMLScriptElement>(RUNTIME)?.getAttribute('data-pru-runtime')
83
+ if (!src)
84
+ return
85
+ const url = new URL(src, location.href)
86
+ if (url.origin !== location.origin || loadedRuntimes.has(url.href))
87
+ return
88
+ loadedRuntimes.add(url.href)
89
+ void import(url.href).catch((err) => {
90
+ loadedRuntimes.delete(url.href)
91
+ console.error('[prunelle] failed to load island runtime:', url.href, err)
92
+ })
93
+ }
94
+
95
+ async function load(swap: Swap, region: string, signal: AbortSignal): Promise<PrefetchEntry | undefined> {
96
+ const { url, post } = swap
97
+ const key = fetchKeyOf(url, region)
98
+ const ready = swap.fresh === true || post !== undefined ? undefined : getCachedHtml(key) ?? await inflightPrefetch.get(key)
99
+ if (ready !== undefined) {
100
+ prefetchCache.delete(key)
101
+ return ready
102
+ }
103
+ const res = await fetch(fetchKeyOf(url), { headers: { 'x-pru-region': region, 'accept': HTML_ACCEPT }, signal, ...(post === undefined ? {} : { method: 'POST', body: post.body }) })
104
+ if (post !== undefined && res.redirected)
105
+ swap.landed = res.url
106
+ const isHtml = (res.headers.get('content-type') ?? '').includes('text/html')
107
+ const isValidationHtml = post !== undefined && !res.ok && res.status >= 400 && res.status < 500 && isHtml
108
+ if ((!res.ok && !isValidationHtml) || !isHtml) {
109
+ void res.body?.cancel()
110
+ return undefined
111
+ }
112
+ if (isValidationHtml && !res.redirected)
113
+ swap.history = 'none'
114
+ return { html: await res.text(), url: res.url || fetchKeyOf(url), ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), build: res.headers.get('x-pru-build') }
115
+ }
116
+
117
+ // A page and an answer that both name their build and name different ones: the tab was opened before a deploy.
118
+ function fromOtherBuild(answer: string | null | undefined): boolean {
119
+ const page = document.querySelector(BUILD)?.getAttribute('data-pru-build')
120
+ return typeof answer === 'string' && typeof page === 'string' && answer !== page
121
+ }
122
+
123
+ // The region's inner HTML and the page title: the answer itself when the server sent the region alone, else the region cut out of a full page (a prerendered page, a proxy that dropped the header).
124
+ function contentOf(entry: PrefetchEntry, path: string): { content: DocumentFragment, title: string | undefined, build: string | null | undefined } | undefined {
125
+ const template = document.createElement('template')
126
+ const leaf = path.split('/').at(-1)!
127
+ if (entry.region === path || entry.region === leaf) {
128
+ template.innerHTML = trustedHtml(entry.html)
129
+ // The title is HTML text, percent-encoded in the header: a textarea unescapes it.
130
+ const unescape = document.createElement('textarea')
131
+ unescape.innerHTML = trustedHtml(entry.title === null ? '' : decodeURIComponent(entry.title))
132
+ return { content: template.content, title: entry.title === null ? undefined : unescape.value, build: entry.build }
133
+ }
134
+ const page = new DOMParser().parseFromString(trustedHtml(entry.html), 'text/html')
135
+ const found = page.querySelector(`[data-pru-region="${leaf.replace(/["\\]/g, '\\$&')}"]`)
136
+ if (found === null)
137
+ return undefined
138
+ template.innerHTML = trustedHtml(found.innerHTML)
139
+ return { content: template.content, title: page.title === '' ? undefined : page.title, build: page.querySelector(BUILD)?.getAttribute('data-pru-build') }
140
+ }
141
+
142
+ function record(url: URL, name: string, mode: 'push' | 'replace' | 'burst'): void {
143
+ clearTimeout(burstTimer)
144
+ // A replace inside the region the entry was made for keeps that region, so back and forward restore the whole of it.
145
+ const before = stateOf(history.state)?.__pruRegion
146
+ const around = mode === 'replace' && before !== undefined && before !== name && findRegion(before)?.contains(findRegion(name)) === true ? before : name
147
+ let push = mode === 'push' || (mode === 'burst' && !burstOpen)
148
+ if (mode === 'burst') {
149
+ burstOpen = true
150
+ burstTimer = setTimeout(() => { burstOpen = false }, BURST_PAUSE)
151
+ }
152
+ else {
153
+ burstOpen = false
154
+ }
155
+ const next = `${url.pathname}${url.search}${url.hash}`
156
+ if (next === `${location.pathname}${location.search}${location.hash}`)
157
+ push = false
158
+ const prev = (typeof history.state === 'object' && history.state !== null ? history.state : {}) as Record<string, unknown>
159
+ const docId = getDocId()
160
+ if (push) {
161
+ // The entry left behind is stamped first, so back and forward can tell it from a page of another document.
162
+ history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx }, '')
163
+ idx++
164
+ history.pushState({ __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
165
+ }
166
+ else {
167
+ history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
168
+ }
169
+ lastRegion = around
170
+ shown = url.pathname + url.search
171
+ }
172
+
173
+ function focusNode(el: Element | null | undefined): void {
174
+ if (el === null || el === undefined)
175
+ return
176
+ if (!el.hasAttribute('tabindex'))
177
+ el.setAttribute('tabindex', '-1')
178
+ ;(el as HTMLElement).focus({ preventScroll: true })
179
+ }
180
+
181
+ // Links and fields the app marked data-pru-sync follow the URL the swap just set.
182
+ function syncParams(): void {
183
+ const params = new URL(location.href).searchParams
184
+ for (const el of document.querySelectorAll<HTMLElement>('[data-pru-sync]')) {
185
+ if (el instanceof HTMLAnchorElement) {
186
+ const url = new URL(el.href, location.href)
187
+ if (url.origin !== location.origin)
188
+ continue
189
+ for (const name of (el.getAttribute('data-pru-sync') ?? '').split(/\s+/).filter(Boolean)) {
190
+ url.searchParams.delete(name)
191
+ for (const value of params.getAll(name))
192
+ url.searchParams.append(name, value)
193
+ }
194
+ el.setAttribute('href', `${url.pathname}${url.search}${url.hash}`)
195
+ }
196
+ else if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement) && el !== document.activeElement) {
197
+ el.value = params.get(el.name) ?? ''
198
+ }
199
+ }
200
+ }
201
+
202
+ // The links that point at the page the swap landed on say so; the ones that did and no longer do stop.
203
+ function syncCurrent(): void {
204
+ for (const link of document.querySelectorAll<HTMLAnchorElement>('a[href]')) {
205
+ if (link.origin === location.origin && link.hash === '' && link.pathname + link.search === location.pathname + location.search)
206
+ link.setAttribute('aria-current', 'page')
207
+ else if (link.getAttribute('aria-current') === 'page')
208
+ link.removeAttribute('aria-current')
209
+ }
210
+ }
211
+
212
+ function elementOfHash(hash: string): HTMLElement | null {
213
+ const raw = hash.slice(1)
214
+ let id: string
215
+ try {
216
+ id = decodeURIComponent(raw)
217
+ }
218
+ catch {
219
+ id = raw
220
+ }
221
+ return id === '' ? null : document.getElementById(id)
222
+ }
223
+
224
+ async function apply(region: HTMLElement, found: { content: DocumentFragment, title: string | undefined }, swap: Swap, finalUrl: URL): Promise<void> {
225
+ const { content, title } = found
226
+ // A typing burst and an append stay put: a transition freezes the page, and the field being typed in with it.
227
+ const animate = !swap.append && swap.history !== 'burst' && swap.fresh !== true
228
+ await swapInTransition(() => {
229
+ if (swap.append)
230
+ appended.add(shown)
231
+ else
232
+ appended.clear()
233
+ if (swap.history !== 'none') {
234
+ saveScroll()
235
+ record(finalUrl, swap.region, swap.history)
236
+ }
237
+ const kept = readScrolls(false)
238
+ const first = content.firstElementChild
239
+ if (swap.append) {
240
+ if (swap.trigger !== undefined && region.contains(swap.trigger))
241
+ swap.trigger.remove()
242
+ region.append(content)
243
+ }
244
+ else {
245
+ // A fetch for a region about to be replaced must not land in the new one.
246
+ for (const inner of region.querySelectorAll('[data-pru-region]'))
247
+ controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
248
+ replaceKeeping(region, content)
249
+ writeScrolls(kept)
250
+ if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
251
+ region.scrollTop = 0
252
+ }
253
+ ensureIslandRuntime(region)
254
+ if (title !== undefined)
255
+ document.title = title
256
+ syncParams()
257
+ syncCurrent()
258
+ if (swap.restore !== undefined)
259
+ restoreScroll(swap.restore)
260
+ else if (!swap.append && swap.history !== 'none')
261
+ elementOfHash(finalUrl.hash)?.scrollIntoView()
262
+ if (swap.focus === true)
263
+ focusNode(swap.append ? first : region)
264
+ const label = region.getAttribute('aria-label')
265
+ if (label !== null)
266
+ announce(label)
267
+ window.dispatchEvent(new CustomEvent('pru:region', { detail: { name: swap.region, url: location.href } }))
268
+ }, animate)
269
+ }
270
+
271
+ // Resolves false when the region could not be swapped: no such region, a failed fetch, or an answer without it.
272
+ async function swapRegion(swap: Swap): Promise<boolean> {
273
+ const name = swap.region
274
+ if (findRegion(name) === null)
275
+ return false
276
+ controllers.get(name)?.abort()
277
+ const controller = new AbortController()
278
+ controllers.set(name, controller)
279
+ const path = pathOf(findRegion(name)!)
280
+ const busy = setTimeout(() => findRegion(name)?.setAttribute('aria-busy', 'true'), BUSY_DELAY)
281
+ try {
282
+ const entry = await load(swap, path, controller.signal)
283
+ if (controller.signal.aborted)
284
+ return true
285
+ const content = entry === undefined ? undefined : contentOf(entry, path)
286
+ const region = findRegion(name)
287
+ if (entry === undefined || content === undefined || region === null)
288
+ return false
289
+ if (fromOtherBuild(content.build)) {
290
+ swap.stale = true
291
+ return false
292
+ }
293
+ const finalUrl = entry.url ? new URL(entry.url, location.href) : swap.url
294
+ if (finalUrl.origin !== location.origin)
295
+ return false
296
+ if (swap.url.hash && !finalUrl.hash)
297
+ finalUrl.hash = swap.url.hash
298
+ const twice = swap.append === true ? undefined : persistedIn(content.content).twice
299
+ if (twice !== undefined) {
300
+ console.error(`prunelle: data-persist="${twice}" is on two elements of the region "${name}" that ${finalUrl.pathname}${finalUrl.search} answers: give each its own key. The page loads whole instead.`)
301
+ return false
302
+ }
303
+ countView(entry.view, finalUrl)
304
+ await apply(region, content, swap, finalUrl)
305
+ return true
306
+ }
307
+ catch (err) {
308
+ return controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')
309
+ }
310
+ finally {
311
+ clearTimeout(busy)
312
+ if (controllers.get(name) === controller) {
313
+ controllers.delete(name)
314
+ findRegion(name)?.removeAttribute('aria-busy')
315
+ }
316
+ }
317
+ }
318
+
319
+ // A swap a link, a form or history asked for: what cannot be swapped loads the whole page. A form already posted and redirected loads the page its redirect reached, never posts twice; one whose post never got a redirect posts the plain way.
320
+ async function navigate(swap: Swap): Promise<void> {
321
+ if (await swapRegion(swap))
322
+ return
323
+ if (swap.post === undefined)
324
+ location.assign(swap.url.href)
325
+ else if (swap.landed)
326
+ location.assign(swap.landed)
327
+ else
328
+ swap.post.form.submit()
329
+ }
330
+
331
+ /** Redraws region `name` from the server at the current address, with no history entry and focus left where it is; reloads the page when the server runs another build; rejects when the page has no such region, the fetch fails or the answer lacks it. */
332
+ export async function refreshRegion(name: string): Promise<void> {
333
+ const swap: Swap = { url: new URL(location.href), region: name, history: 'none', fresh: true }
334
+ if (await swapRegion(swap))
335
+ return
336
+ if (swap.stale === true)
337
+ location.reload()
338
+ else
339
+ throw new Error(`prunelle: region "${name}" could not be redrawn from ${location.href}: render a <Region name="${name}"> on this page, and check the server answers it.`)
340
+ }
341
+
342
+ function formMethod(form: HTMLFormElement, submitter?: HTMLElement | null): string {
343
+ const rawMethod = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formmethod') : null)
344
+ ?? safeGetAttribute(form, 'method')
345
+ ?? 'get'
346
+ return rawMethod.toLowerCase()
347
+ }
348
+
349
+ function formAction(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
350
+ // Read raw attributes via Element.prototype.getAttribute so <input name="action"> cannot DOM-clobber form.action.
351
+ const rawAction = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formaction') : null)
352
+ ?? safeGetAttribute(form, 'action')
353
+ ?? ''
354
+ return new URL(rawAction, location.href)
355
+ }
356
+
357
+ /** The live form on the page that an element is, or belongs to by `form="<id>"` or as a descendant. */
358
+ function liveForm(el: Element | null): HTMLFormElement | null {
359
+ const form = el?.isConnected ? (el as HTMLInputElement).form ?? el.closest?.('form') : null
360
+ return form?.matches('[data-pru-live][data-pru-target]') ? form : null
361
+ }
362
+
363
+ function formUrl(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
364
+ const url = formAction(form, submitter)
365
+ // A field left empty stays out of the address, so it names only the filters in use; a button with an empty value clears its name, as a server reading the last value sees natively.
366
+ const cleared = (submitter as HTMLButtonElement | null | undefined)?.value === '' ? submitter!.getAttribute('name') : null
367
+ const params = new URLSearchParams()
368
+ for (const [key, value] of new FormData(form, submitter ?? undefined)) {
369
+ if (typeof value === 'string' && value !== '' && key !== cleared)
370
+ params.append(key, value)
371
+ }
372
+ url.search = params.toString()
373
+ return url
374
+ }
375
+
376
+ function missingRegion(name: string, element: string): boolean {
377
+ if (findRegion(name) !== null)
378
+ return false
379
+ console.error(`prunelle: ${element} targets the region "${name}", and this page has no <Region name="${name}">: add it, or fix the name. The link loads the whole page instead.`)
380
+ return true
381
+ }
382
+
383
+ function linkOf(event: Event): HTMLAnchorElement | null {
384
+ return (event.target as Element | null)?.closest?.<HTMLAnchorElement>('a[href][data-pru-target]') ?? null
385
+ }
386
+
387
+ const initializedDocs = new WeakSet<Document>()
388
+
389
+ /** Attaches the core `<Region>` link, form, prefetch, and history listeners to the current document (idempotent per document). */
390
+ export function initRegions(): void {
391
+ if (typeof document === 'undefined' || initializedDocs.has(document))
392
+ return
393
+ initializedDocs.add(document)
394
+ const initialState = stateOf(typeof history === 'undefined' ? undefined : history.state)
395
+ idx = initialState?.__pruIdx ?? 0
396
+ lastRegion = initialState?.__pruRegion
397
+ shown = typeof location === 'undefined' ? '' : location.pathname + location.search
398
+ appended.clear()
399
+ burstOpen = false
400
+
401
+ document.addEventListener('click', (event) => {
402
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
403
+ return
404
+ const link = linkOf(event)
405
+ if (link === null || link.target !== '' || link.hasAttribute('download'))
406
+ return
407
+ const url = new URL(link.href, location.href)
408
+ const name = link.getAttribute('data-pru-target')!
409
+ const append = link.hasAttribute('data-pru-append')
410
+ if (url.origin !== location.origin || missingRegion(name, `<a href="${link.getAttribute('href')}">`))
411
+ return
412
+ event.preventDefault()
413
+ // A hash already on the page is a scroll when the document holds the page the link names, with the address keeping its page.
414
+ const page = url.pathname + url.search
415
+ if (!append && (page === shown || appended.has(page)) && elementOfHash(url.hash) !== null) {
416
+ location.hash = url.hash
417
+ return
418
+ }
419
+ void navigate({ url, region: name, append, history: append ? 'replace' : 'push', focus: true, trigger: link })
420
+ }, true)
421
+
422
+ document.addEventListener('submit', (event) => {
423
+ const form = event.target as HTMLFormElement
424
+ if (!(form instanceof HTMLFormElement))
425
+ return
426
+ const submitter = (event as SubmitEvent).submitter
427
+ const name = safeGetAttribute(form, 'data-pru-target')
428
+ const method = formMethod(form, submitter)
429
+ if (event.defaultPrevented || name === null || (method !== 'get' && method !== 'post') || missingRegion(name, '<form>'))
430
+ return
431
+ event.preventDefault()
432
+ clearTimeout(liveTimer)
433
+ if (method === 'get')
434
+ void navigate({ url: formUrl(form, submitter), region: name, history: 'push' })
435
+ else
436
+ void navigate({ url: formAction(form, submitter), region: name, history: 'push', post: { form, body: new FormData(form, submitter ?? undefined) } })
437
+ }, true)
438
+
439
+ document.addEventListener('input', (event) => {
440
+ const field = event.target as Element | null
441
+ const typed = liveForm(field)
442
+ if (typed === null || formMethod(typed) !== 'get')
443
+ return
444
+ clearTimeout(liveTimer)
445
+ liveTimer = setTimeout(() => {
446
+ // A swap that landed since the key may have replaced the form: send the one on the page now, or nothing.
447
+ const form = liveForm(typed) ?? liveForm(field) ?? liveForm(typed.id === '' ? null : document.getElementById(typed.id))
448
+ const name = form && safeGetAttribute(form, 'data-pru-target')!
449
+ if (name && !missingRegion(name, '<form>'))
450
+ void navigate({ url: formUrl(form!), region: name, history: 'burst' })
451
+ }, LIVE_DEBOUNCE)
452
+ })
453
+
454
+ const onIntent = (event: Event) => {
455
+ const link = linkOf(event)
456
+ if (link === null || link.hasAttribute('data-no-prefetch') || link.closest('[data-pru-prefetch]') === null)
457
+ return
458
+ const url = new URL(link.href, location.href)
459
+ if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`) {
460
+ const region = findRegion(link.getAttribute('data-pru-target')!)
461
+ if (region !== null)
462
+ void prefetch(url.href, pathOf(region))
463
+ }
464
+ }
465
+ listenIntent(onIntent)
466
+
467
+ // Keep region state aligned when spa() swaps to another document (including popstate back to a document with prior region entries).
468
+ window.addEventListener('pru:navigate', () => {
469
+ shown = location.pathname + location.search
470
+ appended.clear()
471
+ const st = stateOf(history.state)
472
+ idx = st?.__pruIdx ?? 0
473
+ lastRegion = st?.__pruRegion
474
+ burstOpen = false
475
+ })
476
+ window.addEventListener('popstate', (event) => {
477
+ if (!isSameDocRegionState(event.state))
478
+ return
479
+ const state = stateOf(event.state)
480
+ const sameDocument = location.pathname + location.search === shown
481
+ shown = location.pathname + location.search
482
+ if (state === undefined)
483
+ return
484
+ const name = state.__pruIdx < idx ? lastRegion : state.__pruRegion
485
+ idx = state.__pruIdx
486
+ lastRegion = state.__pruRegion
487
+ burstOpen = false
488
+ const restore = entryScroll(event.state)
489
+ if (name === undefined || sameDocument) {
490
+ // With spa() the browser leaves the scroll to the page, a swap or not.
491
+ if (restore !== undefined && history.scrollRestoration === 'manual')
492
+ restoreScroll(restore)
493
+ return
494
+ }
495
+ void navigate({ url: new URL(location.href), region: name, history: 'none', ...(restore === undefined ? {} : { restore }) })
496
+ })
497
+ trackScroll()
498
+ }