@kayjs/kay 2.0.0-alpha.4 → 2.0.0-alpha.6

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/extras.ts CHANGED
@@ -120,6 +120,17 @@ function clearInserted(current: Node | Node[] | null): void {
120
120
  }
121
121
  }
122
122
 
123
+ function claimTextNode(claimed: Node | null, str: string): Text | undefined {
124
+ if (claimed === null || claimed.nodeType !== 3)
125
+ return undefined
126
+ const text = claimed as Text
127
+ if (text.data === str)
128
+ return text
129
+ if (str.length > 0 && text.data.endsWith(str))
130
+ return text.splitText(text.data.length - str.length)
131
+ return undefined
132
+ }
133
+
123
134
  export function insert(parent: Node, value: () => unknown, marker: Node | null = null): void {
124
135
  let current: Node | Node[] | null = null
125
136
  let textNode: Text | undefined
@@ -144,8 +155,14 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
144
155
  current = null
145
156
  }
146
157
  if (textNode === undefined) {
147
- textNode = document.createTextNode(str)
148
- parent.insertBefore(textNode, marker)
158
+ const claimed = claimTextNode(res.claimed, str)
159
+ if (claimed !== undefined) {
160
+ textNode = claimed
161
+ }
162
+ else {
163
+ textNode = document.createTextNode(str)
164
+ parent.insertBefore(textNode, marker)
165
+ }
149
166
  }
