@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -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/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
package/src/dom/action.ts CHANGED
@@ -1,32 +1,132 @@
1
1
  // Tiny client-side action stub (~300 B gzip, 0 B when no island imports an action).
2
2
 
3
- import type { ActionResult } from '../server/action'
3
+ import type { ReadonlySignal } from '../reactivity/index'
4
+ import type { ActionResult, ServerAction } from '../server/action'
5
+ import { signal } from '../reactivity/index'
4
6
 
5
7
  export interface ClientAction<Input, Output> {
6
- (input: Input): Promise<ActionResult<Output>>
8
+ /** A FormData input is sent as multipart, so it can carry files. */
9
+ (input: Input | FormData): Promise<ActionResult<Output>>
7
10
  readonly url: string
8
11
  toString(): string
9
12
  }
10
13
 
14
+ export interface UseActionOptions<Output> {
15
+ /** Reset the submitted `<form>` element after a successful submission (default: false). */
16
+ reset?: boolean | undefined
17
+ /** Called with the typed action `data` when the action succeeds (`res.ok === true`). */
18
+ onSuccess?: ((data: Output, form?: HTMLFormElement) => void | Promise<void>) | undefined
19
+ /** Called when the action fails (`res.ok === false`). */
20
+ onError?: ((result: Extract<ActionResult<Output>, { ok: false }>) => void) | undefined
21
+ }
22
+
23
+ export interface ActionForm<Input, Output> {
24
+ readonly pending: ReadonlySignal<boolean>
25
+ readonly error: ReadonlySignal<string>
26
+ readonly fieldErrors: ReadonlySignal<Record<string, string>>
27
+ readonly data: ReadonlySignal<Output | undefined>
28
+ /** Action URL for progressive `<form action={form.action} method="post">` (or pass the action directly). */
29
+ readonly action: string
30
+ /** Progressive `<form onSubmit={form.onSubmit}>` handler that submits `FormData` via fetch when JS is loaded. */
31
+ readonly onSubmit: (event: SubmitEvent & { currentTarget: HTMLFormElement }) => Promise<ActionResult<Output> | undefined>
32
+ /** Imperatively submit typed input or `FormData` while tracking `pending`, `error`, `fieldErrors`, and `data`. */
33
+ submit(input: Input | FormData, form?: HTMLFormElement): Promise<ActionResult<Output> | undefined>
34
+ /** Clears `error`, `fieldErrors`, and `data`. */
35
+ reset(): void
36
+ }
37
+
38
+ /** Reactive progressive-enhancement form controller for a Kay server `action()`. */
39
+ export function useAction<Input, Output>(
40
+ action: ClientAction<Input, Output> | ServerAction<Input, Output>,
41
+ options: UseActionOptions<Output> = {},
42
+ ): ActionForm<Input, Output> {
43
+ const pending = signal(false)
44
+ const error = signal('')
45
+ const fieldErrors = signal<Record<string, string>>({})
46
+ const data = signal<Output | undefined>(undefined)
47
+
48
+ const submit = async (input: Input | FormData, formEl?: HTMLFormElement): Promise<ActionResult<Output> | undefined> => {
49
+ if (pending.peek())
50
+ return undefined
51
+ pending.value = true
52
+ error.value = ''
53
+ fieldErrors.value = {}
54
+ try {
55
+ const res = await (action as ClientAction<Input, Output>)(input)
56
+ if (!res.ok) {
57
+ fieldErrors.value = res.fieldErrors ?? {}
58
+ error.value = res.error
59
+ options.onError?.(res)
60
+ return res
61
+ }
62
+ data.value = res.data
63
+ if (options.reset && formEl)
64
+ formEl.reset()
65
+ await options.onSuccess?.(res.data, formEl)
66
+ return res
67
+ }
68
+ catch (err) {
69
+ const msg = err instanceof Error ? err.message : String(err)
70
+ error.value = msg
71
+ const failed: Extract<ActionResult<Output>, { ok: false }> = { ok: false, status: 0, error: msg }
72
+ options.onError?.(failed)
73
+ return failed
74
+ }
75
+ finally {
76
+ pending.value = false
77
+ }
78
+ }
79
+
80
+ return {
81
+ pending,
82
+ error,
83
+ fieldErrors,
84
+ data,
85
+ get action() {
86
+ return action.url || String(action)
87
+ },
88
+ onSubmit(event) {
89
+ event.preventDefault()
90
+ const formEl = event.currentTarget
91
+ return submit(new FormData(formEl), formEl)
92
+ },
93
+ submit,
94
+ reset() {
95
+ error.value = ''
96
+ fieldErrors.value = {}
97
+ data.value = undefined
98
+ },
99
+ }
100
+ }
101
+
11
102
  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
