@kayjs/kay 2.0.0-beta.0 → 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 +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  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 +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  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 +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  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 +114 -18
  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 +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -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 +2 -1
  55. package/src/unrenderable.ts +35 -0
@@ -1,7 +1,7 @@
1
1
  // O(1) row selection primitive: zero WeakSet overhead per row.
2
2
 
3
3
  import type { Owner, Signal } from './index'
4
- import { effect, getOwner, onCleanup, signal } from './index'
4
+ import { effect, getOwner, isTracking, onCleanup, signal } from './index'
5
5
 
6
6
  export interface Selector<K> {
7
7
  is(key: K): boolean
@@ -9,8 +9,7 @@ export interface Selector<K> {
9
9
 
10
10
  interface Entry {
11
11
  s: Signal<boolean>
12
- o: Owner | undefined
13
- r: number
12
+ owners: Set<Owner>
14
13
  }
15
14
 
16
15
  export function selector<K>(source: () => K): Selector<K> {
@@ -34,19 +33,22 @@ export function selector<K>(source: () => K): Selector<K> {
34
33
 
35
34
  return {
36
35
  is(key: K): boolean {
36
+ const owner = getOwner()
37
+ if (owner === undefined && !isTracking())
38
+ return Object.is(current, key)
39
+
37
40
  let entry = subs.get(key)
38
41
  if (entry === undefined) {
39
- entry = { s: signal(Object.is(current, key)), o: undefined, r: 0 }
42
+ entry = { s: signal(Object.is(current, key)), owners: new Set() }
40
43
  subs.set(key, entry)
41
44
  }
42
45
 
43
- const owner = getOwner()
44
- if (owner !== undefined && entry.o !== owner) {
45
- entry.o = owner
46
- entry.r++
46
+ if (owner !== undefined && !entry.owners.has(owner)) {
47
+ entry.owners.add(owner)
47
48
  const target = entry
48
49
  onCleanup(() => {
49
- if (--target.r === 0)
50
+ target.owners.delete(owner)
51
+ if (target.owners.size === 0)
50
52
  subs.delete(key)
51
53
  })
52
54
  }
@@ -1,11 +1,21 @@
1
1
  // Deep reactive proxy store (tree-shakable: 0 B if unused).
2
2
 
3
3
  import type { Signal } from './index'
4
- import { signal, untrack } from './index'
4
+ import { batch, isTracking, signal, untrack } from './index'
5
5
 
6
6
  const RAW = Symbol('kay.store.raw')
7
7
  const OWN_KEYS = Symbol('kay.store.keys')
8
8
 
9
+ // An array method that moves several entries writes each one in turn; batched, its readers see only the finished array.
10
+ const batchedMutators = new Map<PropertyKey, (this: unknown[], ...args: unknown[]) => unknown>(
11
+ (['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'] as const).map((name) => {
12
+ const method = Array.prototype[name] as (...args: unknown[]) => unknown
13
+ return [name, function (this: unknown[], ...args: unknown[]) {
14
+ return batch(() => method.apply(this, args))
15
+ }]
16
+ }),
17
+ )
18
+
9
19
  const proxyCache = new WeakMap<object, object>()
10
20
  const depsCache = new WeakMap<object, Map<PropertyKey, Signal<number>>>()
11
21
 
@@ -18,6 +28,11 @@ function isPlain(value: unknown): value is Record<PropertyKey, unknown> {
18
28
  return proto === Object.prototype || proto === null
19
29
  }
20
30
 
31
+ // The target behind a store proxy, or the value itself.
32
+ function unwrap<T>(value: T): T {
33
+ return typeof value === 'object' && value !== null && RAW in value ? (value as Record<symbol, T>)[RAW]! : value
34
+ }
35
+
21
36
  function getDep(target: object, key: PropertyKey): Signal<number> {
22
37
  let map = depsCache.get(target)
23
38
  if (map === undefined) {
@@ -47,16 +62,22 @@ function wrap<T extends object>(target: T): T {
47
62
  get(obj, key, receiver) {
48
63
  if (key === RAW)
49
64
  return obj
50
- getDep(obj, key).value
65
+ const mutator = Array.isArray(obj) ? batchedMutators.get(key) : undefined
66
+ if (mutator !== undefined)
67
+ return mutator
68
+ if (isTracking()) {
69
+ getDep(obj, key).value
70
+ // A reader of an array's length is walking it (a list loop reads entries untracked), so any entry write reaches it.
71
+ if (key === 'length' && Array.isArray(obj))
72
+ getDep(obj, OWN_KEYS).value
73
+ }
51
74
  const value = Reflect.get(obj, key, receiver)
52
75
  return isPlain(value) ? wrap(value) : value
53
76
  },
54
77
  set(obj, key, value, receiver) {
55
- const rawValue = typeof value === 'object' && value !== null && RAW in value
56
- ? (value as Record<symbol, unknown>)[RAW]
57
- : value
78
+ const rawValue = unwrap(value)
58
79
  const had = Object.prototype.hasOwnProperty.call(obj, key)
59
- const prev = Reflect.get(obj, key, receiver)
80
+ const prev = Reflect.get(obj, key, obj)
60
81
  const prevLength = Array.isArray(obj) ? obj.length : 0
61
82
  const ok = Reflect.set(obj, key, rawValue, receiver)
62
83
  if (!had || !Object.is(prev, rawValue)) {
@@ -79,11 +100,15 @@ function wrap<T extends object>(target: T): T {
79
100
  return ok
80
101
  },
81
102
  has(obj, key) {
82
- getDep(obj, key).value
103
+ if (key === RAW)
104
+ return true
105
+ if (isTracking())
106
+ getDep(obj, key).value
83
107
  return Reflect.has(obj, key)
84
108
  },
85
109
  ownKeys(obj) {
86
- getDep(obj, OWN_KEYS).value
110
+ if (isTracking())
111
+ getDep(obj, OWN_KEYS).value
87
112
  return Reflect.ownKeys(obj)
88
113
  },
89
114
  })
@@ -103,9 +128,9 @@ export function snapshot<T>(value: T): T {
103
128
  }
104
129
 
105
130
  function cloneRaw<T>(value: T): T {
106
- if (typeof value !== 'object' || value === null)
107
- return value
108
- const raw = RAW in value ? (value as Record<symbol, unknown>)[RAW] : value
131
+ const raw = unwrap(value)
132
+ if (typeof raw !== 'object' || raw === null)
133
+ return raw
109
134
  if (Array.isArray(raw))
110
135
  return raw.map(item => cloneRaw(item)) as unknown as T
111
136
  if (isPlain(raw)) {
@@ -1,9 +1,10 @@
1
1
  // Unified server actions: works as both progressive <form action={fn} method="post"> and typed island RPC.
2
2
 
3
3
  import type { Cookies } from './cookies'
4
- import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
5
- import { DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit } from './http'
6
- import { isTrustedOrigin, verifyOrigin } from './security'
4
+ import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
5
+ import type { TrustProxy } from './security'
6
+ import { wantsJson } from './http'
7
+ import { isTrustedOrigin } from './security'
7
8
  import { validateSchema } from './standard-schema'
8
9
 
9
10
  export const ACTION_ERROR_COOKIE = '__kay_action_err'
@@ -31,7 +32,6 @@ export function getActionError(locals?: Record<string, unknown>): ActionErrorFla
31
32
  export interface ActionContext {
32
33
  request: Request
33
34
  url: URL
34
- params: Record<string, string>
35
35
  cookies: Cookies
36
36
  locals: Record<string, unknown>
37
37
  ip?: string | undefined
@@ -104,40 +104,92 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
104
104
  return typeof value === 'function' && (value as { __kayAction?: boolean }).__kayAction === true
105
105
  }
106
106
 
107
- class PayloadTooLargeError extends Error {
108
- constructor() {
109
- super('Payload Too Large')
110
- }
111
- }
112
-
113
- async function parseActionBody(request: Request, maxRequestBodySize: number): Promise<unknown> {
114
- const checked = await enforceRequestBodyLimit(request, maxRequestBodySize)
115
- if (!checked.ok)
116
- throw new PayloadTooLargeError()
117
- const boundedReq = checked.request
118
-
107
+ async function parseActionBody(boundedReq: Request): Promise<unknown> {
119
108
  const contentType = boundedReq.headers.get('content-type') ?? ''
120
109
  if (contentType.includes('application/json'))
121
110
  return boundedReq.json()
122
111
 
123
112
  if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded')) {
124
- const fd = await boundedReq.formData()
125
- const out: Record<string, unknown> = {}
126
- for (const [key, val] of fd.entries()) {
127
- if (key in out) {
128
- const prev = out[key]
129
- out[key] = Array.isArray(prev) ? [...prev, val] : [prev, val]
113
+ // A Map then fromEntries makes every name an own property, `constructor` and `__proto__` included.
114
+ const fields = new Map<string, FormDataEntryValue | FormDataEntryValue[]>()
115
+ for (const [key, val] of (await boundedReq.formData()).entries()) {
116
+ const prev = fields.get(key)
117
+ if (prev === undefined) {
118
+ fields.set(key, val)
119
+ }
120
+ else if (Array.isArray(prev)) {
121
+ prev.push(val)
130
122
  }
131
123
  else {
132
- out[key] = val
124
+ fields.set(key, [prev, val])
133
125
  }
134
126
  }
135
- return out
127
+ return Object.fromEntries(fields)
136
128
  }
137
129
 
138
130
  return undefined
139
131
  }
140
132
 
133
+ function isJsonBody(request: Request): boolean {
134
+ return (request.headers.get('content-type') ?? '').includes('application/json')
135
+ }
136
+
137
+ // The page a form came from, when its origin is one this server trusts: where a no-JS submit goes back to.
138
+ function trustedReferer(request: Request, trustedOrigins: ReadonlySet<string> | undefined, trustProxy: TrustProxy): URL | undefined {
139
+ const referer = request.headers.get('referer')
140
+ if (!referer)
141
+ return undefined
142
+ let refUrl: URL
143
+ try {
144
+ refUrl = new URL(referer)
145
+ }
146
+ catch {
147
+ return undefined
148
+ }
149
+ return isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy) ? refUrl : undefined
150
+ }
151
+
152
+ function topLevelKey(issue: StandardSchemaIssue): string | undefined {
153
+ const seg = issue.path?.length === 1 ? issue.path[0] : undefined
154
+ const key = typeof seg === 'object' && seg !== null ? seg.key : seg
155
+ return typeof key === 'string' ? key : undefined
156
+ }
157
+
158
+ function setField(target: Record<string, unknown>, key: string, value: unknown): void {
159
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
160
+ }
161
+
162
+ // A form sends one checked box as a single value and none as nothing, so a field the schema wants as an array fails. Each failing top-level field is retried as an array, and the array is kept only where it clears that field's issue.
163
+ async function retryWithFormArrays(schema: StandardSchemaV1, body: Record<string, unknown>, failed: ValidationFailure): Promise<ValidationResult<unknown>> {
164
+ const retried = { ...body }
165
+ const wrapped: string[] = []
166
+ for (const issue of failed.issues) {
167
+ const key = topLevelKey(issue)
168
+ if (key === undefined || Array.isArray(retried[key]) || wrapped.includes(key))
169
+ continue
170
+ setField(retried, key, Object.hasOwn(body, key) ? [body[key]] : [])
171
+ wrapped.push(key)
172
+ }
173
+ if (wrapped.length === 0)
174
+ return failed
175
+ const second = await validateSchema(schema, retried)
176
+ if (second.ok)
177
+ return second
178
+ const stillFailing = new Set(second.issues.map(topLevelKey))
179
+ const kept = wrapped.filter(key => !stillFailing.has(key))
180
+ if (kept.length === 0)
181
+ return failed
182
+ for (const key of wrapped) {
183
+ if (kept.includes(key))
184
+ continue
185
+ if (Object.hasOwn(body, key))
186
+ setField(retried, key, body[key])
187
+ else
188
+ delete retried[key]
189
+ }
190
+ return kept.length === wrapped.length ? second : validateSchema(schema, retried)
191
+ }
192
+
141
193
  function encodedFlashSize(flash: ActionErrorFlash): number {
142
194
  return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
143
195
  }
@@ -178,8 +230,10 @@ function buildActionErrorFlash(
178
230
  }
179
231
  values[k] = v
180
232
  const candidate: ActionErrorFlash = { ...base, values }
181
- if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES)
233
+ if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES) {
182
234
  delete values[k]
235
+ break
236
+ }
183
237
  }
184
238
  }
185
239
 
@@ -190,60 +244,88 @@ function buildActionErrorFlash(
190
244
  return JSON.stringify(finalFlash)
191
245
  }
192
246
 
247
+ /** Programmatic action invocation with Standard Schema validation (used by `ServerPluginAPI.invokeAction` inside middleware chains). */
248
+ export async function invokeActionCore<I, O>(
249
+ act: ServerAction<I, O>,
250
+ input: I,
251
+ ctx: ActionContext,
252
+ ): Promise<ActionResult<O>> {
253
+ let validated: unknown = input
254
+ if (act.schema !== undefined) {
255
+ const checked = await validateSchema(act.schema, input)
256
+ if (!checked.ok) {
257
+ return {
258
+ ok: false,
259
+ status: 400,
260
+ error: 'Validation failed',
261
+ fieldErrors: checked.fieldErrors,
262
+ issues: checked.issues,
263
+ }
264
+ }
265
+ validated = checked.value
266
+ }
267
+
268
+ const result = await act.handler(validated as never, ctx)
269
+ if (result instanceof Response) {
270
+ if (result.status >= 300 && result.status < 400)
271
+ return { ok: true, data: result as unknown as O }
272
+ const ok = result.status >= 200 && result.status < 300
273
+ const ct = result.headers.get('content-type') ?? ''
274
+ if (ct.includes('application/json')) {
275
+ try {
276
+ const body = await result.clone().json() as Record<string, unknown>
277
+ if (typeof body === 'object' && body !== null && 'ok' in body)
278
+ return body as unknown as ActionResult<O>
279
+ return ok
280
+ ? { ok: true, data: body as O }
281
+ : {
282
+ ok: false,
283
+ status: result.status,
284
+ error: typeof body.error === 'string' ? body.error : result.statusText,
285
+ ...(body.fieldErrors !== undefined ? { fieldErrors: body.fieldErrors as Record<string, string> } : {}),
286
+ }
287
+ }
288
+ catch {}
289
+ }
290
+ return ok
291
+ ? { ok: true, data: undefined as O }
292
+ : { ok: false, status: result.status, error: (await result.clone().text().catch(() => '')) || result.statusText }
293
+ }
294
+ return { ok: true, data: result as O }
295
+ }
296
+
193
297
  export async function executeAction(
194
298
  act: ServerAction<unknown, unknown>,
195
299
  request: Request,
196
300
  ctx: ActionContext,
197
301
  trustedOrigins?: ReadonlySet<string>,
198
- trustProxy = false,
199
- maxRequestBodySize = DEFAULT_MAX_REQUEST_BODY_SIZE,
302
+ trustProxy: TrustProxy = false,
200
303
  ): Promise<Response> {
201
- const originCheck = verifyOrigin(request, trustedOrigins, trustProxy)
202
- if (!originCheck.ok) {
203
- return Response.json(
204
- { ok: false, status: 403, error: originCheck.reason },
205
- { status: 403 },
206
- )
207
- }
208
-
209
- const wantsJson = (request.headers.get('accept') ?? '').includes('application/json')
210
- || (request.headers.get('content-type') ?? '').includes('application/json')
304
+ const json = wantsJson(request)
211
305
 
212
306
  let input: unknown
213
307
  if (act.schema !== undefined) {
214
308
  let rawBody: unknown
215
309
  try {
216
- rawBody = await parseActionBody(request, maxRequestBodySize)
310
+ rawBody = await parseActionBody(request)
217
311
  }
218
- catch (err) {
219
- if (err instanceof PayloadTooLargeError)
220
- return Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
312
+ catch {
221
313
  return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
222
314
  }
223
315
 
224
- const checked = await validateSchema(act.schema, rawBody)
316
+ let checked = await validateSchema(act.schema, rawBody)
317
+ if (!checked.ok && !isJsonBody(request) && rawBody !== null && typeof rawBody === 'object' && !Array.isArray(rawBody))
318
+ checked = await retryWithFormArrays(act.schema, rawBody as Record<string, unknown>, checked)
225
319
  if (!checked.ok) {
226
320
  // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
227
- if (!wantsJson) {
228
- const referer = request.headers.get('referer')
229
- if (referer) {
230
- let refUrl: URL | undefined
231
- try {
232
- refUrl = new URL(referer)
233
- }
234
- catch {
235
- refUrl = undefined
236
- }
237
- if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy)) {
238
- const serializedFlash = buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields)
239
- ctx.cookies.set(ACTION_ERROR_COOKIE, serializedFlash, {
240
- httpOnly: true,
241
- sameSite: 'lax',
242
- maxAge: 60,
243
- })
244
- return Response.redirect(refUrl.href, 303)
245
- }
246
- }
321
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
322
+ if (back !== undefined) {
323
+ ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields), {
324
+ httpOnly: true,
325
+ sameSite: 'lax',
326
+ maxAge: 60,
327
+ })
328
+ return new Response(null, { status: 303, headers: { location: back.href } })
247
329
  }
248
330
  return Response.json(
249
331
  { ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues },
@@ -257,20 +339,9 @@ export async function executeAction(
257
339
  if (result instanceof Response)
258
340
  return result
259
341
 
260
- if (!wantsJson) {
261
- const referer = request.headers.get('referer')
262
- if (referer) {
263
- let refUrl: URL | undefined
264
- try {
265
- refUrl = new URL(referer)
266
- }
267
- catch {
268
- refUrl = undefined
269
- }
270
- if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy))
271
- return Response.redirect(refUrl.href, 303)
272
- }
273
- }
342
+ const back = json ? undefined : trustedReferer(request, trustedOrigins, trustProxy)
343
+ if (back !== undefined)
344
+ return new Response(null, { status: 303, headers: { location: back.href } })
274
345
 
275
346
  return Response.json({ ok: true, data: result }, { status: 200 })
276
347
  }