150
167
  else if (textNode.data !== str) {
151
168
  textNode.data = str
@@ -207,8 +224,8 @@ export function show(
207
224
  parent: Node,
208
225
  marker: Node | null,
209
226
  when: () => unknown,
210
- renderTrue: () => Node | null,
211
- renderFalse?: () => Node | null,
227
+ renderTrue: () => unknown,
228
+ renderFalse?: () => unknown,
212
229
  ): void {
213
230
  const parentOwner = getOwner()
214
231
  let branch: 0 | 1 | 2 = 0
@@ -242,17 +259,56 @@ export function show(
242
259
  const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
243
260
  marker = res.marker
244
261
  const rendered = res.result
245
- if (rendered === null)
262
+ if (rendered == null || typeof rendered === 'boolean')
246
263
  return
247
264
 
248
- if (rendered.nodeType === 11) {
249
- nodes = Array.from(rendered.childNodes)
250
- parent.insertBefore(rendered, marker)
265
+ if (typeof rendered === 'string' || typeof rendered === 'number') {
266
+ const str = String(rendered)
267
+ if (str === '')
268
+ return
269
+ const text = claimTextNode(res.claimed, str) ?? document.createTextNode(str)
270
+ if (text.parentNode !== parent)
271
+ parent.insertBefore(text, marker)
272
+ nodes = [text]
273
+ return
251
274
  }
252
- else {
253
- nodes = [rendered]
254
- if (rendered.parentNode !== parent)
275
+
276
+ if (rendered instanceof Node) {
277
+ if (rendered.nodeType === 11) {
278
+ nodes = Array.from(rendered.childNodes)
255
279
  parent.insertBefore(rendered, marker)
280
+ }
281
+ else {
282
+ nodes = [rendered]
283
+ if (rendered.parentNode !== parent)
284
+ parent.insertBefore(rendered, marker)
285
+ }
286
+ return
287
+ }
288
+
289
+ if (Array.isArray(rendered)) {
290
+ const f = document.createDocumentFragment()
291
+ const list: Node[] = []
292
+ for (let i = 0; i < rendered.length; i++) {
293
+ const item = rendered[i]
294
+ if (item instanceof Node) {
295
+ if (item.nodeType === 11)
296
+ list.push(...Array.from(item.childNodes))
297
+ else
298
+ list.push(item)
299
+ f.appendChild(item)
300
+ }
301
+ else if (item != null && typeof item !== 'boolean') {
302
+ const str = String(item)
303
+ if (str !== '') {
304
+ const t = document.createTextNode(str)
305
+ list.push(t)
306
+ f.appendChild(t)
307
+ }
308
+ }
309
+ }
310
+ parent.insertBefore(f, marker)
311
+ nodes = list
256
312
  }
257
313
  })
258
314
  }
package/src/dom/index.ts CHANGED
@@ -27,9 +27,9 @@ 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 } {
30
+ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null } {
31
31
  if (!hydrating)
32
- return { result: fn(), marker }
32
+ return { result: fn(), marker, claimed: null }
33
33
 
34
34
  let claimed: Node | null = marker !== null ? marker : parent.lastChild
35
35
  let nextMarker = marker
@@ -45,7 +45,7 @@ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T):
45
45
  const prevNode = hydrateNode
46
46
  hydrateNode = claimed
47
47
  try {
48
- return { result: fn(), marker: nextMarker }
48
+ return { result: fn(), marker: nextMarker, claimed }
49
49
  }
50
50
  finally {
51
51
  hydrateNode = prevNode
package/src/dom/island.ts CHANGED
@@ -5,98 +5,120 @@ 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
+ export function parseIslandProps(raw: string): Record<string, unknown> {
9
+ if (!raw.includes('"__k":'))
10
+ return JSON.parse(raw) as Record<string, unknown>
11
+ return JSON.parse(raw, (_k, v: unknown) => {
12
+ 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
+ }
24
+ return v
25
+ }) as Record<string, unknown>
26
+ }
27
+
8
28
  type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
9
29
 
10
- class KayIsland extends HTMLElement {
11
- _d: (() => void) | undefined
12
- _s = false
30
+ export function defineIslandElement(): void {
31
+ if (typeof customElements === 'undefined' || customElements.get('kay-island'))
32
+ return
13
33
 
14
- connectedCallback(): void {
15
- if (this._s)
16
- return
17
- this._s = true
34
+ class KayIsland extends HTMLElement {
35
+ _d: (() => void) | undefined
36
+ _s = false
18
37
 
19
- const h = this.getAttribute('h')
20
- if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
21
- if (h === 'visible') {
22
- const target = this.firstElementChild ?? this
23
- const io = new IntersectionObserver((entries) => {
24
- if (entries.some(e => e.isIntersecting)) {
25
- io.disconnect()
26
- void this._l(false)
27
- }
28
- }, { rootMargin: '200px' })
29
- io.observe(target)
30
- return
31
- }
32
- if (h === 'idle') {
33
- const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
34
- ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
38
+ connectedCallback(): void {
39
+ if (this._s)
35
40
  return
36
- }
37
- if (h === 'interaction') {
38
- const evs = ['pointerdown', 'focusin', 'keydown']
39
- const go = () => {
40
- for (const e of evs) this.removeEventListener(e, go, true)
41
- void this._l(false)
41
+ this._s = true
42
+
43
+ const h = this.getAttribute('h')
44
+ if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
45
+ if (h === 'visible') {
46
+ const target = this.firstElementChild ?? this
47
+ const io = new IntersectionObserver((entries) => {
48
+ if (entries.some(e => e.isIntersecting)) {
49
+ io.disconnect()
50
+ void this._l(false)
51
+ }
52
+ }, { rootMargin: '200px' })
53
+ io.observe(target)
54
+ return
42
55
  }
43
- for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
44
- return
45
- }
46
- if (h !== null && h.startsWith('media(')) {
47
- const mq = matchMedia(h.slice(6, -1))
48
- if (mq.matches) {
49
- void this._l(false)
56
+ 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)
59
+ return
50
60
  }
51
- else {
61
+ if (h === 'interaction') {
62
+ const evs = ['pointerdown', 'focusin', 'keydown']
52
63
  const go = () => {
53
- if (mq.matches) {
54
- mq.removeEventListener('change', go)
55
- void this._l(false)
64
+ for (const e of evs) this.removeEventListener(e, go, true)
65
+ void this._l(false)
66
+ }
67
+ for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
68
+ return
69
+ }
70
+ if (h !== null && h.startsWith('media(')) {
71
+ const mq = matchMedia(h.slice(6, -1))
72
+ if (mq.matches) {
73
+ void this._l(false)
74
+ }
75
+ else {
76
+ const go = () => {
77
+ if (mq.matches) {
78
+ mq.removeEventListener('change', go)
79
+ void this._l(false)
80
+ }
56
81
  }
82
+ mq.addEventListener('change', go)
57
83
  }
58
- mq.addEventListener('change', go)
84
+ return
59
85
  }
60
- return
61
86
  }
62
- }
63
87
 
64
- void this._l(h === 'client')
65
- }
88
+ void this._l(h === 'client')
89
+ }
66
90
 
67
- disconnectedCallback(): void {
68
- // Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
69
- queueMicrotask(() => {
70
- if (!this.isConnected) {
71
- this._d?.()
72
- this._d = undefined
73
- this._s = false
74
- }
75
- })
76
- }
91
+ disconnectedCallback(): void {
92
+ // Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
93
+ queueMicrotask(() => {
94
+ if (!this.isConnected) {
95
+ this._d?.()
96
+ this._d = undefined
97
+ this._s = false
98
+ }
99
+ })
100
+ }
77
101
 
78
- async _l(clientOnly: boolean): Promise<void> {
79
- const chunk = this.getAttribute('c')
80
- if (!chunk)
81
- return
102
+ async _l(clientOnly: boolean): Promise<void> {
103
+ const chunk = this.getAttribute('c')
104
+ if (!chunk)
105
+ return
82
106
 
83
- const mod = await import(chunk) as IslandModule
84
- if (!this.isConnected)
85
- return
107
+ const mod = await import(chunk) as IslandModule
108
+ if (!this.isConnected)
109
+ return
86
110
 
87
- const p = this.getAttribute('p')
88
- const props: Record<string, unknown> = p ? JSON.parse(p) : {}
89
- const slot = this.querySelector('kay-slot')
90
- if (slot !== null)
91
- props.children = slot
92
- const render = () => mod.default(props)
93
- this._d = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
94
- ? mount(this, render)
95
- : hydrate(this, render)
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)
120
+ }
96
121
  }
97
- }
98
122
 
99
- export function defineIslandElement(): void {
100
- if (typeof customElements !== 'undefined' && !customElements.get('kay-island'))
101
- customElements.define('kay-island', KayIsland)
123
+ customElements.define('kay-island', KayIsland)
102
124
  }
@@ -21,8 +21,19 @@ export interface BuildPluginContext {
21
21
  emitPublic(relPath: string, content: string | Uint8Array): string
22
22
  /** Add a stylesheet URL to <head> on every page. */
23
23
  addStyle(href: string): void
24
+ /** Add a stylesheet URL to <head> on a specific route path only. */
25
+ addRouteStyle(routePath: string, href: string): void
24
26
  /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
25
27
  addHead(html: string): void
28
+ /** Add raw HTML to <head> on a specific route path only. */
29
+ addRouteHead(routePath: string, html: string): void
30
+ }
31
+
32
+ export interface CheckPluginContext {
33
+ readonly root: string
34
+ readonly routesDir: string
35
+ /** Report a validation error from `kay check`. */
36
+ error(message: string): void
26
37
  }
27
38
 
28
39
  export interface ServerPluginAPI {
@@ -52,6 +63,10 @@ export interface KayPlugin {
52
63
  prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
53
64
  /** Client bootstrap module path — bundled ONLY when this plugin is active. */
54
65
  clientEntry?: string | undefined
66
+ /** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
67
+ check?: (ctx: CheckPluginContext) => void | Promise<void>
68
+ /** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
69
+ watchPaths?: string[] | ((root: string) => string[]) | undefined
55
70
  /** Register custom CLI subcommands (e.g. `kay i18n check`). */
56
71
  commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
57
72
  }
@@ -64,6 +79,7 @@ export interface KayConfig {
64
79
  assetPrefix?: string | undefined
65
80
  security?: SecurityHeadersOptions | false | undefined
66
81
  trustedOrigins?: string[] | undefined
82
+ compress?: boolean | undefined
67
83
  plugins?: KayPlugin[] | undefined
68
84
  }
69
85
 
@@ -75,11 +91,18 @@ export function definePlugin(plugin: KayPlugin): KayPlugin {
75
91
  return plugin
76
92
  }
77
93
 
78
- export async function loadConfig(root: string): Promise<KayConfig> {
94
+ const KAY_ROOT_KEY = Symbol.for('kay.root')
95
+ let configReloadSeq = 0
96
+
97
+ export async function loadConfig(root: string, options?: { fresh?: boolean }): Promise<KayConfig> {
79
98
  const absRoot = resolve(root)
99
+ ;(globalThis as Record<symbol, unknown>)[KAY_ROOT_KEY] = absRoot
80
100
  const configPath = join(absRoot, 'kay.config.ts')
81
101
  if (!existsSync(configPath))
82
102
  return {}
83
- const mod = await import(configPath) as { default?: KayConfig }
103
+ const spec = options?.fresh || process.env.KAY_DEV === '1'
104
+ ? `${configPath}?v=${++configReloadSeq}-${Date.now()}`
105
+ : configPath
106
+ const mod = await import(spec) as { default?: KayConfig }
84
107
  return mod.default ?? {}
85
108
  }
@@ -2,9 +2,22 @@
2
2
 
3
3
  import type { Cookies } from './cookies'
4
4
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
5
- import { verifyOrigin } from './security'
5
+ import { isTrustedOrigin, verifyOrigin } from './security'
6
6
  import { validateSchema } from './standard-schema'
7
7
 
8
+ export const ACTION_ERROR_COOKIE = '__kay_action_err'
9
+
10
+ export interface ActionErrorFlash {
11
+ action: string
12
+ error: string
13
+ fieldErrors?: Record<string, string> | undefined
14
+ values?: Record<string, string> | undefined
15
+ }
16
+
17
+ export function getActionError(locals?: Record<string, unknown>): ActionErrorFlash | undefined {
18
+ return locals?.actionError as ActionErrorFlash | undefined
19
+ }
20
+
8
21
  export interface ActionContext {
9
22
  request: Request
10
23
  url: URL
@@ -126,6 +139,40 @@ export async function executeAction(
126
139
 
127
140
  const checked = await validateSchema(act.schema, rawBody)
128
141
  if (!checked.ok) {
142
+ // Zero-JS progressive HTML <form> submit: flash fieldErrors + submitted string values and redirect 303 back to trusted Referer
143
+ if (!wantsJson) {
144
+ const referer = request.headers.get('referer')
145
+ if (referer) {
146
+ let refUrl: URL | undefined
147
+ try {
148
+ refUrl = new URL(referer)
149
+ }
150
+ catch {
151
+ refUrl = undefined
152
+ }
153
+ if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins)) {
154
+ const values: Record<string, string> = {}
155
+ if (rawBody !== null && typeof rawBody === 'object') {
156
+ for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
157
+ if (typeof v === 'string' && !/password|secret|token/i.test(k) && v.length <= 512)
158
+ values[k] = v
159
+ }
160
+ }
161
+ const flash: ActionErrorFlash = {
162
+ action: act.url,
163
+ error: 'Validation failed',
164
+ fieldErrors: checked.fieldErrors,
165
+ ...(Object.keys(values).length > 0 ? { values } : {}),
166
+ }
167
+ ctx.cookies.set(ACTION_ERROR_COOKIE, JSON.stringify(flash), {
168
+ httpOnly: true,
169
+ sameSite: 'lax',
170
+ maxAge: 60,
171
+ })
172
+ return Response.redirect(refUrl.href, 303)
173
+ }
174
+ }
175
+ }
129
176
  return Response.json(
130
177
  { ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues },
131
178
  { status: 400 },
@@ -141,8 +188,14 @@ export async function executeAction(
141
188
  if (!wantsJson) {
142
189
  const referer = request.headers.get('referer')
143
190
  if (referer) {
144
- const refUrl = new URL(referer)
145
- if (refUrl.origin === ctx.url.origin)
191
+ let refUrl: URL | undefined
192
+ try {
193
+ refUrl = new URL(referer)
194
+ }
195
+ catch {
196
+ refUrl = undefined
197
+ }
198
+ if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins))
146
199
  return Response.redirect(refUrl.href, 303)
147
200
  }
148
201
  }