- })
103
+ const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
104
+ const isForm = typeof FormData !== 'undefined' && input instanceof FormData
105
+ let res: Response
106
+ try {
107
+ res = await fetch(url, {
108
+ method: 'POST',
109
+ headers: isForm ? { accept: 'application/json' } : { 'content-type': 'application/json', 'accept': 'application/json' },
110
+ body: isForm ? input : input === undefined ? '{}' : JSON.stringify(input),
111
+ })
112
+ }
113
+ catch (error) {
114
+ return { ok: false, status: 0, error: error instanceof Error ? error.message : String(error) }
115
+ }
21
116
 
117
+ // 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
118
  if (res.redirected) {
23
119
  if (typeof location !== 'undefined')
24
120
  location.assign(res.url)
25
- return { ok: true, data: undefined as Output }
121
+ return new Promise<never>(() => {})
26
122
  }
27
123
 
28
- const body = await res.json().catch(() => ({ ok: false, status: res.status, error: res.statusText }))
29
- return body as ActionResult<Output>
124
+ try {
125
+ return await res.json() as ActionResult<Output>
126
+ }
127
+ catch {
128
+ return { ok: false, status: res.status, error: res.statusText }
129
+ }
30
130
  }) as unknown as ClientAction<Input, Output>
31
131
 
32
132
  Object.defineProperties(call, {
package/src/dom/extras.ts CHANGED
@@ -2,8 +2,10 @@
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 { createOwner, disposeOwner, effect, getOwner, runWithOwner, untrack } from '../reactivity/index'
6
- import { claimInsert, setAttr, setClass, setProp, setStyle, skipRange } from './index'
5
+ import { DOM_PROPS } from '../attrs'
6
+ import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, untrack } from '../reactivity/index'
7
+ import { assertRenderable } from '../unrenderable'
8
+ import { claimInsert, isBlockedAttr, setAttr, setClass, setProp, setStyle, skipRange } from './index'
7
9
 
8
10
  const RAW_HTML = Symbol.for('kay.html')
9
11
 
@@ -12,23 +14,37 @@ function isRawHtml(value: unknown): value is { __html: string } {
12
14
  }
13
15
 
14
16
  export function setInnerHtml(el: Element, value: unknown): void {
15
- const html = value == null || value === false
16
- ? ''
17
- : isRawHtml(value)
18
- ? String(value.__html)
19
- : 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)
20
26
  if (el.innerHTML !== html)
21
27
  el.innerHTML = html
22
28
  }
23
29
 
24
- const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
25
- const SPREAD_DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
30
+ const EVENT_PROP = /^on([A-Z]\w*)$/
26
31
 
27
- function isBlockedSpreadAttr(name: string): boolean {
28
- if (!VALID_ATTR_NAME.test(name))
29
- return true
30
- const lower = name.toLowerCase()
31
- return lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc'
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
32
48
  }
33
49
 
