@kudzujs/core 0.17.8 → 0.17.10

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/README.md CHANGED
@@ -14,7 +14,7 @@ Kudzu compiles ordinary React-shaped TypeScript and TSX into complete static HTM
14
14
 
15
15
  > Experimental `0.17.x`: the compiler API and supported TSX surface may change.
16
16
 
17
- **Current release: [0.17.8](https://github.com/kudzujs/kudzu/releases/tag/v0.17.8).** Delayed keyed rows now keep parent-only text and attributes reactive, including `disabled={busy}`. The compiler reuses existing keyed expression ownership; runtime sources are unchanged. A real Actual Budget Worker/SQLite reduction verifies creation, error recovery, reload persistence and cleanup. Existing 13 artifact fixtures retain identical deploy output. Generator `create-kudzu@0.1.169` targets core `^0.17.8`. No speed or whole-application migration claim is made; startup, restoration and AI-cost/1.0 gates remain unresolved.
17
+ **Current release: [0.17.10](https://github.com/kudzujs/kudzu/releases/tag/v0.17.10).** Supported relative custom hooks now allow identifier aliases for state, setters and returned callbacks. Repeated calls retain independent state, and compiler substitutions avoid capturing callback-local names. No browser runtime is added; Context/private-timer aliases remain unsupported. Generator `create-kudzu@0.1.171` targets core `^0.17.10`. Regression and artifact evidence is recorded in `PERFORMANCE.md`; no speed or whole-application migration claim is made.
18
18
 
19
19
  - [Documentation](https://kudzujs.cloud/docs)
20
20
  - [Installation guide](https://kudzujs.cloud/docs#install)
@@ -24,6 +24,9 @@ import { parseDevHost, parseDevPort, startDevServer } from "./dev-server.mjs"
24
24
  export { parseDevHost, parseDevPort }
25
25
  export { specializeRuntime }
26
26
 
27
+ // Node's module cache outlives individual ProjectSessions.
28
+ const buildGenerations = new Map()
29
+
27
30
  async function loadConfig(root) {
28
31
  for (const name of ["kudzu.config.mjs", "kudzu.config.js"]) {
29
32
  const file = join(root, name)
@@ -91,8 +94,9 @@ export async function buildWithSession(project, { changedFiles, quiet = false, m
91
94
  async function buildInto(project, outputDirectory, { changedFiles, minify, quiet, retainCache, explanationRoute }) {
92
95
  const { root, sourceDirectory, pagesDirectory, workDirectory } = project
93
96
  const previous = retainCache ? project.buildCache : undefined
94
- project.buildGeneration = (project.buildGeneration ?? 0) + 1
95
- project.buildDirectory = project.buildGeneration > 1 ? join(workDirectory, "build", String(project.buildGeneration)) : workDirectory
97
+ const generation = (buildGenerations.get(root) ?? 0) + 1
98
+ buildGenerations.set(root, generation)
99
+ project.buildGeneration = generation
96
100
  const { collectClientModules, compileClientModule, compiledPath, compileSourceAsync, layoutExportError, orderSourceStyles, reachableSourceFiles, safeStaticFiles } = createSourceCompiler(project)
97
101
  const config = await loadConfig(root)
98
102
  const base = normalizeBase(config.base)
@@ -227,7 +231,7 @@ async function buildInto(project, outputDirectory, { changedFiles, minify, quiet
227
231
  const sourceStyleUrls = stylesByPage.get(pageFile).map(file => assetPath(base, `assets/${relative(sourceDirectory, file).replaceAll(sep, "/")}`)).filter(url => !globalStyleUrlSet.has(url))
228
232
  const styleUrls = [...sourceStyleUrls, ...globalStyleUrls]
229
233
  const compiledFile = compiledPath(pageFile)
230
- const module = await import(`${pathToFileURL(compiledFile).href}?v=${Date.now()}`)
234
+ const module = await import(`${pathToFileURL(compiledFile).href}?v=${generation}`)
231
235
  if (typeof module.default !== "function") throw new Error(`${relative(root, pageFile)} must export a default component`)
232
236
  if (Object.hasOwn(module, "layout") && typeof module.layout !== "function") throw layoutExportError(pageFile, sourceIndex.get(pageFile))
233
237
 
@@ -929,8 +933,10 @@ export async function dev({ port = parseDevPort(process.env.PORT), host = parseD
929
933
  if (typeof host !== "string" || !host.trim()) throw new Error(`Invalid dev server host: ${host}`)
930
934
  const project = createProjectSession(projectRoot)
931
935
  const { root, sourceDirectory, workDirectory, outputDirectory } = project
932
- const base = normalizeBase((await loadConfig(root)).base)
933
- return startDevServer({ build: options => buildWithSession(project, options), port, host, base, sourceDirectory, workDirectory, outputDirectory })
936
+ const config = await loadConfig(root)
937
+ const base = normalizeBase(config.base)
938
+ const publicDirectory = normalizePublicDirectory(config.publicDir, project)
939
+ return startDevServer({ build: options => buildWithSession(project, options), port, host, base, sourceDirectory, publicDirectory, workDirectory, outputDirectory })
934
940
  }
935
941
 
936
942
  function inlineJson(value) {
@@ -1096,7 +1102,9 @@ function normalizePublicDirectory(value, { root, outputDirectory, workDirectory
1096
1102
  if (value === undefined) return join(root, "public")
1097
1103
  if (typeof value !== "string" || !value) throw new Error("kudzu.config publicDir must be a non-empty directory path")
1098
1104
  const directory = resolve(root, value)
1099
- if (directory === outputDirectory || directory === workDirectory) throw new Error("kudzu.config publicDir cannot be dist or .kudzu")
1105
+ if ([outputDirectory, workDirectory].some(target => directory === target || directory.startsWith(join(target, sep)) || target.startsWith(join(directory, sep)))) {
1106
+ throw new Error("kudzu.config publicDir cannot overlap dist or .kudzu")
1107
+ }
1100
1108
  return directory
1101
1109
  }
1102
1110
 
@@ -1235,7 +1243,7 @@ function sameRuntimePrecedence(left, right) {
1235
1243
  }
1236
1244
 
1237
1245
  function routeFromPage(file, params = {}, pagesDirectory) {
1238
- const page = relative(pagesDirectory, file).replace(/\\/g, "/").replace(/\.tsx$/, "")
1246
+ const page = pageRoutePattern(file, pagesDirectory)
1239
1247
  if (page.includes("[...")) throw new Error(`Catch-all routes are not supported: ${page}`)
1240
1248
  const filled = page.replace(/\[([^\]]+)\]/g, (_, name) => {
1241
1249
  if (!Object.hasOwn(params, name)) throw new Error(`Missing param "${name}" for route ${page}`)
@@ -1243,7 +1251,7 @@ function routeFromPage(file, params = {}, pagesDirectory) {
1243
1251
  if (!value || value === "." || value === ".." || /[\\/\0?#]/.test(value)) throw new Error(`Invalid param "${name}" for route ${page}`)
1244
1252
  return value
1245
1253
  })
1246
- return filled === "index" ? "" : filled.replace(/\/index$/, "")
1254
+ return filled
1247
1255
  }
1248
1256
 
1249
1257
  function isPlainRecord(value) {
@@ -29,7 +29,6 @@ import { createZustandPass } from "./zustand-pass.mjs"
29
29
 
30
30
  export function createSourceCompiler(project) {
31
31
  const { root, sourceDirectory, pagesDirectory, workDirectory, workerCompiler, modules, counters, timings } = project
32
- const buildDirectory = project.buildDirectory ?? workDirectory
33
32
  const { ordinaryRuntimeDependencies, resolveSourceImport, runtimeModuleReference } = project.graph
34
33
  const parseSourceFile = (file, source) => modules.read(file, source).sourceFile
35
34
  const importFreeModules = new Map()
@@ -121,7 +120,7 @@ function createPlainModuleTransformer(file, sourceFiles) {
121
120
  return context => sourceFile => context.factory.updateSourceFile(sourceFile, sourceFile.statements.map(statement => {
122
121
  if ((!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) || !runtimeModuleReference(statement) || !statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier) || !statement.moduleSpecifier.text.startsWith(".")) return statement
123
122
  const target = resolveSourceImport(file, statement.moduleSpecifier.text, sourceFiles)
124
- const specifier = context.factory.createStringLiteral(relativeModulePath(compiledPath(file), compiledPath(target)))
123
+ const specifier = context.factory.createStringLiteral(buildModulePath(file, target))
125
124
  if (ts.isImportDeclaration(statement)) return context.factory.updateImportDeclaration(statement, statement.modifiers, statement.importClause, specifier, statement.attributes)
126
125
  return context.factory.updateExportDeclaration(statement, statement.modifiers, statement.isTypeOnly, statement.exportClause, specifier, statement.attributes)
127
126
  }))
@@ -714,11 +713,14 @@ function createKudzuTransformer({ semantic, handlerUrl, file, sourceFiles, sourc
714
713
  if (!isLocalConst(node) || !ts.isObjectBindingPattern(node.name) || node.initializer.arguments.length) throw sourceNodeError(node, sourceFile, "Relative custom hooks must initialize one top-level const object destructuring with no arguments")
715
714
  const hook = resolveCustomHook(importBindings.get(callName), node.initializer)
716
715
  const names = new Set()
716
+ const localNames = new Map()
717
717
  for (const element of node.name.elements) {
718
- if (element.dotDotDotToken || element.propertyName || element.initializer || !ts.isIdentifier(element.name)) throw sourceNodeError(element, sourceFile, "Relative custom hook results must use direct identifier shorthand without aliases, defaults, or rest")
719
- const name = element.name.text
718
+ if (element.dotDotDotToken || element.initializer || !ts.isIdentifier(element.name) || element.propertyName && (!ts.isIdentifier(element.propertyName) || hook.context || hook.privateStates.size)) throw sourceNodeError(element, sourceFile, "Relative custom hook results require identifier fields and local names without defaults or rest; Context and private-timer result aliases remain unsupported")
719
+ const name = (element.propertyName ?? element.name).text
720
720
  if (!hook.fields.has(name)) throw sourceNodeError(element, sourceFile, `Relative custom hook does not directly return ${JSON.stringify(name)}`)
721
+ if (names.has(name)) throw sourceNodeError(element, sourceFile, `Relative custom hook result ${JSON.stringify(name)} must be destructured only once`)
721
722
  names.add(name)
723
+ localNames.set(name, element.name.text)
722
724
  }
723
725
  const owner = nearestFunction(node)
724
726
  if (!owner) throw sourceNodeError(node, sourceFile, "Relative custom hooks cannot be used outside a Kudzu component")
@@ -730,7 +732,7 @@ function createKudzuTransformer({ semantic, handlerUrl, file, sourceFiles, sourc
730
732
  if (callback) for (const state of referencedStateNames(callback.body, hook.states, callback)) requiredContextStates.add(state)
731
733
  }
732
734
  }
733
- const contextSubstitutions = new Map()
735
+ const contextSubstitutions = new Map([...localNames].filter(([name, local]) => name !== local).map(([name, local]) => [name, factory.createIdentifier(local)]))
734
736
  const contextSharedStates = new Map()
735
737
  for (const [setter, state] of hook.states) {
736
738
  if (hook.context) {
@@ -774,16 +776,20 @@ function createKudzuTransformer({ semantic, handlerUrl, file, sourceFiles, sourc
774
776
  }
775
777
  if (names.has(setter) !== names.has(state)) throw sourceNodeError(node.name, sourceFile, `Relative custom hook state ${JSON.stringify(state)} and setter ${JSON.stringify(setter)} must be destructured together`)
776
778
  if (names.has(setter)) {
777
- setters.set(setter, state)
778
- registerState(owner, state, setter, "custom-hook", node)
779
+ setters.set(localNames.get(setter), localNames.get(state))
780
+ registerState(owner, localNames.get(state), localNames.get(setter), "custom-hook", node)
779
781
  }
780
782
  }
781
783
  settersByFunction.set(owner, setters)
782
784
  for (const name of names) {
783
785
  if (hook.callbacks.has(name)) {
784
786
  const callback = contextSubstitutions.size ? substituteClone(hook.callbacks.get(name), contextSubstitutions, factory, context) : hook.callbacks.get(name)
787
+ if (contextSubstitutions.size) {
788
+ ts.setParentRecursive(callback, false)
789
+ callback.parent = hook.callbacks.get(name).parent
790
+ }
785
791
  const callbacks = customHookFunctionsByOwner.get(owner) ?? new Map()
786
- callbacks.set(name, callback)
792
+ callbacks.set(localNames.get(name), callback)
787
793
  customHookFunctionsByOwner.set(owner, callbacks)
788
794
  if (hook.context) {
789
795
  const reducers = reducersByFunction.get(owner) ?? new Map()
@@ -2028,13 +2034,13 @@ function createKudzuTransformer({ semantic, handlerUrl, file, sourceFiles, sourc
2028
2034
  if (!runtimeModuleReference(node)) return node
2029
2035
  if (isStaticImport(node.moduleSpecifier.text)) return staticImportEntry(node, sourceFile, file, staticFiles, importedAssets, cssModules, base, factory)?.replacement
2030
2036
  const target = resolveSourceImport(file, node.moduleSpecifier.text, sourceFiles)
2031
- return factory.updateImportDeclaration(node, node.modifiers, node.importClause, factory.createStringLiteral(relativeModulePath(compiledPath(file), compiledPath(target))), node.attributes)
2037
+ return factory.updateImportDeclaration(node, node.modifiers, node.importClause, factory.createStringLiteral(buildModulePath(file, target)), node.attributes)
2032
2038
  }
2033
2039
 
2034
2040
  if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier) && node.moduleSpecifier.text.startsWith(".")) {
2035
2041
  if (!runtimeModuleReference(node)) return node
2036
2042
  const target = resolveSourceImport(file, node.moduleSpecifier.text, sourceFiles)
2037
- return factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, node.exportClause, factory.createStringLiteral(relativeModulePath(compiledPath(file), compiledPath(target))), node.attributes)
2043
+ return factory.updateExportDeclaration(node, node.modifiers, node.isTypeOnly, node.exportClause, factory.createStringLiteral(buildModulePath(file, target)), node.attributes)
2038
2044
  }
2039
2045
 
2040
2046
  const effectAlias = ts.isCallExpression(node) && ts.isIdentifier(node.expression) ? node.expression.text : undefined
@@ -3275,12 +3281,42 @@ function isEventOnlyComponentLocal(root, name) {
3275
3281
  }
3276
3282
 
3277
3283
  function substituteClone(root, substitutions, factory, context) {
3284
+ const index = isFunctionLike(root) ? createBindingIndex(root) : undefined
3285
+ const locals = new Map()
3286
+ if (index) {
3287
+ // Renaming a capture must not bind it to a callback-local name.
3288
+ const targets = new Set([...substitutions.values()].filter(ts.isIdentifier).map(node => node.text))
3289
+ const bindings = index.bindings()
3290
+ const occupied = new Set([...bindings.map(binding => binding.debugName), ...targets])
3291
+ for (const binding of bindings) {
3292
+ if (!targets.has(binding.debugName) || ["global", "unresolved"].includes(binding.declarationKind)) continue
3293
+ let name = `__kLocal_${binding.debugName}`
3294
+ while (occupied.has(name)) name += "_"
3295
+ occupied.add(name)
3296
+ locals.set(binding.slot, name)
3297
+ }
3298
+ }
3299
+ const localName = node => {
3300
+ if (!index || !locals.size) return undefined
3301
+ const parent = node.parent
3302
+ const declaration = parent?.name === node && (ts.isVariableDeclaration(parent) || ts.isParameter(parent) || ts.isBindingElement(parent) || ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent) || ts.isClassDeclaration(parent) || ts.isClassExpression(parent))
3303
+ const binding = declaration ? index.resolveBinding(node) : index.resolveReference(node)
3304
+ return binding && locals.get(binding.slot)
3305
+ }
3278
3306
  const visit = (node, shadowed = new Set()) => {
3279
3307
  if (ts.isTypeNode(node)) return cloneAst(node, factory, context)
3280
- if (ts.isShorthandPropertyAssignment(node) && substitutions.has(node.name.text) && !shadowed.has(node.name.text)) {
3308
+ if (ts.isShorthandPropertyAssignment(node) && localName(node.name)) {
3309
+ const name = factory.createIdentifier(localName(node.name))
3310
+ return factory.createPropertyAssignment(cloneAst(node.name, factory, context), node.objectAssignmentInitializer ? factory.createAssignment(name, visit(node.objectAssignmentInitializer, shadowed)) : name)
3311
+ }
3312
+ if (ts.isBindingElement(node) && !node.propertyName && !node.dotDotDotToken && ts.isIdentifier(node.name) && localName(node.name) && ts.isObjectBindingPattern(node.parent)) {
3313
+ return factory.updateBindingElement(node, node.dotDotDotToken, cloneAst(node.name, factory, context), factory.createIdentifier(localName(node.name)), node.initializer && visit(node.initializer, shadowed))
3314
+ }
3315
+ if (ts.isIdentifier(node) && localName(node)) return factory.createIdentifier(localName(node))
3316
+ if (ts.isShorthandPropertyAssignment(node) && substitutions.has(node.name.text) && !shadowed.has(node.name.text) && (!isFunctionLike(root) || !isShadowedIdentifier(node.name, root))) {
3281
3317
  return factory.createPropertyAssignment(cloneAst(node.name, factory, context), cloneAst(substitutions.get(node.name.text), factory, context))
3282
3318
  }
3283
- if (ts.isIdentifier(node) && substitutions.has(node.text) && !shadowed.has(node.text) && isReferenceIdentifier(node) && !isJsxSyntaxIdentifier(node)) {
3319
+ if (ts.isIdentifier(node) && substitutions.has(node.text) && !shadowed.has(node.text) && (!isFunctionLike(root) || !isShadowedIdentifier(node, root)) && isReferenceIdentifier(node) && !isJsxSyntaxIdentifier(node)) {
3284
3320
  return cloneAst(substitutions.get(node.text), factory, context)
3285
3321
  }
3286
3322
  const nextShadowed = isFunctionLike(node)
@@ -3825,7 +3861,12 @@ function clientModulePath(file) {
3825
3861
  }
3826
3862
 
3827
3863
  function compiledPath(file) {
3828
- return join(buildDirectory, relative(sourceDirectory, file)).replace(/\.(?:ts|tsx)$/, ".mjs")
3864
+ return join(workDirectory, relative(sourceDirectory, file)).replace(/\.(?:ts|tsx)$/, ".mjs")
3865
+ }
3866
+
3867
+ function buildModulePath(from, to) {
3868
+ const path = relativeModulePath(compiledPath(from), compiledPath(to))
3869
+ return project.buildGeneration > 1 ? `${path}?v=${project.buildGeneration}` : path
3829
3870
  }
3830
3871
 
3831
3872
  const compileEventCommand = createCommandSpecializer({ isPrimitiveLiteral: isPrimitiveDefaultLiteral })
@@ -2,7 +2,7 @@ export type StateSetter<T> = (value: T | ((previous: T) => T)) => void
2
2
  export type Reducer<State, Action> = (state: State, action: Action) => State
3
3
  export type Dispatch<Action> = (action: Action) => void
4
4
  export type EffectCleanup = () => void | Promise<void>
5
- export type EffectDependency = string | number | boolean | null
5
+ export type EffectDependency = string | number | boolean | null | readonly unknown[]
6
6
  export const Fragment: unique symbol
7
7
 
8
8
  export function useId(): string
@@ -956,7 +956,8 @@ async function renderList(node, namespace, selectValue) {
956
956
  renderContext.listRoot = templateRoot
957
957
  renderContext.listRowRoot = templateRoot
958
958
  const template = await renderNode(node.render({}, 0), namespace, selectValue)
959
- if (template.includes("data-k-native-") || template.includes("data-k-effects=") || template.includes("data-k-list=")) descriptor.mount = true
959
+ const commandEvents = template.includes("data-k-on-") || template.includes("data-k-set-true-")
960
+ if (commandEvents || template.includes("data-k-native-") || template.includes("data-k-effects=") || template.includes("data-k-list=")) descriptor.mount = true
960
961
  if (template.includes("data-k-list=")) descriptor.nested = true
961
962
  if (template.includes("data-k-effects=")) descriptor.effects = true
962
963
  if (templateRoot.conditions) descriptor.conditions = true
@@ -976,7 +977,7 @@ async function renderList(node, namespace, selectValue) {
976
977
  descriptor.mount = true
977
978
  }
978
979
  if (renderContext.listRowIds.length) descriptor.rowIds = renderContext.listRowIds.map(({ id }) => id)
979
- if (descriptor.rowStates && !descriptor.effects && !descriptor.nested && !template.includes("data-k-text")) descriptor.fastRelease = true
980
+ if (descriptor.rowStates && !descriptor.effects && !descriptor.nested && !commandEvents && !template.includes("data-k-text")) descriptor.fastRelease = true
980
981
  const valueSeed = node.ownerField || node.keyField === null ? undefined : listSeed(node.values, renderContext.listFields)
981
982
  const seed = node.selector.length ? undefined : valueSeed
982
983
  if (seed) descriptor.seed = seed
@@ -29,8 +29,15 @@ if (typeof document !== "undefined") {
29
29
  for (const node of document.querySelectorAll("[data-k-text]")) browserState.set(node.dataset.kText, JSON.parse(node.dataset.kValue))
30
30
 
31
31
  const eventNames = ["click", "input", "change"]
32
- for (const eventName of eventNames) document.addEventListener(eventName, event => {
33
- const target = event.target.closest(`[data-k-on-${eventName}]`)
34
- if (target) applyCommands(browserState, JSON.parse(target.getAttribute(`data-k-on-${eventName}`)), commitDom)
35
- })
32
+ for (const eventName of eventNames) {
33
+ const listener = event => {
34
+ const target = event.currentTarget
35
+ const direct = target.getAttribute(`data-k-set-true-${eventName}`)
36
+ if (direct) {
37
+ browserState.set(direct, true)
38
+ commitDom(direct, true)
39
+ } else applyCommands(browserState, JSON.parse(target.getAttribute(`data-k-on-${eventName}`)), commitDom)
40
+ }
41
+ for (const node of document.querySelectorAll(`[data-k-set-true-${eventName}],[data-k-on-${eventName}]`)) node.addEventListener(eventName, listener)
42
+ }
36
43
  }
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto"
2
2
  import { readFile, stat, watch } from "node:fs/promises"
3
3
  import { createServer } from "node:http"
4
- import { extname, join, resolve, sep } from "node:path"
4
+ import { dirname, extname, join, resolve, sep } from "node:path"
5
5
  import { browserPath, withBase } from "./compiler/path-helpers.mjs"
6
6
  import { stateSchema } from "./dev-state.js"
7
7
 
@@ -19,7 +19,7 @@ export function parseDevHost(value) {
19
19
  return value?.trim() || "127.0.0.1"
20
20
  }
21
21
 
22
- export async function startDevServer({ build, port, host, base, sourceDirectory, workDirectory, outputDirectory }) {
22
+ export async function startDevServer({ build, port, host, base, sourceDirectory, publicDirectory, workDirectory, outputDirectory }) {
23
23
  let buildError
24
24
  let revision = 0
25
25
  const session = randomUUID()
@@ -111,12 +111,47 @@ export async function startDevServer({ build, port, host, base, sourceDirectory,
111
111
  } while (pending)
112
112
  rebuilding = false
113
113
  }
114
- const watcher = watch(sourceDirectory, { recursive: true })
115
- for await (const event of watcher) {
116
- changedFile = event.filename
117
- changedFiles.add(event.filename)
114
+ const directories = publicDirectory === sourceDirectory || publicDirectory.startsWith(`${sourceDirectory}${sep}`) ? [sourceDirectory] : [sourceDirectory, publicDirectory]
115
+ await Promise.all(directories.map(directory => watchDirectory(directory, file => {
116
+ changedFile = file
117
+ changedFiles.add(file)
118
118
  clearTimeout(timer)
119
119
  timer = setTimeout(rebuild, 80)
120
+ })))
121
+ }
122
+
123
+ async function watchDirectory(directory, changed) {
124
+ for (;;) {
125
+ let ancestor = dirname(directory)
126
+ let missing
127
+ while (!await exists(ancestor)) {
128
+ missing = ancestor
129
+ ancestor = dirname(ancestor)
130
+ }
131
+ const controller = new AbortController()
132
+ try {
133
+ // A parent watch detects replacement even when the directory is recreated before stat().
134
+ const observe = async (root, recursive) => {
135
+ for await (const event of watch(root, { recursive, signal: controller.signal })) {
136
+ const file = event.filename == null ? undefined : resolve(root, event.filename)
137
+ if (file && file !== directory && !file.startsWith(`${directory}${sep}`) && !directory.startsWith(`${file}${sep}`)) continue
138
+ changed(file)
139
+ if (!recursive || file === directory) break
140
+ }
141
+ }
142
+ const watchers = [observe(ancestor, false)]
143
+ if (await exists(directory)) watchers.push(observe(directory, true))
144
+ // Ancestor creation may race watcher installation.
145
+ if (missing && await exists(missing)) {
146
+ changed(directory)
147
+ controller.abort()
148
+ }
149
+ await Promise.race(watchers)
150
+ } catch (error) {
151
+ if (error.code !== "ENOENT" && error.name !== "AbortError") throw error
152
+ } finally {
153
+ controller.abort()
154
+ }
120
155
  }
121
156
  }
122
157
 
@@ -23,11 +23,13 @@ if(typeof document!=="undefined"){
23
23
  for(const node of document.querySelectorAll("[data-k-text]"))browserState.set(node.dataset.kText,JSON.parse(node.dataset.kValue))
24
24
 
25
25
  const eventNames = ["click", "input", "change"]
26
- for(const eventName of eventNames)document.addEventListener(eventName,event=>{
27
- const target=event.target.closest(`[data-k-set-true-${eventName}],[data-k-on-${eventName}]`)
28
- if(!target)return
26
+ for(const eventName of eventNames){
27
+ const listener=event=>{
28
+ const target=event.currentTarget
29
29
  const direct=target.getAttribute(`data-k-set-true-${eventName}`)
30
30
  if(direct){browserState.set(direct,true);commitDom(direct,true)}
31
31
  else applyCommands(browserState,JSON.parse(target.getAttribute(`data-k-on-${eventName}`)),commitDom)
32
- })
32
+ }
33
+ for(const node of document.querySelectorAll(`[data-k-set-true-${eventName}],[data-k-on-${eventName}]`))node.addEventListener(eventName,listener)
34
+ }
33
35
  }
@@ -118,39 +118,22 @@ if (typeof document !== "undefined") {
118
118
  mountText(document)
119
119
 
120
120
  const eventNames = ["click", "input", "change"]
121
- for (const eventName of eventNames) {
122
- const directName = `kSetTrue${capitalize(eventName)}`
123
- const commandsName = `kOn${capitalize(eventName)}`
124
- const selector = `[data-k-set-true-${eventName}],[data-k-on-${eventName}]`
125
- document.addEventListener(eventName, event => {
126
- const direct = event.target.dataset?.[directName]
127
- if (direct) {
128
- browserState.set(direct, true)
129
- commitDom(direct, true)
130
- return
131
- }
132
- const commands = event.target.dataset?.[commandsName]
133
- if (commands) {
134
- applyCommands(browserState, JSON.parse(commands), commitDom)
135
- return
136
- }
137
- const target = event.target.closest?.(selector)
138
- if (!target) return
139
- const inheritedDirect = target.dataset[directName]
140
- if (inheritedDirect) {
141
- browserState.set(inheritedDirect, true)
142
- commitDom(inheritedDirect, true)
143
- return
144
- }
145
- applyCommands(browserState, JSON.parse(target.dataset[commandsName]), commitDom)
146
- })
121
+ const listener = event => {
122
+ const target = event.currentTarget
123
+ const direct = target.getAttribute(`data-k-set-true-${event.type}`)
124
+ if (direct) {
125
+ browserState.set(direct, true)
126
+ commitDom(direct, true)
127
+ } else applyCommands(browserState, JSON.parse(target.getAttribute(`data-k-on-${event.type}`)), commitDom)
147
128
  }
129
+ const listen = (root, method) => {
130
+ for (const eventName of eventNames) for (const node of matching(root, `[data-k-set-true-${eventName}],[data-k-on-${eventName}]`)) node[method](eventName, listener)
131
+ }
132
+ registerMountHook(root => listen(root, "addEventListener"))
133
+ registerUnmountHook(root => listen(root, "removeEventListener"))
134
+ listen(document, "addEventListener")
148
135
  }
149
136
 
150
137
  function matching(root, selector) {
151
138
  return [...(root.matches?.(selector) ? [root] : []), ...(root.querySelectorAll?.(selector) ?? [])]
152
139
  }
153
-
154
- function capitalize(value) {
155
- return value[0].toUpperCase() + value.slice(1)
156
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kudzujs/core",
3
- "version": "0.17.8",
3
+ "version": "0.17.10",
4
4
  "description": "HTML-first TSX framework with synchronous state semantics and no virtual DOM",
5
5
  "type": "module",
6
6
  "license": "MIT",