@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
package/src/dom/action.ts CHANGED
@@ -3,30 +3,40 @@
3
3
  import type { ActionResult } from '../server/action'
4
4
 
5
5
  export interface ClientAction<Input, Output> {
6
- (input: Input): Promise<ActionResult<Output>>
6
+ /** A FormData input is sent as multipart, so it can carry files. */
7
+ (input: Input | FormData): Promise<ActionResult<Output>>
7
8
  readonly url: string
8
9
  toString(): string
9
10
  }
10
11
 
11
12
  export function actionStub<Input = unknown, Output = unknown>(url: string): ClientAction<Input, Output> {
12
- const call = (async (input: Input): Promise<ActionResult<Output>> => {
13
- const res = await fetch(url, {
14
- method: 'POST',
15
- headers: {
16
- 'content-type': 'application/json',
17
- 'accept': 'application/json',
18
- },
19
- body: input === undefined ? '{}' : JSON.stringify(input),
20
- })
13
+ const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
14
+ const isForm = typeof FormData !== 'undefined' && input instanceof FormData
15
+ let res: Response
16
+ try {
17
+ res = await fetch(url, {
18
+ method: 'POST',
19
+ headers: isForm ? { accept: 'application/json' } : { 'content-type': 'application/json', 'accept': 'application/json' },
20
+ body: isForm ? input : input === undefined ? '{}' : JSON.stringify(input),
21
+ })
22
+ }
23
+ catch (error) {
24
+ return { ok: false, status: 0, error: error instanceof Error ? error.message : String(error) }
25
+ }
21
26
 
27
+ // The action answered with a redirect: the page navigates there and the call never settles, so no caller acts on data it did not get.
22
28
  if (res.redirected) {
23
29
  if (typeof location !== 'undefined')
24
30
  location.assign(res.url)
25
- return { ok: true, data: undefined as Output }
31
+ return new Promise<never>(() => {})
26
32
  }
27
33
 
28
- const body = await res.json().catch(() => ({ ok: false, status: res.status, error: res.statusText }))
29
- return body as ActionResult<Output>
34
+ try {
35
+ return await res.json() as ActionResult<Output>
36
+ }
37
+ catch {
38
+ return { ok: false, status: res.status, error: res.statusText }
39
+ }
30
40
  }) as unknown as ClientAction<Input, Output>
31
41
 
32
42
  Object.defineProperties(call, {
package/src/dom/extras.ts CHANGED
@@ -2,19 +2,50 @@
2
2
  // so Bun.build({ splitting: true }) keeps them out of minimal islands that don't use them.
3
3
 
4
4
  import type { Owner } from '../reactivity/index'
5
+ import { DOM_PROPS } from '../attrs'
5
6
  import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, untrack } from '../reactivity/index'
6
- import { claimInsert, setAttr, setClass, setProp, setStyle } from './index'
7
+ import { assertRenderable } from '../unrenderable'
8
+ import { claimInsert, isBlockedAttr, setAttr, setClass, setProp, setStyle, skipRange } from './index'
9
+
10
+ const RAW_HTML = Symbol.for('kay.html')
11
+
12
+ function isRawHtml(value: unknown): value is { __html: string } {
13
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[RAW_HTML] === true && '__html' in value
14
+ }
7
15
 
8
16
  export function setInnerHtml(el: Element, value: unknown): void {
9
- const html = value == null || value === false
10
- ? ''
11
- : (typeof value === 'object' && '__html' in value ? String((value as { __html: string }).__html) : String(value))
17
+ let html: string
18
+ if (value == null || value === false)
19
+ html = ''
20
+ else if (isRawHtml(value))
21
+ html = String(value.__html)
22
+ else if (typeof value === 'object' && '__html' in value)
23
+ throw new TypeError('kay: innerHTML takes the HTML string, got a { __html } object; pass the string, or raw(html) for a value typed Html.')
24
+ else
25
+ html = String(value)
12
26
  if (el.innerHTML !== html)
13
27
  el.innerHTML = html
14
28
  }
15
29
 
16
- const SPREAD_EVENT_RE = /^on([A-Z]\w*)$/
17
- const SPREAD_DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
30
+ const EVENT_PROP = /^on([A-Z]\w*)$/
31
+
32
+ /** Merges prop objects while preserving getter descriptors so reactive props stay lazy across component spreads. */
33
+ export function mergeProps(...sources: (Record<string, unknown> | null | undefined)[]): Record<string, unknown> {
34
+ const out: Record<string, unknown> = {}
35
+ for (let i = 0; i < sources.length; i++) {
36
+ const src = sources[i]
37
+ if (src == null || typeof src !== 'object')
38
+ continue
39
+ const keys = Object.keys(src)
40
+ for (let j = 0; j < keys.length; j++) {
41
+ const key = keys[j]!
42
+ const desc = Object.getOwnPropertyDescriptor(src, key)
43
+ if (desc !== undefined)
44
+ Object.defineProperty(out, key, desc)
45
+ }
46
+ }
47
+ return out
48
+ }
18
49
 
19
50
  export function omit(props: Record<string, unknown>, excluded: string[]): Record<string, unknown> {
20
51
  const out: Record<string, unknown> = {}
@@ -31,23 +62,23 @@ export function omit(props: Record<string, unknown>, excluded: string[]): Record
31
62
 
32
63
  export function spread(el: Element, getProps: () => Record<string, unknown> | null | undefined): void {
33
64
  let prevKeys: string[] = []
34
- const listeners = new Map<string, (e: Event) => void>()
35
-
36
- const removeListener = (ev: string) => {
37
- const fn = listeners.get(ev)
38
- if (fn !== undefined) {
39
- el.removeEventListener(ev, fn)
40
- listeners.delete(ev)
41
- }
65
+ let lastRef: unknown
66
+ // One listener per event type, calling whichever handler the props hold now.
67
+ const handlers = new Map<string, (e: Event) => void>()
68
+ const listen = (e: Event): void => {
69
+ const handler = handlers.get(e.type)
70
+ if (handler !== undefined)
71
+ batch(() => handler(e))
42
72
  }
43
73
 
44
74
  onCleanup(() => {
45
- for (const [ev, fn] of listeners)
46
- el.removeEventListener(ev, fn)
47
- listeners.clear()
75
+ for (const type of handlers.keys())
76
+ el.removeEventListener(type, listen)
77
+ handlers.clear()
48
78
  })
49
79
 
50
80
  effect(() => {
81
+ const types = new Set<string>()
51
82
  const props = getProps() ?? {}
52
83
  const nextKeys = Object.keys(props)
53
84
 
@@ -55,18 +86,19 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
55
86
  const k = prevKeys[i]!
56
87
  if (k in props)
57
88
  continue
58
- const ev = SPREAD_EVENT_RE.exec(k)
59
- if (ev !== null) {
60
- removeListener(ev[1]!.toLowerCase())
61
- }
62
- else if (k === 'class' || k === 'className') {
89
+ if (k === 'class' || k === 'className') {
63
90
  setClass(el, '')
64
91
  }
65
92
  else if (k === 'style') {
66
93
  setStyle(el as HTMLElement, null)
67
94
  }
68
95
  else if (k !== 'key' && k !== 'ref' && k !== '$hydrate' && k !== 'children') {
69
- el.removeAttribute(k === 'htmlFor' ? 'for' : k)
96
+ const name = k === 'htmlFor' ? 'for' : k
97
+ if (!isBlockedAttr(name)) {
98
+ if (DOM_PROPS.has(name))
99
+ setProp(el, name, name === 'value' ? '' : false)
100
+ el.removeAttribute(name)
101
+ }
70
102
  }
71
103
  }
72
104
 
@@ -74,36 +106,43 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
74
106
  const k = nextKeys[i]!
75
107
  if (k === 'key' || k === '$hydrate' || k === 'children')
76
108
  continue
109
+ if (k === 'dangerouslySetInnerHTML')
110
+ throw new TypeError('kay: dangerouslySetInnerHTML in a spread: write innerHTML={html} on the element.')
77
111
  const v = props[k]
78
112
  if (k === 'ref') {
79
- if (typeof v === 'function')
80
- (v as (node: Element) => void)(el)
113
+ if (typeof v === 'function' && v !== lastRef) {
114
+ lastRef = v
115
+ ;(v as (node: Element) => void)(el)
116
+ }
81
117
  continue
82
118
  }
83
- const ev = SPREAD_EVENT_RE.exec(k)
84
- if (ev !== null) {
85
- const type = ev[1]!.toLowerCase()
86
- removeListener(type)
87
- if (typeof v === 'function') {
88
- const wrapped = (e: Event) => batch(() => (v as (ev: Event) => void)(e))
89
- listeners.set(type, wrapped)
90
- el.addEventListener(type, wrapped)
91
- }
119
+ const event = typeof v === 'function' ? EVENT_PROP.exec(k) : null
120
+ if (event !== null) {
121
+ const type = event[1]!.toLowerCase()
122
+ types.add(type)
123
+ el.addEventListener(type, listen)
124
+ handlers.set(type, v as (e: Event) => void)
92
125
  continue
93
126
  }
94
127
  const name = k === 'className' ? 'class' : k === 'htmlFor' ? 'for' : k
95
- if (name === 'innerHTML')
96
- setInnerHtml(el, v)
97
- else if (name === 'class')
128
+ if (isBlockedAttr(name))
129
+ continue
130
+ if (name === 'class')
98
131
  setClass(el, v)
99
132
  else if (name === 'style')
100
133
  setStyle(el as HTMLElement, v)
101
- else if (SPREAD_DOM_PROPS.has(name))
134
+ else if (DOM_PROPS.has(name))
102
135
  setProp(el, name, v)
103
136
  else
104
137
  setAttr(el, name, v)
105
138
  }
106
139
 
140
+ for (const type of handlers.keys()) {
141
+ if (!types.has(type)) {
142
+ handlers.delete(type)
143
+ el.removeEventListener(type, listen)
144
+ }
145
+ }
107
146
  prevKeys = nextKeys
108
147
  })
109
148
  }
@@ -120,6 +159,28 @@ function clearInserted(current: Node | Node[] | null): void {
120
159
  }
121
160
  }
122
161
 
162
+ // Inserts the nodes and texts of a rendered array before the marker; a fragment contributes its children.
163
+ function insertAll(parent: Node, marker: Node | null, items: unknown[]): Node[] {
164
+ const f = document.createDocumentFragment()
165
+ const nodes: Node[] = []
166
+ for (const item of items) {
167
+ if (item instanceof Node) {
168
+ if (item.nodeType === 11)
169
+ nodes.push(...Array.from(item.childNodes))
170
+ else
171
+ nodes.push(item)
172
+ f.appendChild(item)
173
+ }
174
+ else if (item != null && typeof item !== 'boolean' && item !== '') {
175
+ const t = document.createTextNode(String(item))
176
+ nodes.push(t)
177
+ f.appendChild(t)
178
+ }
179
+ }
180
+ parent.insertBefore(f, marker)
181
+ return nodes
182
+ }
183
+
123
184
  function claimTextNode(claimed: Node | null, str: string): Text | undefined {
124
185
  if (claimed === null || claimed.nodeType !== 3)
125
186
  return undefined
@@ -131,22 +192,42 @@ function claimTextNode(claimed: Node | null, str: string): Text | undefined {
131
192
  return undefined
132
193
  }
133
194
 
134
- export function insert(parent: Node, value: () => unknown, marker: Node | null = null): void {
195
+ export function insert(parent: Node, value: () => unknown, marker: Node | null = null, startMarker?: Node | null): void {
135
196
  let current: Node | Node[] | null = null
136
197
  let textNode: Text | undefined
198
+ let firstRun = true
137
199
 
138
200
  effect(() => {
139
- const res = claimInsert(parent, marker, value)
140
- marker = res.marker
201
+ let res: { result: unknown, marker: Node | null, claimed: Node | null, nodes: Node[] | undefined }
202
+ if (firstRun) {
203
+ firstRun = false
204
+ let effMarker = marker
205
+ let effStart = startMarker
206
+ if (effStart === undefined && effMarker !== null && effMarker.nodeType === 8) {
207
+ const close = skipRange(effMarker)
208
+ if (close !== null) {
209
+ effStart = effMarker
210
+ effMarker = close
211
+ }
212
+ }
213
+ res = claimInsert(parent, effMarker, value, effStart)
214
+ marker = res.marker
215
+ }
216
+ else {
217
+ res = { result: value(), marker, claimed: null, nodes: undefined }
218
+ }
141
219
  const next = res.result
220
+ const ssrNodes = res.nodes
142
221
 
143
- if (next == null && res.nodes !== undefined) {
144
- current = res.nodes
222
+ if (next == null && ssrNodes !== undefined) {
223
+ current = ssrNodes
145
224
  return
146
225
  }
147
226
 
148
227
  if (next == null || typeof next === 'boolean') {
149
228
  clearInserted(current)
229
+ if (ssrNodes !== undefined)
230
+ clearInserted(ssrNodes)
150
231
  current = null
151
232
  if (textNode !== undefined)
152
233
  textNode.data = ''
@@ -163,8 +244,12 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
163
244
  const claimed = claimTextNode(res.claimed, str)
164
245
  if (claimed !== undefined) {
165
246
  textNode = claimed
247
+ if (ssrNodes !== undefined)
248
+ clearInserted(ssrNodes.filter(n => n !== claimed))
166
249
  }
167
250
  else {
251
+ if (ssrNodes !== undefined)
252
+ clearInserted(ssrNodes)
168
253
  textNode = document.createTextNode(str)
169
254
  parent.insertBefore(textNode, marker)
170
255
  }
@@ -175,6 +260,12 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
175
260
  return
176
261
  }
177
262
 
263
+ if (process.env.NODE_ENV !== 'production') {
264
+ if (isRawHtml(next))
265
+ throw new TypeError('kay: raw() HTML cannot be a dynamic child in the browser; set it with innerHTML={html} on an element.')
266
+ assertRenderable(next, 'text')
267
+ }
268
+
178
269
  if (textNode !== undefined) {
179
270
  textNode.remove()
180
271
  textNode = undefined
@@ -184,10 +275,14 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
184
275
  if (current === next)
185
276
  return
186
277
  if (current === null && next.parentNode === parent) {
278
+ if (ssrNodes !== undefined)
279
+ clearInserted(ssrNodes.filter(n => n !== next))
187
280
  current = next
188
281
  return
189
282
  }
190
283
  clearInserted(current)
284
+ if (ssrNodes !== undefined)
285
+ clearInserted(ssrNodes)
191
286
  if (next.nodeType === 11) {
192
287
  const nodes = Array.from(next.childNodes)
193
288
  parent.insertBefore(next, marker)
@@ -202,25 +297,11 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
202
297
 
203
298
  if (Array.isArray(next)) {
204
299
  clearInserted(current)
205
- const f = document.createDocumentFragment()
206
- const nodes: Node[] = []
207
- for (let i = 0; i < next.length; i++) {
208
- const item = next[i]
209
- if (item instanceof Node) {
210
- if (item.nodeType === 11)
211
- nodes.push(...Array.from(item.childNodes))
212
- else
213
- nodes.push(item)
214
- f.appendChild(item)
215
- }
216
- else if (item != null && typeof item !== 'boolean') {
217
- const t = document.createTextNode(String(item))
218
- nodes.push(t)
219
- f.appendChild(t)
220
- }
300
+ if (ssrNodes !== undefined) {
301
+ const kept = new Set(next)
302
+ clearInserted(ssrNodes.filter(n => !kept.has(n)))
221
303
  }
222
- parent.insertBefore(f, marker)
223
- current = nodes
304
+ current = insertAll(parent, marker, next)
224
305
  }
225
306
  })
226
307
  }
@@ -236,6 +317,7 @@ export function show(
236
317
  let branch: 0 | 1 | 2 = 0
237
318
  let owner: Owner | undefined
238
319
  let nodes: Node[] = []
320
+ let firstRun = true
239
321
 
240
322
  const clear = () => {
241
323
  if (owner !== undefined) {
@@ -253,6 +335,18 @@ export function show(
253
335
  if (branch === nextBranch)
254
336
  return
255
337
 
338
+ let startMarker: Node | null | undefined
339
+ if (firstRun) {
340
+ firstRun = false
341
+ if (marker !== null && marker.nodeType === 8 && (marker as Comment).data === 'k[') {
342
+ const close = skipRange(marker)
343
+ if (close !== null) {
344
+ startMarker = marker
345
+ marker = close
346
+ }
347
+ }
348
+ }
349
+
256
350
  clear()
257
351
  branch = nextBranch
258
352
 
@@ -261,7 +355,7 @@ export function show(
261
355
  return
262
356
 
263
357
  owner = createOwner(parentOwner)
264
- const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
358
+ const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)), startMarker)
265
359
  marker = res.marker
266
360
  const rendered = res.result
267
361
  if (rendered == null || typeof rendered === 'boolean') {
@@ -294,28 +388,7 @@ export function show(
294
388
  }
295
389
 
296
390
  if (Array.isArray(rendered)) {
297
- const f = document.createDocumentFragment()
298
- const list: Node[] = []
299
- for (let i = 0; i < rendered.length; i++) {
300
- const item = rendered[i]
301
- if (item instanceof Node) {
302
- if (item.nodeType === 11)
303
- list.push(...Array.from(item.childNodes))
304
- else
305
- list.push(item)
306
- f.appendChild(item)
307
- }
308
- else if (item != null && typeof item !== 'boolean') {
309
- const str = String(item)
310
- if (str !== '') {
311
- const t = document.createTextNode(str)
312
- list.push(t)
313
- f.appendChild(t)
314
- }
315
- }
316
- }
317
- parent.insertBefore(f, marker)
318
- nodes = list
391
+ nodes = insertAll(parent, marker, rendered)
319
392
  }
320
393
  })
321
394
  }