@kayjs/kay 2.0.0-alpha.7 → 2.0.0-beta.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.
package/src/dom/index.ts CHANGED
@@ -27,29 +27,70 @@ export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
27
27
  return true
28
28
  }
29
29
 
30
- export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null } {
30
+ // `nodes` is the SSR range the render claimed through template() (a fragment hydrates to null, so the caller learns its nodes here).
31
+ export function claimInsert<T>(
32
+ parent: Node,
33
+ marker: Node | null,
34
+ fn: () => T,
35
+ startMarker?: Node | null,
36
+ ): { result: T, marker: Node | null, claimed: Node | null, nodes: Node[] | undefined } {
31
37
  if (!hydrating)
32
- return { result: fn(), marker, claimed: null }
38
+ return { result: fn(), marker, claimed: null, nodes: undefined }
33
39
 
34
- let claimed: Node | null = marker !== null ? marker : parent.lastChild
35
- let nextMarker = marker
36
- if (marker !== null && marker.nodeType !== 8) {
37
- const anchor = document.createComment('')
38
- ;(anchor as unknown as { __kayAnchor?: boolean }).__kayAnchor = true
39
- parent.insertBefore(anchor, marker.nextSibling)
40
- nextMarker = anchor
41
- }
42
- else if (marker !== null) {
43
- claimed = null
40
+ if (startMarker !== undefined) {
41
+ const first = startMarker === null ? parent.firstChild : startMarker.nextSibling
42
+ const claimed = first === marker ? null : first
43
+ const prevNode = hydrateNode
44
+ hydrateNode = claimed
45
+ let result: T
46
+ try {
47
+ result = fn()
48
+ }
49
+ finally {
50
+ hydrateNode = prevNode
51
+ }
52
+ const nodes: Node[] = []
53
+ for (let n: Node | null = claimed; n !== null && n !== marker; n = n.nextSibling)
54
+ nodes.push(n)
55
+ return { result, marker, claimed, nodes: nodes.length > 0 ? nodes : undefined }
44
56
  }
57
+
58
+ const claimed: Node | null = marker === null ? parent.lastChild : marker.nodeType === 8 ? null : marker
45
59
  const prevNode = hydrateNode
46
60
  hydrateNode = claimed
61
+ let result: T
62
+ let end: Node | null
47
63
  try {
48
- return { result: fn(), marker: nextMarker, claimed }
64
+ result = fn()
65
+ end = hydrateNode
49
66
  }
50
67
  finally {
51
68
  hydrateNode = prevNode
52
69
  }
70
+ if (marker === null) {
71
+ let nodes: Node[] | undefined
72
+ if (claimed !== null && end !== claimed) {
73
+ nodes = []
74
+ for (let n: Node | null = claimed; n !== null && n !== end; n = n.nextSibling)
75
+ nodes.push(n)
76
+ }
77
+ return { result, marker: null, claimed, nodes }
78
+ }
79
+ if (claimed === null)
80
+ return { result, marker, claimed, nodes: undefined }
81
+
82
+ // The anchor goes after the claimed range; a text value or a nested insert moves no cursor and claims the one node.
83
+ const consumed = end !== claimed
84
+ const anchor = document.createComment('')
85
+ ;(anchor as unknown as { __kayAnchor?: boolean }).__kayAnchor = true
86
+ parent.insertBefore(anchor, consumed ? end : claimed.nextSibling)
87
+ let nodes: Node[] | undefined
88
+ if (consumed) {
89
+ nodes = []
90
+ for (let n: Node | null = claimed; n !== null && n !== anchor; n = n.nextSibling)
91
+ nodes.push(n)
92
+ }
93
+ return { result, marker: anchor, claimed, nodes }
53
94
  }
54
95
 
55
96
  export function hydrate(container: Element, render: () => Node | DocumentFragment | null): () => void {
@@ -64,6 +105,10 @@ export function hydrate(container: Element, render: () => Node | DocumentFragmen
64
105
  render()
65
106
  })
66
107
  }
108
+ catch (err) {
109
+ disposeOwner(owner)
110
+ throw err
111
+ }
67
112
  finally {
68
113
  hydrating = prevHydrating
69
114
  hydrateNode = prevNode
@@ -82,6 +127,10 @@ export function mount(container: Element, render: () => Node | DocumentFragment
82
127
  if (node !== null)
83
128
  container.appendChild(node)
84
129
  }
130
+ catch (err) {
131
+ disposeOwner(owner)
132
+ throw err
133
+ }
85
134
  finally {
86
135
  hydrating = prevHydrating
87
136
  }
@@ -161,6 +210,14 @@ export function skipText(marker: Node): Node | null {
161
210
  return next !== null && next.nodeType === 3 ? next.nextSibling : next
162
211
  }
163
212
 
213
+ /** Advance past an SSR-bracketed dynamic range (`<!---->...<!---->`) to its closing comment marker. */
214
+ export function skipRange(marker: Node): Node | null {
215
+ let cur = marker.nextSibling
216
+ while (cur !== null && cur.nodeType !== 8)
217
+ cur = cur.nextSibling
218
+ return cur
219
+ }
220
+
164
221
  export function setText(node: Text, value: unknown): void {
165
222
  const str = value == null || typeof value === 'boolean' ? '' : String(value)
166
223
  if (node.data !== str)
@@ -185,13 +242,49 @@ export function setClass(el: Element, value: unknown): void {
185
242
  }
186
243
  }
187
244
 
245
+ const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
246
+ const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href'])
247
+ const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
248
+ const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
249
+
250
+ function isBlockedAttr(name: string): boolean {
251
+ if (!VALID_ATTR_NAME.test(name))
252
+ return true
253
+ const lower = name.toLowerCase()
254
+ return lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc'
255
+ }
256
+
257
+ function isStringBoolAttr(name: string): boolean {
258
+ const lower = name.toLowerCase()
259
+ return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
260
+ }
261
+
262
+ function isUnsafeUrlAttr(name: string, value: unknown): boolean {
263
+ if (!URL_ATTRS.has(name.toLowerCase()))
264
+ return false
265
+ return UNSAFE_URL_RE.test(String(value).replace(/[\u0000-\u0020]+/g, ''))
266
+ }
267
+
188
268
  export function setAttr(el: Element, name: string, value: unknown): void {
189
- if (value == null || value === false)
269
+ if (isBlockedAttr(name))
270
+ return
271
+ if (value == null) {
272
+ el.removeAttribute(name)
273
+ }
274
+ else if (typeof value === 'boolean') {
275
+ if (isStringBoolAttr(name))
276
+ el.setAttribute(name, value ? 'true' : 'false')
277
+ else if (value)
278
+ el.setAttribute(name, '')
279
+ else
280
+ el.removeAttribute(name)
281
+ }
282
+ else if (isUnsafeUrlAttr(name, value)) {
190
283
  el.removeAttribute(name)
191
- else if (value === true)
192
- el.setAttribute(name, '')
193
- else
284
+ }
285
+ else {
194
286
  el.setAttribute(name, String(value))
287
+ }
195
288
  }
196
289
 
197
290
  export function setProp(el: Element, name: string, value: unknown): void {
package/src/dom/island.ts CHANGED
@@ -33,12 +33,20 @@ export function defineIslandElement(): void {
33
33
 
34
34
  class KayIsland extends HTMLElement {
35
35
  _d: (() => void) | undefined
36
+ _c: (() => void) | undefined
36
37
  _s = false
38
+ _t = 0
39
+
40
+ _clearStrategy(): void {
41
+ this._c?.()
42
+ this._c = undefined
43
+ }
37
44
 
38
45
  connectedCallback(): void {
39
46
  if (this._s)
40
47
  return
41
48
  this._s = true
49
+ const token = ++this._t
42
50
 
43
51
  const h = this.getAttribute('h')
44
52
  if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
@@ -46,52 +54,74 @@ export function defineIslandElement(): void {
46
54
  const target = this.firstElementChild ?? this
47
55
  const io = new IntersectionObserver((entries) => {
48
56
  if (entries.some(e => e.isIntersecting)) {
49
- io.disconnect()
50
- void this._l(false)
57
+ this._clearStrategy()
58
+ void this._l(false, token)
51
59
  }
52
60
  }, { rootMargin: '200px' })
61
+ this._c = () => io.disconnect()
53
62
  io.observe(target)
54
63
  return
55
64
  }
56
65
  if (h === 'idle') {
57
- const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
58
- ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
66
+ const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
67
+ if (g.requestIdleCallback) {
68
+ const id = g.requestIdleCallback(() => {
69
+ this._c = undefined
70
+ void this._l(false, token)
71
+ })
72
+ this._c = () => g.cancelIdleCallback?.(id)
73
+ }
74
+ else {
75
+ const id = setTimeout(() => {
76
+ this._c = undefined
77
+ void this._l(false, token)
78
+ }, 1)
79
+ this._c = () => clearTimeout(id)
80
+ }
59
81
  return
60
82
  }
61
83
  if (h === 'interaction') {
62
84
  const evs = ['pointerdown', 'focusin', 'keydown']
63
- const go = () => {
85
+ const stop = () => {
64
86
  for (const e of evs) this.removeEventListener(e, go, true)
65
- void this._l(false)
87
+ }
88
+ const go = () => {
89
+ this._c = undefined
90
+ stop()
91
+ void this._l(false, token)
66
92
  }
67
93
  for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
94
+ this._c = stop
68
95
  return
69
96
  }
70
97
  if (h !== null && h.startsWith('media(')) {
71
98
  const mq = matchMedia(h.slice(6, -1))
72
99
  if (mq.matches) {
73
- void this._l(false)
100
+ void this._l(false, token)
74
101
  }
75
102
  else {
76
103
  const go = () => {
77
104
  if (mq.matches) {
78
- mq.removeEventListener('change', go)
79
- void this._l(false)
105
+ this._clearStrategy()
106
+ void this._l(false, token)
80
107
  }
81
108
  }
82
109
  mq.addEventListener('change', go)
110
+ this._c = () => mq.removeEventListener('change', go)
83
111
  }
84
112
  return
85
113
  }
86
114
  }
87
115
 
88
- void this._l(h === 'client')
116
+ void this._l(h === 'client', token)
89
117
  }
90
118
 
91
119
  disconnectedCallback(): void {
92
120
  // Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
93
121
  queueMicrotask(() => {
94
122
  if (!this.isConnected) {
123
+ this._t++
124
+ this._clearStrategy()
95
125
  this._d?.()
96
126
  this._d = undefined
97
127
  this._s = false
@@ -99,24 +129,37 @@ export function defineIslandElement(): void {
99
129
  })
100
130
  }
101
131
 
102
- async _l(clientOnly: boolean): Promise<void> {
132
+ async _l(clientOnly: boolean, token: number): Promise<void> {
133
+ this._clearStrategy()
103
134
  const chunk = this.getAttribute('c')
104
- if (!chunk)
135
+ if (!chunk || token !== this._t || !this.isConnected || this._d !== undefined)
105
136
  return
106
137
 
107
- const mod = await import(chunk) as IslandModule
108
- if (!this.isConnected)
109
- return
138
+ let dispose: (() => void) | undefined
139
+ try {
140
+ const mod = await import(chunk) as IslandModule
141
+ if (!this.isConnected || token !== this._t || this._d !== undefined)
142
+ return
110
143
 
111
- const p = this.getAttribute('p')
112
- const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
113
- const slot = this.querySelector('kay-slot')
114
- if (slot !== null)
115
- props.children = slot
116
- const render = () => mod.default(props)
117
- this._d = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
118
- ? mount(this, render)
119
- : hydrate(this, render)
144
+ const p = this.getAttribute('p')
145
+ const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
146
+ const slot = this.querySelector('kay-slot')
147
+ if (slot !== null)
148
+ props.children = slot
149
+ const render = () => mod.default(props)
150
+ dispose = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
151
+ ? mount(this, render)
152
+ : hydrate(this, render)
153
+ if (!this.isConnected || token !== this._t) {
154
+ dispose()
155
+ return
156
+ }
157
+ this._d = dispose
158
+ }
159
+ catch (err) {
160
+ dispose?.()
161
+ console.error(`[kay-island] failed to hydrate ${chunk}:`, err)
162
+ }
120
163
  }
121
164
  }
122
165
 
package/src/dom/loop.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // LIS minimal DOM moves (swap = 2 moves), and O(1) parent.textContent = '' clear.
3
3
 
4
4
  import type { Owner, Signal } from '../reactivity/index'
5
- import { createOwner, disposeOwner, effect, getOwner, runWithOwner, signal, untrack } from '../reactivity/index'
5
+ import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
6
6
  import { claimLoop } from './index'
7
7
 
8
8
  interface Row<T> {
@@ -27,6 +27,11 @@ export function loop<T>(
27
27
  const parentOwner = getOwner()
28
28
  const needsIndex = renderRow.length >= 2
29
29
  let rows: Row<T>[] = []
30
+ if (parentOwner !== undefined) {
31
+ onCleanup(() => {
32
+ rows = []
33
+ })
34
+ }
30
35
 
31
36
  const makeRow = (itemVal: T, idx: number, key: unknown): Row<T> => {
32
37
  const owner = createOwner(parentOwner)
@@ -36,11 +36,16 @@ export interface CheckPluginContext {
36
36
  error(message: string): void
37
37
  }
38
38
 
39
+ export interface PluginRouteOptions {
40
+ /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks). */
41
+ csrf?: boolean | undefined
42
+ }
43
+
39
44
  export interface ServerPluginAPI {
40
45
  /** Register global middleware that runs before route handlers. */
41
46
  use(middleware: Middleware): void
42
47
  /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
43
- route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>): void
48
+ route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
44
49
  /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
45
50
  rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
46
51
  }
@@ -88,6 +93,8 @@ export interface KayConfig {
88
93
  assetPrefix?: string | undefined
89
94
  security?: SecurityHeadersOptions | false | undefined
90
95
  trustedOrigins?: string[] | undefined
96
+ trustProxy?: boolean | undefined
97
+ maxRequestBodySize?: number | undefined
91
98
  compress?: boolean | undefined
92
99
  onError?: ((info: ServerErrorInfo) => void) | undefined
93
100
  plugins?: KayPlugin[] | undefined