34
50
  export function omit(props: Record<string, unknown>, excluded: string[]): Record<string, unknown> {
@@ -46,8 +62,23 @@ export function omit(props: Record<string, unknown>, excluded: string[]): Record
46
62
 
47
63
  export function spread(el: Element, getProps: () => Record<string, unknown> | null | undefined): void {
48
64
  let prevKeys: string[] = []
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))
72
+ }
73
+
74
+ onCleanup(() => {
75
+ for (const type of handlers.keys())
76
+ el.removeEventListener(type, listen)
77
+ handlers.clear()
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
 
@@ -63,8 +94,11 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
63
94
  }
64
95
  else if (k !== 'key' && k !== 'ref' && k !== '$hydrate' && k !== 'children') {
65
96
  const name = k === 'htmlFor' ? 'for' : k
66
- if (!isBlockedSpreadAttr(name))
97
+ if (!isBlockedAttr(name)) {
98
+ if (DOM_PROPS.has(name))
99
+ setProp(el, name, name === 'value' ? '' : false)
67
100
  el.removeAttribute(name)
101
+ }
68
102
  }
69
103
  }
70
104
 
@@ -72,25 +106,43 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
72
106
  const k = nextKeys[i]!
73
107
  if (k === 'key' || k === '$hydrate' || k === 'children')
74
108
  continue
109
+ if (k === 'dangerouslySetInnerHTML')
110
+ throw new TypeError('kay: dangerouslySetInnerHTML in a spread: write innerHTML={html} on the element.')
75
111
  const v = props[k]
76
112
  if (k === 'ref') {
77
- if (typeof v === 'function')
78
- (v as (node: Element) => void)(el)
113
+ if (typeof v === 'function' && v !== lastRef) {
114
+ lastRef = v
115
+ ;(v as (node: Element) => void)(el)
116
+ }
117
+ continue
118
+ }
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)
79
125
  continue
80
126
  }
81
127
  const name = k === 'className' ? 'class' : k === 'htmlFor' ? 'for' : k
82
- if (isBlockedSpreadAttr(name))
128
+ if (isBlockedAttr(name))
83
129
  continue
84
130
  if (name === 'class')
85
131
  setClass(el, v)
86
132
  else if (name === 'style')
87
133
  setStyle(el as HTMLElement, v)
88
- else if (SPREAD_DOM_PROPS.has(name))
134
+ else if (DOM_PROPS.has(name))
89
135
  setProp(el, name, v)
90
136
  else
91
137
  setAttr(el, name, v)
92
138
  }
93
139
 
140
+ for (const type of handlers.keys()) {
141
+ if (!types.has(type)) {
142
+ handlers.delete(type)
143
+ el.removeEventListener(type, listen)
144
+ }
145
+ }
94
146
  prevKeys = nextKeys
95
147
  })
96
148
  }
@@ -107,6 +159,28 @@ function clearInserted(current: Node | Node[] | null): void {
107
159
  }
108
160
  }
