prunelle 0.0.0-stage → 0.7.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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,329 @@
1
+ // Prunelle minimal DOM & hydration core. Every island imports it, so what only some islands need lives apart: attribute bindings in prunelle/internal/dom-attrs, claiming SSR lists and inserts in dom-claim, lists in dom-loop, inserts and spreads in dom-extras.
2
+
3
+ import { batch, createOwner, disposeOwner, getOwner, onCleanup, runWithOwner } from '../reactivity/index'
4
+ import { assertRenderable } from '../unrenderable'
5
+
6
+ export { effect } from '../reactivity/index'
7
+
8
+ let hydrating = false
9
+ let hydrateNode: Node | null = null
10
+ let hydrateRoot: Element | null = null
11
+ let mismatchHook: ((parent: Node, stale: Node, node: Node) => void) | null = null
12
+
13
+ export function setMismatchHook(fn: typeof mismatchHook): typeof mismatchHook {
14
+ const prev = mismatchHook
15
+ mismatchHook = fn
16
+ return prev
17
+ }
18
+
19
+ export function isRangeEnd(node: Node): boolean {
20
+ return node.nodeType === 8 && (node as Comment).data === 'k]'
21
+ }
22
+
23
+ export function hydrateCursor(): Node | null {
24
+ return hydrating ? hydrateNode : null
25
+ }
26
+
27
+ export function isHydrating(): boolean {
28
+ return hydrating
29
+ }
30
+
31
+ /** Points the hydration cursor at `node` (claiming SSR nodes when `on`) and returns the cursor it replaced, for the caller to restore. */
32
+ export function moveCursor(on: boolean, node: Node | null): [boolean, Node | null] {
33
+ const prev: [boolean, Node | null] = [hydrating, hydrateNode]
34
+ hydrating = on
35
+ hydrateNode = node
36
+ return prev
37
+ }
38
+
39
+ export function hydrate(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
40
+ const owner = createOwner(undefined)
41
+ if (idPrefix !== undefined)
42
+ owner.id = { p: idPrefix, n: 0 }
43
+ const prevHydrating = hydrating
44
+ const prevNode = hydrateNode
45
+ const prevRoot = process.env.NODE_ENV !== 'production' ? hydrateRoot : null
46
+ hydrating = true
47
+ hydrateNode = container.firstChild
48
+ if (process.env.NODE_ENV !== 'production')
49
+ hydrateRoot = container
50
+
51
+ try {
52
+ const node = runWithOwner(owner, render)
53
+ if (node !== null && node.parentNode === null)
54
+ container.appendChild(node)
55
+ }
56
+ catch (err) {
57
+ disposeOwner(owner)
58
+ throw err
59
+ }
60
+ finally {
61
+ hydrating = prevHydrating
62
+ hydrateNode = prevNode
63
+ if (process.env.NODE_ENV !== 'production')
64
+ hydrateRoot = prevRoot
65
+ }
66
+
67
+ return () => disposeOwner(owner)
68
+ }
69
+
70
+ export function mount(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
71
+ const owner = createOwner(undefined)
72
+ if (idPrefix !== undefined)
73
+ owner.id = { p: idPrefix, n: 0 }
74
+ const prevHydrating = hydrating
75
+ hydrating = false
76
+ try {
77
+ const node = runWithOwner(owner, render)
78
+ container.textContent = ''
79
+ if (node !== null)
80
+ container.appendChild(node)
81
+ }
82
+ catch (err) {
83
+ disposeOwner(owner)
84
+ throw err
85
+ }
86
+ finally {
87
+ hydrating = prevHydrating
88
+ }
89
+ return () => disposeOwner(owner)
90
+ }
91
+
92
+ function warnMismatch(node: Node, expectedTag: string, steppedOver: boolean): void {
93
+ const island = hydrateRoot?.getAttribute('c') ?? hydrateRoot?.tagName.toLowerCase() ?? 'unknown'
94
+ const found = node.nodeType === 1
95
+ ? `<${(node as Element).tagName.toLowerCase()}>`
96
+ : node.nodeType === 3
97
+ ? `#text(${JSON.stringify((node as Text).data.slice(0, 30))})`
98
+ : node.nodeType === 8
99
+ ? `<!--${(node as Comment).data}-->`
100
+ : `nodeType(${node.nodeType})`
101
+ console.warn(`prunelle: hydration mismatch in island "${island}": expected <${expectedTag}>, found ${found}; ${steppedOver ? `hydrating the next <${expectedTag}>` : 'falling back to fresh clone'}.`)
102
+ }
103
+
104
+ export function template(html: string, isSvg?: boolean): () => Node {
105
+ let cached: Node | undefined
106
+ const expectedTag = /^<([A-Za-z][^\s/>]*)/.exec(html)?.[1]?.toLowerCase()
107
+
108
+ const clone = (): Node => {
109
+ if (cached === undefined) {
110
+ const t = document.createElement('template')
111
+ t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
112
+ cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
113
+ }
114
+ return cached.cloneNode(true)
115
+ }
116
+
117
+ return (): Node => {
118
+ if (hydrating && hydrateNode !== null) {
119
+ const stale = hydrateNode
120
+ // Stop at a closing range marker so a mismatch inside a branch never steals or replaces nodes outside it.
121
+ if (isRangeEnd(stale)) {
122
+ if (process.env.NODE_ENV !== 'production' && expectedTag !== undefined)
123
+ warnMismatch(stale, expectedTag, false)
124
+ hydrating = false
125
+ hydrateNode = null
126
+ return clone()
127
+ }
128
+ // A node injected before the markup (an extension, a password manager) is stepped over; no matching node at all means the server rendered something else.
129
+ let node: Node | null = stale
130
+ while (node !== null && !isRangeEnd(node) && expectedTag !== undefined && node.nodeName.toLowerCase() !== expectedTag)
131
+ node = node.nextSibling
132
+ if (node !== null && isRangeEnd(node))
133
+ node = null
134
+ if (process.env.NODE_ENV !== 'production' && node !== stale)
135
+ warnMismatch(stale, expectedTag!, node !== null)
136
+ const parent = stale.parentNode
137
+ if (node === null) {
138
+ hydrating = false
139
+ hydrateNode = null
140
+ node = clone()
141
+ parent?.replaceChild(node, stale)
142
+ }
143
+ else {
144
+ hydrateNode = node.nextSibling
145
+ }
146
+ if (node !== stale && parent !== null)
147
+ mismatchHook?.(parent, stale, node)
148
+ return node
149
+ }
150
+
151
+ return clone()
152
+ }
153
+ }
154
+
155
+ // Moves the hydration cursor past the SSR range of a root fragment's dynamic child (`<!--k[-->...<!--k]-->` or `<!---->text<!---->`) and returns its opening marker; null when not hydrating.
156
+ export function claimRange(): Node | null {
157
+ const start = hydrating ? hydrateNode : null
158
+ if (start === null || start.nodeType !== 8)
159
+ return null
160
+ hydrateNode = skipRange(start)?.nextSibling ?? null
161
+ return start
162
+ }
163
+
164
+ // A text child of a root fragment, claimed from the SSR markup while hydrating; a dynamic one sits between `<!---->` markers.
165
+ export function fragText(data: string, dynamic?: boolean): Text {
166
+ if (dynamic) {
167
+ const start = claimRange()
168
+ if (start !== null)
169
+ return textAfter(start)
170
+ }
171
+ else if (hydrating && hydrateNode !== null && hydrateNode.nodeType === 3) {
172
+ const text = hydrateNode as Text
173
+ hydrateNode = text.nextSibling
174
+ return text
175
+ }
176
+ return document.createTextNode(data)
177
+ }
178
+
179
+ export function frag(...nodes: (Node | null)[]): Node | null {
180
+ const first = nodes.find(n => n?.parentNode && n.parentNode.nodeType !== 11)
181
+ if (first) {
182
+ const parent = first.parentNode!
183
+ let prev: Node | null = null
184
+ for (const n of nodes) {
185
+ if (!n)
186
+ continue
187
+ if (n.parentNode === parent) {
188
+ prev = n
189
+ continue
190
+ }
191
+ const tail = n.nodeType === 11 ? n.lastChild : n
192
+ parent.insertBefore(n, prev ? prev.nextSibling : first)
193
+ if (prev && tail)
194
+ prev = tail
195
+ }
196
+ return null
197
+ }
198
+ let f: DocumentFragment | null = null
199
+ for (const n of nodes) {
200
+ if (n)
201
+ (f ??= document.createDocumentFragment()).appendChild(n)
202
+ }
203
+ return f
204
+ }
205
+
206
+ export function firstText(el: Node): Text {
207
+ const first = el.firstChild
208
+ if (first !== null && first.nodeType === 3)
209
+ return first as Text
210
+ const text = document.createTextNode('')
211
+ el.insertBefore(text, first)
212
+ return text
213
+ }
214
+
215
+ export function textAfter(marker: Node): Text {
216
+ const next = marker.nextSibling
217
+ if (next !== null && next.nodeType === 3)
218
+ return next as Text
219
+ const text = document.createTextNode('')
220
+ marker.parentNode!.insertBefore(text, next)
221
+ return text
222
+ }
223
+
224
+ /** Advance past an optional SSR text node (`<!-->text<!-->` or `<!--><!-->`) to the closing comment marker. */
225
+ export function skipText(marker: Node): Node | null {
226
+ const next = marker.nextSibling
227
+ return next !== null && next.nodeType === 3 ? next.nextSibling : next
228
+ }
229
+
230
+ /** Advance past an SSR-bracketed dynamic range (`<!--k[-->...<!--k]-->` or `<!---->...<!---->`) to its closing comment marker. */
231
+ export function skipRange(marker: Node): Node | null {
232
+ const balanced = marker.nodeType === 8 && (marker as Comment).data === 'k['
233
+ let depth = balanced ? 1 : 0
234
+ let cur = marker.nextSibling
235
+ while (cur !== null) {
236
+ if (cur.nodeType === 8) {
237
+ if (!balanced)
238
+ return cur
239
+ const data = (cur as Comment).data
240
+ if (data === 'k[')
241
+ depth++
242
+ else if (data === 'k]' && --depth === 0)
243
+ return cur
244
+ }
245
+ cur = cur.nextSibling
246
+ }
247
+ return null
248
+ }
249
+
250
+ export function setText(node: Text, value: unknown): void {
251
+ if (process.env.NODE_ENV !== 'production')
252
+ assertRenderable(value, 'text')
253
+ const str = value == null || typeof value === 'boolean' ? '' : String(value)
254
+ if (node.data !== str)
255
+ node.data = str
256
+ }
257
+
258
+ // ---- Delegated events
259
+
260
+ const delegated = new WeakMap<Document, Set<string>>()
261
+
262
+ function dispatchEvent(event: Event): void {
263
+ const key = `$$${event.type}`
264
+ let current: EventTarget | null = null
265
+ const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
266
+ Object.defineProperty(event, 'currentTarget', { configurable: true, get: () => current })
267
+ const errors: unknown[] = []
268
+
269
+ try {
270
+ const path = event.composedPath?.()
271
+ const usePath = path !== undefined && path.length > 0
272
+ let i = 0
273
+ let node = (usePath ? path[0] : event.target) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
274
+ while (node != null) {
275
+ const handler = node[key]
276
+ if (typeof handler === 'function') {
277
+ current = node
278
+ try {
279
+ batch(() => handler(event))
280
+ }
281
+ catch (err) {
282
+ errors.push(err)
283
+ }
284
+ if (event.cancelBubble)
285
+ break
286
+ }
287
+ node = (usePath ? path[++i] : (node as unknown as Node).parentNode) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
288
+ }
289
+ }
290
+ finally {
291
+ if (prevDesc !== undefined)
292
+ Object.defineProperty(event, 'currentTarget', prevDesc)
293
+ else
294
+ delete (event as unknown as Record<string, unknown>).currentTarget
295
+ }
296
+ // Every handler ran: the first error is thrown as before, the others are reported.
297
+ for (let i = 1; i < errors.length; i++)
298
+ reportError(errors[i])
299
+ if (errors.length > 0)
300
+ throw errors[0]
301
+ }
302
+
303
+ export function delegate(events: string[]): void {
304
+ if (typeof document === 'undefined')
305
+ return
306
+ let set = delegated.get(document)
307
+ if (set === undefined) {
308
+ set = new Set()
309
+ delegated.set(document, set)
310
+ }
311
+ for (let i = 0; i < events.length; i++) {
312
+ const type = events[i]!
313
+ if (!set.has(type)) {
314
+ set.add(type)
315
+ document.addEventListener(type, dispatchEvent)
316
+ }
317
+ }
318
+ }
319
+
320
+ export function on(el: Node, event: string, handler: ((e: Event) => void) | false | null | undefined): void {
321
+ if (typeof handler !== 'function')
322
+ return
323
+ const fn = (e: Event) => {
324
+ batch(() => handler(e))
325
+ }
326
+ el.addEventListener(event, fn)
327
+ if (getOwner() !== undefined)
328
+ onCleanup(() => el.removeEventListener(event, fn))
329
+ }
@@ -0,0 +1,318 @@
1
+ // Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
2
+
3
+ import type { hydrate, mount } from './index'
4
+
5
+ declare const PRUNELLE_VISIBLE: boolean | undefined
6
+ declare const PRUNELLE_IDLE: boolean | undefined
7
+ declare const PRUNELLE_INTERACTION: boolean | undefined
8
+ declare const PRUNELLE_MEDIA: boolean | undefined
9
+ declare const PRUNELLE_CLIENT_ONLY: boolean | undefined
10
+ /** The URL `prunelle build` gave the prop revivers; left undefined, they load from source. */
11
+ declare const PRUNELLE_REVIVE: string | undefined
12
+
13
+ // Only props holding a Date, Map, Set or another tagged value load the revivers: plain JSON parses with no extra file.
14
+ const reviver = (): Promise<typeof import('./revive')> => typeof PRUNELLE_REVIVE === 'undefined' ? import('./revive') : import(PRUNELLE_REVIVE)
15
+
16
+ // An island chunk also re-exports the DOM runtime it imports (`writeClientEntries`), `mount` only in an app with a client-only island.
17
+ type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null, hydrate: typeof hydrate, mount?: typeof mount }
18
+
19
+ /** Finds this island's own `<script type="application/json" data-pru-props>` direct child. */
20
+ function findOwnPropsScript(root: Element): Element | null {
21
+ for (let child = root.lastElementChild; child !== null; child = child.previousElementSibling) {
22
+ if (child.tagName === 'SCRIPT' && child.hasAttribute('data-pru-props'))
23
+ return child
24
+ }
25
+ return null
26
+ }
27
+
28
+ /** Finds this island's own `<pru-slot>` without descending into nested `<pru-island>` boundaries. */
29
+ function findOwnSlot(root: Element): Element | null {
30
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
31
+ const tag = child.tagName
32
+ if (tag === 'PRU-SLOT')
33
+ return child
34
+ if (tag === 'PRU-ISLAND')
35
+ continue
36
+ const nested = findOwnSlot(child)
37
+ if (nested !== null)
38
+ return nested
39
+ }
40
+ return null
41
+ }
42
+
43
+ function extractOwnSlot(root: Element): Element | null {
44
+ for (let child = root.lastElementChild; child !== null; child = child.previousElementSibling) {
45
+ if (child.tagName === 'TEMPLATE' && child.hasAttribute('data-pru-slot')) {
46
+ const slot = document.createElement('pru-slot')
47
+ slot.appendChild((child as HTMLTemplateElement).content)
48
+ child.remove()
49
+ return slot
50
+ }
51
+ }
52
+ return findOwnSlot(root)
53
+ }
54
+
55
+ /** Collects box-generating descendant elements for IntersectionObserver, stepping through `display: contents` wrappers. */
56
+ function collectVisibleTargets(root: Element, out: Element[]): void {
57
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
58
+ const tag = child.tagName
59
+ if (tag === 'SCRIPT' || tag === 'TEMPLATE')
60
+ continue
61
+ const isContents = tag === 'PRU-SLOT'
62
+ || tag === 'PRU-ISLAND'
63
+ || (typeof getComputedStyle === 'function' && getComputedStyle(child).display === 'contents')
64
+ if (isContents)
65
+ collectVisibleTargets(child, out)
66
+ else
67
+ out.push(child)
68
+ }
69
+ }
70
+
71
+ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void {
72
+ if (target === null || typeof target.dispatchEvent !== 'function')
73
+ return
74
+ if (typeof (target as Node).nodeType === 'number' && !root.contains(target as Node))
75
+ return
76
+ const init: EventInit = { bubbles: ev.bubbles, cancelable: ev.cancelable, composed: ev.composed }
77
+ let clone: Event
78
+ if (ev.type === 'keydown') {
79
+ const ke = ev as KeyboardEvent
80
+ clone = new KeyboardEvent(ev.type, { ...init, key: ke.key, code: ke.code, altKey: ke.altKey, ctrlKey: ke.ctrlKey, shiftKey: ke.shiftKey, metaKey: ke.metaKey })
81
+ }
82
+ else if (ev.type === 'click' || ev.type === 'pointerdown') {
83
+ const me = ev as MouseEvent
84
+ const Ctor = ev.type === 'pointerdown' && typeof PointerEvent === 'function' ? PointerEvent : MouseEvent
85
+ clone = new Ctor(ev.type, { ...init, button: me.button, buttons: me.buttons, clientX: me.clientX, clientY: me.clientY, altKey: me.altKey, ctrlKey: me.ctrlKey, shiftKey: me.shiftKey, metaKey: me.metaKey })
86
+ }
87
+ else {
88
+ clone = typeof FocusEvent === 'function' ? new FocusEvent(ev.type, init) : new Event(ev.type, init)
89
+ }
90
+ target.dispatchEvent(clone)
91
+ }
92
+
93
+ // A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
94
+ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
95
+ const evs = ['pointerdown', 'click', 'focusin', 'keydown']
96
+ const queued: { ev: Event, target: EventTarget | null }[] = []
97
+ let loading = false
98
+ const go = (ev: Event) => {
99
+ // Prevent native toggle/submit/navigation before hydration so replaying the click triggers it once with handlers attached.
100
+ if (ev.type === 'click')
101
+ ev.preventDefault()
102
+ queued.push({ ev, target: ev.target })
103
+ if (!loading) {
104
+ loading = true
105
+ void onTrigger(() => {
106
+ for (let i = 0; i < queued.length; i++)
107
+ replayEvent(root, queued[i]!.ev, queued[i]!.target)
108
+ }).then((ok) => {
109
+ if (!ok) {
110
+ loading = false
111
+ queued.length = 0
112
+ }
113
+ })
114
+ }
115
+ }
116
+ for (const e of evs) root.addEventListener(e, go, true)
117
+ return () => {
118
+ for (const e of evs) root.removeEventListener(e, go, true)
119
+ }
120
+ }
121
+
122
+ function isAllowedChunkUrl(chunk: string): boolean {
123
+ if (/[\u0000-\u0020\u007F]/.test(chunk))
124
+ return false
125
+ if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
126
+ try {
127
+ return new URL(chunk, location.href).origin === location.origin
128
+ }
129
+ catch {
130
+ return false
131
+ }
132
+ }
133
+ // A browser reads `//host` and `/\host` as another site.
134
+ if (chunk[0] === '/')
135
+ return chunk[1] !== '/' && chunk[1] !== '\\'
136
+ return !/^(?:javascript|data|vbscript):/i.test(chunk)
137
+ }
138
+
139
+ function watchVisible(root: HTMLElement, onVisible: () => void): (() => void) | undefined {
140
+ if (typeof IntersectionObserver === 'undefined') {
141
+ onVisible()
142
+ return undefined
143
+ }
144
+ const targets: Element[] = []
145
+ collectVisibleTargets(root, targets)
146
+ let restoreDisplay: (() => void) | undefined
147
+ if (targets.length === 0) {
148
+ const display = typeof getComputedStyle === 'function' ? getComputedStyle(root).display : 'contents'
149
+ if (display === 'contents' || display === '') {
150
+ const prev = root.style.display
151
+ root.style.display = 'inline'
152
+ restoreDisplay = () => { root.style.display = prev }
153
+ }
154
+ targets.push(root)
155
+ }
156
+ const io = new IntersectionObserver((entries) => {
157
+ if (entries.some(e => e.isIntersecting))
158
+ onVisible()
159
+ }, { rootMargin: '200px' })
160
+ for (const target of targets)
161
+ io.observe(target)
162
+ return () => {
163
+ io.disconnect()
164
+ restoreDisplay?.()
165
+ }
166
+ }
167
+
168
+ let clientIslandIdSeq = 0
169
+
170
+ export function defineIslandElement(): void {
171
+ if (typeof customElements === 'undefined' || customElements.get('pru-island'))
172
+ return
173
+
174
+ class PrunelleIsland extends HTMLElement {
175
+ _d: (() => void) | undefined
176
+ _c: (() => void) | undefined
177
+ _p: string | undefined
178
+ _slot: Element | undefined
179
+ _s = false
180
+ _t = 0
181
+
182
+ _clearStrategy(token?: number): void {
183
+ if (token !== undefined && token !== this._t)
184
+ return
185
+ this._c?.()
186
+ this._c = undefined
187
+ }
188
+
189
+ connectedCallback(): void {
190
+ if (this._s)
191
+ return
192
+ this._s = true
193
+ const token = ++this._t
194
+
195
+ const h = this.getAttribute('h')
196
+ if ((typeof PRUNELLE_VISIBLE === 'undefined' || PRUNELLE_VISIBLE) && h === 'visible') {
197
+ this._c = watchVisible(this, () => void this._l(false, token))
198
+ return
199
+ }
200
+ if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
201
+ const g = globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number, cancelIdleCallback?: (id: number) => void }
202
+ const run = () => void this._l(false, token)
203
+ if (g.requestIdleCallback) {
204
+ const id = g.requestIdleCallback(run, { timeout: 2000 })
205
+ this._c = () => g.cancelIdleCallback?.(id)
206
+ }
207
+ else {
208
+ const id = setTimeout(run, 1)
209
+ this._c = () => clearTimeout(id)
210
+ }
211
+ return
212
+ }
213
+ if ((typeof PRUNELLE_INTERACTION === 'undefined' || PRUNELLE_INTERACTION) && h === 'interaction') {
214
+ this._c = watchInteraction(this, after => this._l(false, token, true, after))
215
+ return
216
+ }
217
+ if ((typeof PRUNELLE_MEDIA === 'undefined' || PRUNELLE_MEDIA) && h !== null && h.startsWith('media(')) {
218
+ const mq = matchMedia(h.slice(6, -1))
219
+ if (mq.matches) {
220
+ void this._l(false, token)
221
+ }
222
+ else {
223
+ const go = () => {
224
+ if (mq.matches)
225
+ void this._l(false, token)
226
+ }
227
+ mq.addEventListener('change', go)
228
+ this._c = () => mq.removeEventListener('change', go)
229
+ }
230
+ return
231
+ }
232
+
233
+ void this._l(h === 'client', token)
234
+ }
235
+
236
+ disconnectedCallback(): void {
237
+ // Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
238
+ queueMicrotask(() => {
239
+ if (!this.isConnected) {
240
+ this._t++
241
+ this._clearStrategy()
242
+ this._d?.()
243
+ this._d = undefined
244
+ this._s = false
245
+ }
246
+ })
247
+ }
248
+
249
+ // Resolves false when the chunk failed to load or hydrate.
250
+ async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<boolean> {
251
+ if (token !== this._t)
252
+ return true
253
+ if (!keepStrategy)
254
+ this._clearStrategy(token)
255
+ const chunk = this.getAttribute('c')
256
+ if (!chunk || !isAllowedChunkUrl(chunk) || !this.isConnected || this._d !== undefined) {
257
+ if (chunk && !isAllowedChunkUrl(chunk))
258
+ console.error(`[pru-island] refused chunk URL ${chunk}: it must be on this origin.`)
259
+ this._clearStrategy(token)
260
+ if (!this.isConnected)
261
+ this._s = false
262
+ return true
263
+ }
264
+
265
+ let dispose: (() => void) | undefined
266
+ let mod: IslandModule | undefined
267
+ try {
268
+ const ps = findOwnPropsScript(this)
269
+ if (ps !== null) {
270
+ this._p = ps.textContent || '{}'
271
+ ps.remove()
272
+ }
273
+ const raw = this._p ?? this.getAttribute('p')
274
+ const [loaded, revive] = await Promise.all([import(chunk) as Promise<IslandModule>, raw?.includes('"__k":') ? reviver() : undefined])
275
+ mod = loaded
276
+ if (token !== this._t)
277
+ return true
278
+ this._clearStrategy(token)
279
+ if (!this.isConnected || this._d !== undefined) {
280
+ if (!this.isConnected)
281
+ this._s = false
282
+ return true
283
+ }
284
+
285
+ const props = (raw ? revive?.parseIslandProps(raw) ?? JSON.parse(raw) : {}) as Record<string, unknown>
286
+ const slot = extractOwnSlot(this) ?? this._slot ?? null
287
+ if (slot !== null) {
288
+ this._slot = slot
289
+ props.children = slot
290
+ }
291
+ const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
292
+ const render = () => loaded.default(props)
293
+ dispose = (typeof PRUNELLE_CLIENT_ONLY === 'undefined' || PRUNELLE_CLIENT_ONLY) && clientOnly
294
+ ? loaded.mount!(this, render, idPrefix)
295
+ : loaded.hydrate(this, render, idPrefix)
296
+ if (!this.isConnected || token !== this._t) {
297
+ dispose()
298
+ if (token === this._t)
299
+ this._s = false
300
+ return true
301
+ }
302
+ this._d = dispose
303
+ after?.()
304
+ return true
305
+ }
306
+ catch (err) {
307
+ if (!keepStrategy)
308
+ this._clearStrategy(token)
309
+ dispose?.()
310
+ // The chunk URL is a hash; in dev the component's own name says which island failed.
311
+ console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
312
+ return false
313
+ }
314
+ }
315
+ }
316
+
317
+ customElements.define('pru-island', PrunelleIsland)
318
+ }