@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.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 (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
package/src/dom/index.ts CHANGED
@@ -1,21 +1,32 @@
1
1
  // Kay v2 minimal DOM & hydration core (loop -> kay/dom-loop, extras -> kay/dom-extras for fine-grained chunk splitting).
2
2
 
3
+ import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
3
4
  import { batch, createOwner, disposeOwner, runWithOwner } from '../reactivity/index'
5
+ import { styleText } from '../style'
6
+ import { assertRenderable } from '../unrenderable'
4
7
 
8
+ export { isBlockedAttr } from '../attrs'
5
9
  export { effect } from '../reactivity/index'
6
10
 
7
11
  let hydrating = false
8
12
  let hydrateNode: Node | null = null
13
+ let hydrateRoot: Element | null = null
9
14
 
10
- export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
15
+ export function claimLoop(parent: Node, fn: () => void, skip = 0, startMarker?: Node | null): boolean {
11
16
  if (!hydrating)
12
17
  return false
13
18
  const prevCursor = hydrateNode
14
- let cur = parent.firstChild
15
- for (let i = 0; i < skip && cur !== null; i++) {
16
- cur = cur.nextSibling
17
- while (cur !== null && (cur as unknown as { __kayAnchor?: boolean }).__kayAnchor === true)
19
+ let cur: Node | null
20
+ if (startMarker !== undefined && startMarker !== null) {
21
+ cur = startMarker.nextSibling
22
+ }
23
+ else {
24
+ cur = parent.firstChild
25
+ for (let i = 0; i < skip && cur !== null; i++) {
18
26
  cur = cur.nextSibling
27
+ while (cur !== null && (cur as unknown as { __kayAnchor?: boolean }).__kayAnchor === true)
28
+ cur = cur.nextSibling
29
+ }
19
30
  }
20
31
  hydrateNode = cur
21
32
  try {
@@ -27,6 +38,14 @@ export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
27
38
  return true
28
39
  }
29
40
 
41
+ // The siblings from `from` up to, not including, `to`; undefined when there are none.
42
+ function between(from: Node | null, to: Node | null): Node[] | undefined {
43
+ const nodes: Node[] = []
44
+ for (let n = from; n !== null && n !== to; n = n.nextSibling)
45
+ nodes.push(n)
46
+ return nodes.length > 0 ? nodes : undefined
47
+ }
48
+
30
49
  // `nodes` is the SSR range the render claimed through template() (a fragment hydrates to null, so the caller learns its nodes here).
31
50
  export function claimInsert<T>(
32
51
  parent: Node,
@@ -37,25 +56,14 @@ export function claimInsert<T>(
37
56
  if (!hydrating)
38
57
  return { result: fn(), marker, claimed: null, nodes: undefined }
39
58
 
59
+ let claimed: Node | null
40
60
  if (startMarker !== undefined) {
41
61
  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 }
62
+ claimed = first === marker ? null : first
63
+ }
64
+ else {
65
+ claimed = marker === null ? parent.lastChild : marker.nodeType === 8 ? null : marker
56
66
  }
57
-
58
- const claimed: Node | null = marker === null ? parent.lastChild : marker.nodeType === 8 ? null : marker
59
67
  const prevNode = hydrateNode
60
68
  hydrateNode = claimed
61
69
  let result: T
@@ -67,15 +75,10 @@ export function claimInsert<T>(
67
75
  finally {
68
76
  hydrateNode = prevNode
69
77
  }
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
- }
78
+ if (startMarker !== undefined)
79
+ return { result, marker, claimed, nodes: between(claimed, marker) }
80
+ if (marker === null)
81
+ return { result, marker: null, claimed, nodes: between(claimed, end) }
79
82
  if (claimed === null)
80
83
  return { result, marker, claimed, nodes: undefined }
81
84
 
@@ -84,21 +87,20 @@ export function claimInsert<T>(
84
87
  const anchor = document.createComment('')
85
88
  ;(anchor as unknown as { __kayAnchor?: boolean }).__kayAnchor = true
86
89
  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 }
90
+ return { result, marker: anchor, claimed, nodes: consumed ? between(claimed, anchor) : undefined }
94
91
  }
95
92
 
96
- export function hydrate(container: Element, render: () => Node | DocumentFragment | null): () => void {
93
+ export function hydrate(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
97
94
  const owner = createOwner(undefined)
95
+ if (idPrefix !== undefined)
96
+ owner.id = { p: idPrefix, n: 0 }
98
97
  const prevHydrating = hydrating
99
98
  const prevNode = hydrateNode
99
+ const prevRoot = process.env.NODE_ENV !== 'production' ? hydrateRoot : null
100
100
  hydrating = true
101
101
  hydrateNode = container.firstChild
102
+ if (process.env.NODE_ENV !== 'production')
103
+ hydrateRoot = container
102
104
 
103
105
  try {
104
106
  runWithOwner(owner, () => {
@@ -112,13 +114,17 @@ export function hydrate(container: Element, render: () => Node | DocumentFragmen
112
114
  finally {
113
115
  hydrating = prevHydrating
114
116
  hydrateNode = prevNode
117
+ if (process.env.NODE_ENV !== 'production')
118
+ hydrateRoot = prevRoot
115
119
  }
116
120
 
117
121
  return () => disposeOwner(owner)
118
122
  }
119
123
 
120
- export function mount(container: Element, render: () => Node | DocumentFragment | null): () => void {
124
+ export function mount(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
121
125
  const owner = createOwner(undefined)
126
+ if (idPrefix !== undefined)
127
+ owner.id = { p: idPrefix, n: 0 }
122
128
  const prevHydrating = hydrating
123
129
  hydrating = false
124
130
  try {
@@ -139,20 +145,46 @@ export function mount(container: Element, render: () => Node | DocumentFragment
139
145
 
140
146
  export function template(html: string, isSvg?: boolean): () => Node {
141
147
  let cached: Node | undefined
148
+ const expectedTag = process.env.NODE_ENV !== 'production'
149
+ ? /^<([A-Za-z][^\s/>]*)/.exec(html)?.[1]?.toLowerCase()
150
+ : undefined
151
+
152
+ const clone = (): Node => {
153
+ if (cached === undefined) {
154
+ const t = document.createElement('template')
155
+ t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
156
+ cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
157
+ }
158
+ return cached.cloneNode(true)
159
+ }
142
160
 
143
161
  return (): Node => {
144
162
  if (hydrating && hydrateNode !== null) {
145
163
  const node = hydrateNode
164
+ if (process.env.NODE_ENV !== 'production' && expectedTag !== undefined) {
165
+ const foundTag = node.nodeType === 1 ? (node as Element).tagName.toLowerCase() : undefined
166
+ if (foundTag !== expectedTag) {
167
+ const island = hydrateRoot?.getAttribute('c') ?? hydrateRoot?.tagName.toLowerCase() ?? 'unknown'
168
+ const foundDesc = foundTag !== undefined
169
+ ? `<${foundTag}>`
170
+ : node.nodeType === 3
171
+ ? `#text(${JSON.stringify((node as Text).data.slice(0, 30))})`
172
+ : node.nodeType === 8
173
+ ? `<!--${(node as Comment).data}-->`
174
+ : `nodeType(${node.nodeType})`
175
+ console.warn(`kay: hydration mismatch in island "${island}": expected <${expectedTag}>, found ${foundDesc}; falling back to fresh clone.`)
176
+ hydrating = false
177
+ hydrateNode = null
178
+ const fresh = clone()
179
+ node.parentNode?.replaceChild(fresh, node)
180
+ return fresh
181
+ }
182
+ }
146
183
  hydrateNode = node.nextSibling
147
184
  return node
148
185
  }
149
186
 
150
- if (cached === undefined) {
151
- const t = document.createElement('template')
152
- t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
153
- cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
154
- }
155
- return cached.cloneNode(true)
187
+ return clone()
156
188
  }
157
189
  }
158
190
 
@@ -174,16 +206,25 @@ export function eachStatic<T>(
174
206
  ): void {
175
207
  if (!items || items.length === 0)
176
208
  return
209
+ let startMarker: Node | null | undefined
210
+ let insertBefore = marker
211
+ if (marker !== null && marker.nodeType === 8 && (marker as Comment).data === 'k[') {
212
+ const close = skipRange(marker)
213
+ if (close !== null) {
214
+ startMarker = marker
215
+ insertBefore = close
216
+ }
217
+ }
177
218
  if (claimLoop(parent, () => {
178
219
  for (let i = 0; i < items.length; i++)
179
220
  render(items[i]!, i)
180
- }, skip)) {
221
+ }, skip, startMarker)) {
181
222
  return
182
223
  }
183
224
  const f = document.createDocumentFragment()
184
225
  for (let i = 0; i < items.length; i++)
185
226
  f.appendChild(render(items[i]!, i))
186
- parent.insertBefore(f, marker)
227
+ parent.insertBefore(f, insertBefore)
187
228
  }
188
229
 
189
230
  export function firstText(el: Node): Text {
@@ -210,21 +251,37 @@ export function skipText(marker: Node): Node | null {
210
251
  return next !== null && next.nodeType === 3 ? next.nextSibling : next
211
252
  }
212
253
 
213
- /** Advance past an SSR-bracketed dynamic range (`<!---->...<!---->`) to its closing comment marker. */
254
+ /** Advance past an SSR-bracketed dynamic range (`<!--k[-->...<!--k]-->` or `<!---->...<!---->`) to its closing comment marker. */
214
255
  export function skipRange(marker: Node): Node | null {
256
+ const balanced = marker.nodeType === 8 && (marker as Comment).data === 'k['
257
+ let depth = balanced ? 1 : 0
215
258
  let cur = marker.nextSibling
216
- while (cur !== null && cur.nodeType !== 8)
259
+ while (cur !== null) {
260
+ if (cur.nodeType === 8) {
261
+ if (!balanced)
262
+ return cur
263
+ const data = (cur as Comment).data
264
+ if (data === 'k[')
265
+ depth++
266
+ else if (data === 'k]' && --depth === 0)
267
+ return cur
268
+ }
217
269
  cur = cur.nextSibling
218
- return cur
270
+ }
271
+ return null
219
272
  }
220
273
 
221
274
  export function setText(node: Text, value: unknown): void {
275
+ if (process.env.NODE_ENV !== 'production')
276
+ assertRenderable(value, 'text')
222
277
  const str = value == null || typeof value === 'boolean' ? '' : String(value)
223
278
  if (node.data !== str)
224
279
  node.data = str
225
280
  }
226
281
 
227
282
  export function setClass(el: Element, value: unknown): void {
283
+ if (process.env.NODE_ENV !== 'production')
284
+ assertRenderable(value, 'class')
228
285
  const str = value == null || value === false ? '' : String(value)
229
286
  if (typeof el.className === 'string') {
230
287
  if (el.className !== str) {
@@ -242,32 +299,11 @@ export function setClass(el: Element, value: unknown): void {
242
299
  }
243
300
  }
244
301
 
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
-
268
302
  export function setAttr(el: Element, name: string, value: unknown): void {
269
303
  if (isBlockedAttr(name))
270
304
  return
305
+ if (process.env.NODE_ENV !== 'production')
306
+ assertRenderable(value, name)
271
307
  if (value == null) {
272
308
  el.removeAttribute(name)
273
309
  }
@@ -299,14 +335,13 @@ export function setStyle(el: HTMLElement, value: unknown): void {
299
335
  el.style.cssText = value
300
336
  }
301
337
  else if (typeof value === 'object') {
302
- for (const [k, v] of Object.entries(value as Record<string, unknown>))
303
- el.style.setProperty(k, v == null ? '' : String(v))
338
+ el.style.cssText = styleText(value as Record<string, unknown>)
304
339
  }
305
340
  }
306
341
 
307
342
  // ---- Delegated events
308
343
 
309
- const delegated = new Set<string>()
344
+ const delegated = new WeakMap<Document, Set<string>>()
310
345
 
311
346
  function dispatchEvent(event: Event): void {
312
347
  const key = `$$${event.type}`
@@ -316,7 +351,7 @@ function dispatchEvent(event: Event): void {
316
351
 
317
352
  while (node !== null) {
318
353
  const handler = node[key]
319
- if (handler !== undefined) {
354
+ if (typeof handler === 'function') {
320
355
  current = node
321
356
  batch(() => handler(event))
322
357
  if (event.cancelBubble)
@@ -329,16 +364,23 @@ function dispatchEvent(event: Event): void {
329
364
  export function delegate(events: string[]): void {
330
365
  if (typeof document === 'undefined')
331
366
  return
367
+ let set = delegated.get(document)
368
+ if (set === undefined) {
369
+ set = new Set()
370
+ delegated.set(document, set)
371
+ }
332
372
  for (let i = 0; i < events.length; i++) {
333
373
  const type = events[i]!
334
- if (!delegated.has(type)) {
335
- delegated.add(type)
374
+ if (!set.has(type)) {
375
+ set.add(type)
336
376
  document.addEventListener(type, dispatchEvent)
337
377
  }
338
378
  }
339
379
  }
340
380
 
341
- export function on(el: Node, event: string, handler: (e: Event) => void): void {
381
+ export function on(el: Node, event: string, handler: ((e: Event) => void) | false | null | undefined): void {
382
+ if (typeof handler !== 'function')
383
+ return
342
384
  el.addEventListener(event, (e) => {
343
385
  batch(() => handler(e))
344
386
  })
package/src/dom/island.ts CHANGED
@@ -5,21 +5,24 @@ import { hydrate, mount } from './index'
5
5
  declare const KAY_DEFERRED: boolean | undefined
6
6
  declare const KAY_CLIENT_ONLY: boolean | undefined
7
7
 
8
+ const REVIVERS: Record<string, (v: never) => unknown> = {
9
+ __proto__: null as never,
10
+ D: (v: string) => new Date(v),
11
+ S: (v: unknown[]) => new Set(v),
12
+ M: (v: [unknown, unknown][]) => new Map(v),
13
+ U: (v: string) => new URL(v),
14
+ R: ([src, flags]: [string, string]) => new RegExp(src, flags),
15
+ B: (v: string) => BigInt(v),
16
+ }
17
+
8
18
  export function parseIslandProps(raw: string): Record<string, unknown> {
9
19
  if (!raw.includes('"__k":'))
10
20
  return JSON.parse(raw) as Record<string, unknown>
11
21
  return JSON.parse(raw, (_k, v: unknown) => {
12
22
  if (v !== null && typeof v === 'object' && '__k' in v && 'v' in v) {
13
- const tagged = v as { __k: string, v: unknown }
14
- if (tagged.__k === 'D') return new Date(tagged.v as string)
15
- if (tagged.__k === 'S') return new Set(tagged.v as unknown[])
16
- if (tagged.__k === 'M') return new Map(tagged.v as [unknown, unknown][])
17
- if (tagged.__k === 'U') return new URL(tagged.v as string)
18
- if (tagged.__k === 'R') {
19
- const [src, flags] = tagged.v as [string, string]
20
- return new RegExp(src, flags)
21
- }
22
- if (tagged.__k === 'B') return BigInt(tagged.v as string)
23
+ const revive = REVIVERS[(v as { __k: string }).__k]
24
+ if (revive !== undefined)
25
+ return revive((v as { v: never }).v)
23
26
  }
24
27
  return v
25
28
  }) as Record<string, unknown>
@@ -27,6 +30,40 @@ export function parseIslandProps(raw: string): Record<string, unknown> {
27
30
 
28
31
  type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
29
32
 
33
+ /** Finds this island's own `<kay-slot>` without descending into nested `<kay-island>` boundaries. */
34
+ function findOwnSlot(root: Element): Element | null {
35
+ for (let child = root.firstElementChild; child !== null; child = child.nextElementSibling) {
36
+ const tag = child.tagName
37
+ if (tag === 'KAY-SLOT')
38
+ return child
39
+ if (tag === 'KAY-ISLAND')
40
+ continue
41
+ const nested = findOwnSlot(child)
42
+ if (nested !== null)
43
+ return nested
44
+ }
45
+ return null
46
+ }
47
+
48
+ function isAllowedChunkUrl(chunk: string): boolean {
49
+ if (chunk.startsWith('//'))
50
+ return false
51
+ if (chunk.startsWith('/'))
52
+ return true
53
+ if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
54
+ try {
55
+ const parsed = new URL(chunk, location.href)
56
+ return parsed.origin === location.origin
57
+ }
58
+ catch {
59
+ return false
60
+ }
61
+ }
62
+ return !/^(?:javascript|data|vbscript):/i.test(chunk)
63
+ }
64
+
65
+ let clientIslandIdSeq = 0
66
+
30
67
  export function defineIslandElement(): void {
31
68
  if (typeof customElements === 'undefined' || customElements.get('kay-island'))
32
69
  return
@@ -51,12 +88,11 @@ export function defineIslandElement(): void {
51
88
  const h = this.getAttribute('h')
52
89
  if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
53
90
  if (h === 'visible') {
54
- const target = this.firstElementChild ?? this
91
+ const first = this.firstElementChild
92
+ const target = first !== null && first.tagName !== 'SCRIPT' ? first : this
55
93
  const io = new IntersectionObserver((entries) => {
56
- if (entries.some(e => e.isIntersecting)) {
57
- this._clearStrategy()
94
+ if (entries.some(e => e.isIntersecting))
58
95
  void this._l(false, token)
59
- }
60
96
  }, { rootMargin: '200px' })
61
97
  this._c = () => io.disconnect()
62
98
  io.observe(target)
@@ -64,18 +100,13 @@ export function defineIslandElement(): void {
64
100
  }
65
101
  if (h === 'idle') {
66
102
  const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
103
+ const run = () => void this._l(false, token)
67
104
  if (g.requestIdleCallback) {
68
- const id = g.requestIdleCallback(() => {
69
- this._c = undefined
70
- void this._l(false, token)
71
- })
105
+ const id = g.requestIdleCallback(run)
72
106
  this._c = () => g.cancelIdleCallback?.(id)
73
107
  }
74
108
  else {
75
- const id = setTimeout(() => {
76
- this._c = undefined
77
- void this._l(false, token)
78
- }, 1)
109
+ const id = setTimeout(run, 1)
79
110
  this._c = () => clearTimeout(id)
80
111
  }
81
112
  return
@@ -85,11 +116,7 @@ export function defineIslandElement(): void {
85
116
  const stop = () => {
86
117
  for (const e of evs) this.removeEventListener(e, go, true)
87
118
  }
88
- const go = () => {
89
- this._c = undefined
90
- stop()
91
- void this._l(false, token)
92
- }
119
+ const go = () => void this._l(false, token)
93
120
  for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
94
121
  this._c = stop
95
122
  return
@@ -101,10 +128,8 @@ export function defineIslandElement(): void {
101
128
  }
102
129
  else {
103
130
  const go = () => {
104
- if (mq.matches) {
105
- this._clearStrategy()
131
+ if (mq.matches)
106
132
  void this._l(false, token)
107
- }
108
133
  }
109
134
  mq.addEventListener('change', go)
110
135
  this._c = () => mq.removeEventListener('change', go)
@@ -132,7 +157,7 @@ export function defineIslandElement(): void {
132
157
  async _l(clientOnly: boolean, token: number): Promise<void> {
133
158
  this._clearStrategy()
134
159
  const chunk = this.getAttribute('c')
135
- if (!chunk || token !== this._t || !this.isConnected || this._d !== undefined)
160
+ if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined)
136
161
  return
137
162
 
138
163
  let dispose: (() => void) | undefined
@@ -141,15 +166,25 @@ export function defineIslandElement(): void {
141
166
  if (!this.isConnected || token !== this._t || this._d !== undefined)
142
167
  return
143
168
 
144
- const p = this.getAttribute('p')
145
- const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
146
- const slot = this.querySelector('kay-slot')
169
+ let props: Record<string, unknown> = {}
170
+ const ps = this.lastElementChild
171
+ if (ps !== null && ps.tagName === 'SCRIPT' && ps.getAttribute('type') === 'application/json') {
172
+ props = parseIslandProps(ps.textContent || '{}')
173
+ ps.remove()
174
+ }
175
+ else {
176
+ const p = this.getAttribute('p')
177
+ if (p)
178
+ props = parseIslandProps(p)
179
+ }
180
+ const slot = findOwnSlot(this)
147
181
  if (slot !== null)
148
182
  props.children = slot
183
+ const idPrefix = this.getAttribute('i') ?? `c${clientIslandIdSeq++}-`
149
184
  const render = () => mod.default(props)
150
185
  dispose = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
151
- ? mount(this, render)
152
- : hydrate(this, render)
186
+ ? mount(this, render, idPrefix)
187
+ : hydrate(this, render, idPrefix)
153
188
  if (!this.isConnected || token !== this._t) {
154
189
  dispose()
155
190
  return
package/src/dom/loop.ts CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  import type { Owner, Signal } from '../reactivity/index'
5
5
  import { createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, signal, untrack } from '../reactivity/index'
6
- import { claimLoop } from './index'
6
+ import { claimLoop, skipRange } from './index'
7
7
 
8
8
  interface Row<T> {
9
9
  key: unknown
@@ -16,6 +16,16 @@ interface Row<T> {
16
16
  const EMPTY: readonly never[] = []
17
17
  const EMPTY_NUMS: number[] = []
18
18
 
19
+ // A new rows array holding the kept prefix and suffix of the old one, with room for the middle.
20
+ function keepEnds<T>(rows: Row<T>[], start: number, oldEnd: number, newEnd: number, nextLen: number): Row<T>[] {
21
+ const result = new Array<Row<T>>(nextLen)
22
+ for (let i = 0; i < start; i++)
23
+ result[i] = rows[i]!
24
+ for (let i = newEnd; i < nextLen; i++)
25
+ result[i] = rows[oldEnd + (i - newEnd)]!
26
+ return result
27
+ }
28
+
19
29
  export function loop<T>(
20
30
  parent: Node,
21
31
  marker: Node | null,
@@ -27,6 +37,7 @@ export function loop<T>(
27
37
  const parentOwner = getOwner()
28
38
  const needsIndex = renderRow.length >= 2
29
39
  let rows: Row<T>[] = []
40
+ let firstRun = true
30
41
  if (parentOwner !== undefined) {
31
42
  onCleanup(() => {
32
43
  rows = []
@@ -42,6 +53,18 @@ export function loop<T>(
42
53
  }
43
54
 
44
55
  effect(() => {
56
+ let startMarker: Node | null | undefined
57
+ if (firstRun) {
58
+ firstRun = false
59
+ if (marker !== null && marker.nodeType === 8 && (marker as Comment).data === 'k[') {
60
+ const close = skipRange(marker)
61
+ if (close !== null) {
62
+ startMarker = marker
63
+ marker = close
64
+ }
65
+ }
66
+ }
67
+
45
68
  const list = each()
46
69
  const next = list === false || list == null ? EMPTY : list
47
70
  const nextLen = next.length
@@ -73,7 +96,7 @@ export function loop<T>(
73
96
  const item = next[i]!
74
97
  created[i] = makeRow(item, i, keyFn(item, i))
75
98
  }
76
- }, skip)) {
99
+ }, skip, startMarker)) {
77
100
  rows = created
78
101
  return
79
102
  }
@@ -129,10 +152,7 @@ export function loop<T>(
129
152
  // Fast path 4: Pure insertion (e.g. append 1,000 rows)
130
153
  if (start === oldEnd) {
131
154
  const addCount = newEnd - start
132
- const result = new Array<Row<T>>(nextLen)
133
- for (let i = 0; i < start; i++)
134
- result[i] = rows[i]!
135
-
155
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
136
156
  const frag = document.createDocumentFragment()
137
157
  for (let i = 0; i < addCount; i++) {
138
158
  const idx = start + i
@@ -142,9 +162,6 @@ export function loop<T>(
142
162
  frag.appendChild(row.node)
143
163
  }
144
164
  parent.insertBefore(frag, after)
145
-
146
- for (let i = newEnd; i < nextLen; i++)
147
- result[i] = rows[oldEnd + (i - newEnd)]!
148
165
  rows = result
149
166
  return
150
167
  }
@@ -156,12 +173,7 @@ export function loop<T>(
156
173
  disposeOwner(row.owner)
157
174
  parent.removeChild(row.node)
158
175
  }
159
- const result = new Array<Row<T>>(nextLen)
160
- for (let i = 0; i < start; i++)
161
- result[i] = rows[i]!
162
- for (let i = newEnd; i < nextLen; i++)
163
- result[i] = rows[oldEnd + (i - newEnd)]!
164
- rows = result
176
+ rows = keepEnds(rows, start, oldEnd, newEnd, nextLen)
165
177
  return
166
178
  }
167
179
 
@@ -171,11 +183,7 @@ export function loop<T>(
171
183
  oldMap.set(rows[i]!.key, i)
172
184
 
173
185
  const midLen = newEnd - start
174
- const result = new Array<Row<T>>(nextLen)
175
- for (let i = 0; i < start; i++)
176
- result[i] = rows[i]!
177
- for (let i = newEnd; i < nextLen; i++)
178
- result[i] = rows[oldEnd + (i - newEnd)]!
186
+ const result = keepEnds(rows, start, oldEnd, newEnd, nextLen)
179
187
 
180
188
  const used = new Uint8Array(oldEnd - start)
181
189
  let reused = 0
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { createContext, Head, provideContext, Suspense, useContext, useId } from './context'
2
+ export type { Context } from './context'
1
3
  export {
2
4
  batch,
3
5
  computed,
@@ -13,8 +15,10 @@ export type { Owner, ReadonlySignal, Signal } from './reactivity/index'
13
15
  export { selector } from './reactivity/selector'
14
16
  export type { Selector } from './reactivity/selector'
15
17
  export { snapshot, store } from './reactivity/store'
16
- export { Head, Suspense } from './ssr/context'
18
+ export { useAction } from './dom/action'
19
+ export type { ActionForm, ClientAction, UseActionOptions } from './dom/action'
17
20
  export type { Component, Html, HydrateStrategy, KayChild } from './jsx-runtime'
21
+ export type { ExtractRouteParams, KayLocals, LayoutProps, LoaderData, LoaderFn, NotFoundResult, PageProps, RouteContext } from './server/index'
18
22
 
19
23
  import type { Component, HydrateStrategy } from './jsx-runtime'
20
24