109
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
+
110
184
  function claimTextNode(claimed: Node | null, str: string): Text | undefined {
111
185
  if (claimed === null || claimed.nodeType !== 3)
112
186
  return undefined
@@ -170,12 +244,8 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
170
244
  const claimed = claimTextNode(res.claimed, str)
171
245
  if (claimed !== undefined) {
172
246
  textNode = claimed
173
- if (ssrNodes !== undefined && ssrNodes.length > 1) {
174
- for (let i = 0; i < ssrNodes.length; i++) {
175
- if (ssrNodes[i] !== claimed)
176
- ssrNodes[i]!.parentNode?.removeChild(ssrNodes[i]!)
177
- }
178
- }
247
+ if (ssrNodes !== undefined)
248
+ clearInserted(ssrNodes.filter(n => n !== claimed))
179
249
  }
180
250
  else {
181
251
  if (ssrNodes !== undefined)
@@ -190,6 +260,12 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
190
260
  return
191
261
  }
192
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
+
193
269
  if (textNode !== undefined) {
194
270
  textNode.remove()
195
271
  textNode = undefined
@@ -199,12 +275,8 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
199
275
  if (current === next)
200
276
  return
201
277
  if (current === null && next.parentNode === parent) {
202
- if (ssrNodes !== undefined && ssrNodes.length > 1) {
203
- for (let i = 0; i < ssrNodes.length; i++) {
204
- if (ssrNodes[i] !== next)
205
- ssrNodes[i]!.parentNode?.removeChild(ssrNodes[i]!)
206
- }
207
- }
278
+ if (ssrNodes !== undefined)
279
+ clearInserted(ssrNodes.filter(n => n !== next))
208
280
  current = next
209
281
  return
210
282
  }
@@ -226,36 +298,10 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
226
298
  if (Array.isArray(next)) {
227
299
  clearInserted(current)
228
300
  if (ssrNodes !== undefined) {
229
- const kept = new Set<Node>()
230
- for (let i = 0; i < next.length; i++) {
231
- const item = next[i]
232
- if (item instanceof Node && item.parentNode === parent)
233
- kept.add(item)
234
- }
235
- for (let i = 0; i < ssrNodes.length; i++) {
236
- if (!kept.has(ssrNodes[i]!))
237
- ssrNodes[i]!.parentNode?.removeChild(ssrNodes[i]!)
238
- }
301
+ const kept = new Set(next)
302
+ clearInserted(ssrNodes.filter(n => !kept.has(n)))
239
303
  }
240
- const f = document.createDocumentFragment()
241
- const nodes: Node[] = []
242
- for (let i = 0; i < next.length; i++) {
243
- const item = next[i]
244
- if (item instanceof Node) {
245
- if (item.nodeType === 11)
246
- nodes.push(...Array.from(item.childNodes))
247
- else
248
- nodes.push(item)
249
- f.appendChild(item)
250
- }
251
- else if (item != null && typeof item !== 'boolean') {
252
- const t = document.createTextNode(String(item))
253
- nodes.push(t)
254
- f.appendChild(t)
255
- }
256
- }
257
- parent.insertBefore(f, marker)
258
- current = nodes
304
+ current = insertAll(parent, marker, next)
259
305
  }
260
306
  })
261
307
  }
@@ -271,6 +317,7 @@ export function show(
271
317
  let branch: 0 | 1 | 2 = 0
272
318
  let owner: Owner | undefined
273
319
  let nodes: Node[] = []
320
+ let firstRun = true
274
321
 
275
322
  const clear = () => {
276
323
  if (owner !== undefined) {
@@ -288,6 +335,18 @@ export function show(
288
335
  if (branch === nextBranch)
289
336
  return
290
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
+
291
350
  clear()
292
351
  branch = nextBranch
293
352
 
@@ -296,7 +355,7 @@ export function show(
296
355
  return
297
356
 
298
357
  owner = createOwner(parentOwner)
299
- const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
358
+ const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)), startMarker)
300
359
  marker = res.marker
301
360
  const rendered = res.result
302
361
  if (rendered == null || typeof rendered === 'boolean') {
@@ -329,28 +388,7 @@ export function show(
329
388
  }
330
389
 
331
390
  if (Array.isArray(rendered)) {
332
- const f = document.createDocumentFragment()
333
- const list: Node[] = []
334
- for (let i = 0; i < rendered.length; i++) {
335
- const item = rendered[i]
336
- if (item instanceof Node) {
337
- if (item.nodeType === 11)
338
- list.push(...Array.from(item.childNodes))
339
- else
340
- list.push(item)
341
- f.appendChild(item)
342
- }
343
- else if (item != null && typeof item !== 'boolean') {
344
- const str = String(item)
345
- if (str !== '') {
346
- const t = document.createTextNode(str)
347
- list.push(t)
348
- f.appendChild(t)
349
- }
350
- }
351
- }
352
- parent.insertBefore(f, marker)
353
- nodes = list
391
+ nodes = insertAll(parent, marker, rendered)
354
392
  }
355
393
  })
356
394
  }