prunelle 0.1.1 → 0.7.0

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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -6,7 +6,8 @@ import type { DevChildMessage, DevChildOptions } from './protocol'
6
6
  import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
- import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
9
+ import { recordDevCrashError } from './error-log'
10
+ import { createDevHostCheck } from './host-check'
10
11
  import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
11
12
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
12
13
 
@@ -18,18 +19,43 @@ export interface DevSupervisorOptions {
18
19
  maxRequestBodySize?: number | undefined
19
20
  /** The app process is replaced once its RSS passes this after a rebuild. */
20
21
  maxRssMb?: number | undefined
22
+ /** Origins besides loopback and IP addresses the server answers under: the config's `site` and `trustedOrigins`. */
23
+ allowedOrigins?: readonly (string | undefined)[] | undefined
21
24
  }
22
25
 
23
26
  interface Child {
24
27
  proc: Subprocess<'ignore', 'inherit', 'pipe'>
25
28
  socket: string
26
29
  stopping: boolean
30
+ crashHandled: Promise<void>
27
31
  }
28
32
 
29
33
  const CHILD_ENTRY = join(import.meta.dir, 'child.ts')
30
34
  const STOP_GRACE_MS = 5000
31
35
  const KEPT_STDERR = 8192
32
36
  const DEFAULT_MAX_RSS_MB = 2048
37
+ // When no CLI/API limit is set, let the child process enforce `prunelle.config.ts`'s `maxRequestBodySize` (including updates across recycles).
38
+ const DEFAULT_SUPERVISOR_MAX_BODY = 1024 * 1024 * 1024
39
+
40
+ async function drainStderr(stream: ReadableStream<Uint8Array>): Promise<string> {
41
+ let tail = ''
42
+ const decoder = new TextDecoder()
43
+ for await (const chunk of stream) {
44
+ process.stderr.write(chunk)
45
+ tail = (tail + decoder.decode(chunk, { stream: true })).slice(-KEPT_STDERR)
46
+ }
47
+ const rest = decoder.decode()
48
+ return rest !== '' ? (tail + rest).slice(-KEPT_STDERR) : tail
49
+ }
50
+
51
+ async function stopChild(child: Child): Promise<void> {
52
+ child.stopping = true
53
+ if (child.proc.exitCode === null && child.proc.signalCode === null)
54
+ child.proc.send({ t: 'stop' })
55
+ const kill = setTimeout(() => child.proc.kill('SIGKILL'), STOP_GRACE_MS)
56
+ await child.proc.exited
57
+ clearTimeout(kill)
58
+ }
33
59
 
34
60
  export async function devSupervisor(options: DevSupervisorOptions): Promise<{ url: string, stop: () => Promise<void> }> {
35
61
  const root = resolve(options.root)
@@ -48,8 +74,14 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
48
74
  if (stopped)
49
75
  return Promise.resolve(undefined)
50
76
  const socket = join(socketDir, `${++spawned}.sock`)
51
- const childOptions: DevChildOptions = { root, routesDir: options.routesDir, unix: socket, maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB }
52
- let stderrTail = ''
77
+ const childOptions: DevChildOptions = {
78
+ root,
79
+ routesDir: options.routesDir,
80
+ unix: socket,
81
+ hostname: options.hostname,
82
+ ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}),
83
+ maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB,
84
+ }
53
85
  let onReady: (child: Child | undefined) => void = () => {}
54
86
  const started = new Promise<Child | undefined>((res) => { onReady = res })
55
87
  const proc = Bun.spawn({
@@ -64,6 +96,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
64
96
  else if (message.t === 'ready') {
65
97
  reloadAssets = makeDevReloadAssets(message.assetPrefix)
66
98
  crashed = undefined
99
+ recordDevCrashError(root, undefined)
67
100
  onReady(child)
68
101
  }
69
102
  else if (child === live && !child.stopping && !stopped) {
@@ -72,39 +105,26 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
72
105
  }
73
106
  },
74
107
  })
75
- const child: Child = { proc, socket, stopping: false }
76
- live = child
77
- void (async () => {
78
- const decoder = new TextDecoder()
79
- for await (const chunk of proc.stderr) {
80
- process.stderr.write(chunk)
81
- stderrTail = (stderrTail + decoder.decode(chunk, { stream: true })).slice(-KEPT_STDERR)
82
- }
83
- })()
84
- void proc.exited.then((code) => {
108
+ const stderrDone = drainStderr(proc.stderr)
109
+ const crashHandled = proc.exited.then(async (code) => {
85
110
  rmSync(socket, { force: true })
86
111
  if (child.stopping || stopped)
87
112
  return
113
+ const stderrTail = await stderrDone
88
114
  const how = proc.signalCode !== null ? `was killed by ${proc.signalCode}` : `exited with code ${code}`
89
115
  crashed = [`prunelle dev: the app process ${how}.`, stderrTail.trim(), 'Save a file to start it again.'].filter(Boolean).join('\n\n')
116
+ recordDevCrashError(root, crashed)
90
117
  if (live === child)
91
118
  live = undefined
92
119
  onReady(undefined)
93
120
  hub.broadcast('reload')
94
121
  restartOnSave()
95
122
  })
123
+ const child: Child = { proc, socket, stopping: false, crashHandled }
124
+ live = child
96
125
  return started
97
126
  }
98
127
 
99
- async function stopChild(child: Child): Promise<void> {
100
- child.stopping = true
101
- if (child.proc.exitCode === null && child.proc.signalCode === null)
102
- child.proc.send({ t: 'stop' })
103
- const kill = setTimeout(() => child.proc.kill('SIGKILL'), STOP_GRACE_MS)
104
- await child.proc.exited
105
- clearTimeout(kill)
106
- }
107
-
108
128
  // A crashed app restarts on the next edit under the root (not recursively) or its source folders.
109
129
  function restartOnSave(): void {
110
130
  const dirs = [[root, false], [join(root, 'src'), true], ...(options.routesDir !== undefined ? [[resolve(root, options.routesDir), true] as const] : [])] as const
@@ -124,12 +144,16 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
124
144
  ready = spawnChild()
125
145
  await ready
126
146
 
147
+ const checkHost = createDevHostCheck(options.hostname, options.allowedOrigins ?? [])
127
148
  const server = Bun.serve({
128
149
  port: options.port ?? 3000,
129
150
  hostname: options.hostname ?? '127.0.0.1',
130
151
  idleTimeout: 30,
131
- maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
152
+ maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_SUPERVISOR_MAX_BODY,
132
153
  async fetch(request, srv) {
154
+ const refused = checkHost(request)
155
+ if (refused !== undefined)
156
+ return refused
133
157
  const url = new URL(request.url)
134
158
  if (url.pathname === reloadAssets.eventsPath) {
135
159
  srv.timeout(request, 0)
@@ -156,8 +180,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
156
180
  catch (err) {
157
181
  if (request.signal.aborted)
158
182
  return new Response(null, { status: 499 })
159
- // A refused connection is most often the child dying: its exit, and its stderr, come right after.
160
- await Promise.race([child.proc.exited, Bun.sleep(1000)])
183
+ // A refused connection is most often the child dying: wait for its exit and drained stderr before answering.
184
+ await Promise.race([child.crashHandled, Bun.sleep(1000)])
161
185
  return buildErrorResponse(request, crashed ?? `prunelle dev: the app process did not answer: ${err instanceof Error ? err.message : String(err)}`, reloadAssets.script)
162
186
  }
163
187
  },
@@ -179,6 +203,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
179
203
  hub.close()
180
204
  if (live !== undefined)
181
205
  await stopChild(live)
206
+ rmSync(join(root, '.prunelle-dev'), { recursive: true, force: true })
182
207
  rmSync(socketDir, { recursive: true, force: true })
183
208
  })()
184
209
  return stopPromise
@@ -3,7 +3,7 @@
3
3
  import type { FSWatcher } from 'node:fs'
4
4
  import type { loadConfig } from '../plugins/index'
5
5
  import { existsSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
6
- import { dirname, isAbsolute, join, resolve } from 'node:path'
6
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
7
7
  import { isInNodeModules } from '../build/files'
8
8
  import { isInside } from '../build/is-inside'
9
9
  import { createAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
@@ -21,9 +21,34 @@ export function srcChangeKind(name: string): ChangeKind {
21
21
  return CODE_FILE_RE.test(name) ? 'code' : 'full'
22
22
  }
23
23
 
24
+ type ScanLoader = 'js' | 'jsx' | 'ts' | 'tsx'
25
+
26
+ // A `.ts` file is read as TS, not TSX: there `<T>(x: T) => x` is a generic arrow, not a JSX tag (#108).
27
+ function scanLoader(file: string): ScanLoader {
28
+ if (file.endsWith('.tsx'))
29
+ return 'tsx'
30
+ if (file.endsWith('.jsx'))
31
+ return 'jsx'
32
+ return /\.[cm]?js$/.test(file) ? 'js' : 'ts'
33
+ }
34
+
24
35
  // The files outside node_modules that `entry` imports, transitively, `entry` left out.
25
36
  export function localImports(entry: string): string[] {
26
- const transpiler = new Bun.Transpiler({ loader: 'tsx' })
37
+ const transpilers = new Map<ScanLoader, Bun.Transpiler>()
38
+ const importsOf = (file: string, source: string): string[] => {
39
+ const loader = scanLoader(file)
40
+ let transpiler = transpilers.get(loader)
41
+ if (transpiler === undefined) {
42
+ transpiler = new Bun.Transpiler({ loader })
43
+ transpilers.set(loader, transpiler)
44
+ }
45
+ try {
46
+ return transpiler.scanImports(source).map(entry => entry.path)
47
+ }
48
+ catch {
49
+ return [] // a syntax error, which the config load reports itself
50
+ }
51
+ }
27
52
  const seen = new Set<string>([entry])
28
53
  const queue = [entry]
29
54
  for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
@@ -34,7 +59,7 @@ export function localImports(entry: string): string[] {
34
59
  catch {
35
60
  continue // deleted since it was resolved
36
61
  }
37
- for (const { path } of transpiler.scanImports(source)) {
62
+ for (const path of importsOf(file, source)) {
38
63
  let resolved: string
39
64
  try {
40
65
  resolved = Bun.resolveSync(path, dirname(file))
@@ -54,6 +79,33 @@ export function localImports(entry: string): string[] {
54
79
 
55
80
  const isInsideDir = (parent: string, target: string): boolean => isInside(parent, target, { orSame: true })
56
81
 
82
+ /** Watches files through their parent directory (filtering by basename) so atomic rename saves on Linux keep firing. */
83
+ function watchFilesByParentDir(files: Iterable<string>, onMatch: (filename: string) => void, out: FSWatcher[]): void {
84
+ const byDir = new Map<string, Set<string>>()
85
+ for (const file of files) {
86
+ const dir = dirname(file)
87
+ if (!existsSync(dir))
88
+ continue
89
+ let names = byDir.get(dir)
90
+ if (names === undefined) {
91
+ names = new Set()
92
+ byDir.set(dir, names)
93
+ }
94
+ names.add(basename(file))
95
+ }
96
+ for (const [dir, names] of byDir) {
97
+ try {
98
+ out.push(watch(dir, (_ev, filename) => {
99
+ if (typeof filename === 'string' && names.has(filename))
100
+ onMatch(filename)
101
+ }))
102
+ }
103
+ catch (err) {
104
+ console.warn(`[prunelle dev] could not watch ${dir}: ${err instanceof Error ? err.message : String(err)}`)
105
+ }
106
+ }
107
+ }
108
+
57
109
  export interface DevWatcherOptions {
58
110
  root: string
59
111
  devRoot: string
@@ -67,6 +119,7 @@ export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }
67
119
  const dirWatchers = new Map<string, FSWatcher>()
68
120
  const pluginWatchers: FSWatcher[] = []
69
121
  const graphWatchers = new Map<string, FSWatcher>()
122
+ const rootGraphFiles = new Set<string>()
70
123
  let activeRoutesDir = resolve(root, routesDir ?? 'src/routes')
71
124
  let activePublicDir = resolve(root, 'public')
72
125
  let builtPublic = new Set<string>()
@@ -120,6 +173,7 @@ export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }
120
173
  w.close()
121
174
  pluginWatchers.length = 0
122
175
  const seen = new Set<string>(dirWatchers.keys())
176
+ const watchFiles: string[] = []
123
177
  const watchCtx = createAppContext({ root, outDir: devRoot, publicDir: activePublicDir, assetPrefix, site: cfg.site, dev: true })
124
178
  for (const plugin of resolvePlugins(cfg.plugins)) {
125
179
  const paths = runWithAppContext(watchCtx, () =>
@@ -129,14 +183,18 @@ export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }
129
183
  if (seen.has(abs) || !existsSync(abs))
130
184
  continue
131
185
  seen.add(abs)
132
- const isDir = statSync(abs).isDirectory()
133
- pluginWatchers.push(watch(abs, isDir ? { recursive: true } : {}, () => schedule('full')))
186
+ if (statSync(abs).isDirectory())
187
+ pluginWatchers.push(watch(abs, { recursive: true }, () => schedule('full')))
188
+ else
189
+ watchFiles.push(abs)
134
190
  }
135
191
  }
192
+ watchFilesByParentDir(watchFiles, () => schedule('full'), pluginWatchers)
136
193
  },
137
194
 
138
195
  syncBuild(watchedFiles: ReadonlySet<string>, publicFiles: readonly string[]): void {
139
196
  builtPublic = new Set(publicFiles)
197
+ rootGraphFiles.clear()
140
198
  const nextDirs = new Set<string>()
141
199
  let realRoot: string
142
200
  try {
@@ -151,10 +209,11 @@ export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }
151
209
  if (isInsideDir(devRoot, file) || isInsideDir(join(root, '.prunelle-cache'), file))
152
210
  continue
153
211
  const dir = dirname(file)
154
- // Root is already watched non-recursively for `prunelle.config.ts`; skip if it's only prunelle.config.ts itself.
212
+ // Never watch unfiltered project root (which would fire on .prunelle-dev, .prunelle-cache, lockfiles); filter to tracked root filenames in watchRoot.
155
213
  if (dir === root || dir === realRoot) {
156
- if (file === join(root, 'prunelle.config.ts') || file === join(realRoot, 'prunelle.config.ts'))
157
- continue
214
+ if (file !== join(root, 'prunelle.config.ts') && file !== join(realRoot, 'prunelle.config.ts'))
215
+ rootGraphFiles.add(basename(file))
216
+ continue
158
217
  }
159
218
  if (isCoveredByStaticWatchers(dir))
160
219
  continue
@@ -181,17 +240,19 @@ export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }
181
240
  }
182
241
  },
183
242
 
184
- // The root, non-recursively: prunelle.config.ts, and a public, routes or src folder created after startup; with `configImports`, the local files prunelle.config.ts imports too.
243
+ // The root, non-recursively: prunelle.config.ts, tracked root graph files, and a public, routes or src folder created after startup; with `configImports`, the local files prunelle.config.ts imports too.
185
244
  watchRoot(currentConfig: () => PrunelleConfig, configImports: boolean): void {
186
- if (configImports) {
187
- for (const file of localImports(join(root, 'prunelle.config.ts')))
188
- rootWatchers.push(watch(file, () => schedule('config')))
189
- }
245
+ if (configImports)
246
+ watchFilesByParentDir(localImports(join(root, 'prunelle.config.ts')), () => schedule('config'), rootWatchers)
190
247
  rootWatchers.push(watch(root, (_ev, filename) => {
191
248
  if (filename === 'prunelle.config.ts') {
192
249
  schedule('config')
193
250
  return
194
251
  }
252
+ if (typeof filename === 'string' && rootGraphFiles.has(filename)) {
253
+ schedule(srcChangeKind(filename))
254
+ return
255
+ }
195
256
  const changed = typeof filename === 'string' && filename !== '' ? resolve(root, filename) : undefined
196
257
  for (const dir of [activePublicDir, activeRoutesDir, srcDir]) {
197
258
  if (!dirWatchers.has(dir) && existsSync(dir) && (changed === undefined || isInsideDir(changed, dir))) {
package/src/dom/action.ts CHANGED
@@ -58,28 +58,26 @@ export function useAction<Input, Output>(
58
58
  if (pending.peek())
59
59
  return undefined
60
60
  set(true)
61
+ let res: ActionResult<Output>
61
62
  try {
62
- const res = await (action as ClientAction<Input, Output>)(input)
63
- if (!res.ok) {
64
- set(false, res.error, res.fieldErrors)
65
- options.onError?.(res)
66
- return res
67
- }
68
- batch(() => {
69
- data.value = res.data
70
- pending.value = false
71
- })
72
- if (options.reset && formEl)
73
- formEl.reset()
74
- await options.onSuccess?.(res.data, formEl)
75
- return res
63
+ res = await (action as ClientAction<Input, Output>)(input)
76
64
  }
77
65
  catch (err) {
78
- const failed = fail(0, errMsg(err))
79
- set(false, failed.error)
80
- options.onError?.(failed)
81
- return failed
66
+ res = fail(0, errMsg(err))
67
+ }
68
+ if (!res.ok) {
69
+ set(false, res.error, res.fieldErrors)
70
+ options.onError?.(res)
71
+ return res
82
72
  }
73
+ batch(() => {
74
+ data.value = res.data
75
+ pending.value = false
76
+ })
77
+ if (options.reset && formEl)
78
+ formEl.reset()
79
+ await options.onSuccess?.(res.data, formEl)
80
+ return res
83
81
  }
84
82
 
85
83
  return {
@@ -88,7 +86,10 @@ export function useAction<Input, Output>(
88
86
  fieldErrors,
89
87
  data,
90
88
  get action() {
91
- return action.url || String(action)
89
+ const u = action.url || String(action)
90
+ if ('__pruAction' in action)
91
+ (globalThis as { __pruAct?: (url: string, act: unknown) => void }).__pruAct?.(u, action)
92
+ return u
92
93
  },
93
94
  onSubmit(event) {
94
95
  event.preventDefault()
@@ -105,6 +106,21 @@ export function useAction<Input, Output>(
105
106
  }
106
107
  }
107
108
 
109
+ function isSameDocHash(to: string): boolean {
110
+ if (to.startsWith('#'))
111
+ return true
112
+ if (!to.includes('#') || typeof location.href !== 'string')
113
+ return false
114
+ try {
115
+ const cur = new URL(location.href)
116
+ const next = new URL(to, cur)
117
+ return next.origin === cur.origin && next.pathname === cur.pathname && next.search === cur.search
118
+ }
119
+ catch {
120
+ return false
121
+ }
122
+ }
123
+
108
124
  export function actionStub<Input = unknown, Output = unknown>(url: string): ClientAction<Input, Output> {
109
125
  const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
110
126
  const isForm = typeof FormData !== 'undefined' && input instanceof FormData
@@ -131,8 +147,18 @@ export function actionStub<Input = unknown, Output = unknown>(url: string): Clie
131
147
  const to = h.get('x-pru-redirect') || (res.status > 299 && res.status < 400 && h.get('location')) || (res.redirected && res.url)
132
148
  if (to) {
133
149
  if (typeof location !== 'undefined') {
134
- location.assign(to)
135
- return new Promise<never>(() => {})
150
+ try {
151
+ if (typeof location.href === 'string' && h.get('x-pru-redirect-external') !== '1' && new URL(to, location.href).origin !== new URL(location.href).origin)
152
+ throw new Error('Redirect to another site refused')
153
+ location.assign(to)
154
+ }
155
+ catch (err) {
156
+ return fail(0, errMsg(err))
157
+ }
158
+ if (isSameDocHash(to))
159
+ return { ok: true, data: undefined as Output }
160
+ // A navigation unloads the page first; when none happens (a refused prompt, a download) the caller gets an error instead of waiting forever.
161
+ return new Promise<ActionResult<Output>>(resolve => setTimeout(() => resolve(fail(0, 'Navigation did not complete')), 10000))
136
162
  }
137
163
  return fail(res.status || 302, to)
138
164
  }
package/src/dom/attrs.ts CHANGED
@@ -24,13 +24,22 @@ export function setClass(el: Element, value: unknown): void {
24
24
  }
25
25
  }
26
26
 
27
+ const XLINK_NS = 'http://www.w3.org/1999/xlink'
28
+
27
29
  export function setAttr(el: Element, name: string, value: unknown): void {
28
30
  if (isBlockedAttr(name))
29
31
  return
30
32
  if (process.env.NODE_ENV !== 'production')
31
33
  assertRenderable(value, name)
34
+ const isXlink = name === 'xlink:href'
35
+ const remove = (): void => {
36
+ if (isXlink)
37
+ el.removeAttributeNS(XLINK_NS, 'href')
38
+ else
39
+ el.removeAttribute(name)
40
+ }
32
41
  if (value == null) {
33
- el.removeAttribute(name)
42
+ remove()
34
43
  }
35
44
  else if (typeof value === 'boolean') {
36
45
  if (isStringBoolAttr(name))
@@ -38,12 +47,15 @@ export function setAttr(el: Element, name: string, value: unknown): void {
38
47
  else if (value)
39
48
  el.setAttribute(name, '')
40
49
  else
41
- el.removeAttribute(name)
50
+ remove()
42
51
  }
43
52
  else if (isUnsafeUrlAttr(name, value, el.tagName)) {
44
53
  if (process.env.NODE_ENV !== 'production')
45
54
  console.warn(`prunelle: dropped unsafe URL on <${el.tagName.toLowerCase()} ${name}>.`)
46
- el.removeAttribute(name)
55
+ remove()
56
+ }
57
+ else if (isXlink) {
58
+ el.setAttributeNS(XLINK_NS, name, String(value))
47
59
  }
48
60
  else {
49
61
  el.setAttribute(name, String(value))
package/src/dom/extras.ts CHANGED
@@ -4,10 +4,9 @@
4
4
  import type { CatchProps } from '../context'
5
5
  import type { Owned } from '../reactivity/graph'
6
6
  import type { Owner } from '../reactivity/index'
7
- import { DOM_PROPS } from '../attrs'
7
+ import { DOM_PROPS, isBlockedAttr } from '../attrs'
8
8
  import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, onEffectError, runOwned, runWithOwner, signal, untrack } from '../reactivity/index'
9
9
  import { assertRenderable } from '../unrenderable'
10
- import { isBlockedAttr } from '../attrs'
11
10
  import { setAttr, setClass, setProp, setStyle } from './attrs'
12
11
  import { claimInsert } from './claim'
13
12
  import { claimRange, delegate, hydrateCursor, isHydrating, moveCursor, skipRange } from './index'
@@ -61,7 +60,7 @@ export function propDefault<T>(fn: () => T, now: boolean): () => T {
61
60
  let done = false
62
61
  const get = (): T => {
63
62
  if (!done) {
64
- value = fn()
63
+ value = untrack(fn)
65
64
  done = true
66
65
  }
67
66
  return value
@@ -89,7 +88,17 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
89
88
  let lastRef: unknown
90
89
  const elRec = el as unknown as Record<string, unknown>
91
90
  // Delegated events share document-level dispatch with compiled handlers so stopPropagation() runs child->parent.
92
- const delegatedTypes = new Set<string>()
91
+ // Stores [written handler, handler present before spread] so static handlers are restored or left intact.
92
+ const delegated = new Map<string, [unknown, unknown]>()
93
+ const releaseDelegated = (type: string, entry: [unknown, unknown]): void => {
94
+ const key = `$$${type}`
95
+ if (elRec[key] === entry[0]) {
96
+ if (entry[1] !== undefined)
97
+ elRec[key] = entry[1]
98
+ else
99
+ delete elRec[key]
100
+ }
101
+ }
93
102
  // One listener per non-delegated event type, calling whichever handler the props hold now.
94
103
  const handlers = new Map<string, (e: Event) => void>()
95
104
  const listen = (e: Event): void => {
@@ -102,9 +111,9 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
102
111
  for (const type of handlers.keys())
103
112
  el.removeEventListener(type, listen)
104
113
  handlers.clear()
105
- for (const type of delegatedTypes)
106
- delete elRec[`$$${type}`]
107
- delegatedTypes.clear()
114
+ for (const [type, entry] of delegated)
115
+ releaseDelegated(type, entry)
116
+ delegated.clear()
108
117
  })
109
118
 
110
119
  effect(() => {
@@ -127,7 +136,7 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
127
136
  if (!isBlockedAttr(name)) {
128
137
  if (DOM_PROPS.has(name))
129
138
  setProp(el, name, name === 'value' ? '' : false)
130
- el.removeAttribute(name)
139
+ setAttr(el, name, null)
131
140
  }
132
141
  }
133
142
  }
@@ -151,11 +160,17 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
151
160
  const type = event[1]!.toLowerCase()
152
161
  types.add(type)
153
162
  if (DELEGATED_EVENTS.has(type)) {
154
- if (!delegatedTypes.has(type)) {
155
- delegatedTypes.add(type)
163
+ const key = `$$${type}`
164
+ const entry = delegated.get(type)
165
+ if (entry === undefined) {
166
+ delegated.set(type, [v, elRec[key]])
156
167
  delegate([type])
168
+ elRec[key] = v
169
+ }
170
+ else if (elRec[key] === entry[0]) {
171
+ elRec[key] = v
172
+ entry[0] = v
157
173
  }
158
- elRec[`$$${type}`] = v
159
174
  }
160
175
  else {
161
176
  if (!handlers.has(type))
@@ -177,10 +192,10 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
177
192
  setAttr(el, name, v)
178
193
  }
179
194
 
180
- for (const type of delegatedTypes) {
195
+ for (const [type, entry] of delegated) {
181
196
  if (!types.has(type)) {
182
- delegatedTypes.delete(type)
183
- delete elRec[`$$${type}`]
197
+ delegated.delete(type)
198
+ releaseDelegated(type, entry)
184
199
  }
185
200
  }
186
201
  for (const type of handlers.keys()) {
package/src/dom/index.ts CHANGED
@@ -42,9 +42,9 @@ export function hydrate(container: Element, render: () => Node | DocumentFragmen
42
42
  hydrateRoot = container
43
43
 
44
44
  try {
45
- runWithOwner(owner, () => {
46
- render()
47
- })
45
+ const node = runWithOwner(owner, render)
46
+ if (node !== null && node.parentNode === null)
47
+ container.appendChild(node)
48
48
  }
49
49
  catch (err) {
50
50
  disposeOwner(owner)
@@ -165,12 +165,30 @@ export function fragText(data: string, dynamic?: boolean): Text {
165
165
  return document.createTextNode(data)
166
166
  }
167
167
 
168
- export function frag(...nodes: Node[]): Node | null {
169
- if (hydrating)
168
+ export function frag(...nodes: (Node | null)[]): Node | null {
169
+ const first = nodes.find(n => n?.parentNode && n.parentNode.nodeType !== 11)
170
+ if (first) {
171
+ const parent = first.parentNode!
172
+ let prev: Node | null = null
173
+ for (const n of nodes) {
174
+ if (!n)
175
+ continue
176
+ if (n.parentNode === parent) {
177
+ prev = n
178
+ continue
179
+ }
180
+ const tail = n.nodeType === 11 ? n.lastChild : n
181
+ parent.insertBefore(n, prev ? prev.nextSibling : first)
182
+ if (prev && tail)
183
+ prev = tail
184
+ }
170
185
  return null
171
- const f = document.createDocumentFragment()
172
- for (let i = 0; i < nodes.length; i++)
173
- f.appendChild(nodes[i]!)
186
+ }
187
+ let f: DocumentFragment | null = null
188
+ for (const n of nodes) {
189
+ if (n)
190
+ (f ??= document.createDocumentFragment()).appendChild(n)
191
+ }
174
192
  return f
175
193
  }
176
194
 
@@ -235,6 +253,7 @@ function dispatchEvent(event: Event): void {
235
253
  let current: EventTarget | null = null
236
254
  const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
237
255
  Object.defineProperty(event, 'currentTarget', { configurable: true, get: () => current })
256
+ const errors: unknown[] = []
238
257
 
239
258
  try {
240
259
  const path = event.composedPath?.()
@@ -245,9 +264,14 @@ function dispatchEvent(event: Event): void {
245
264
  const handler = node[key]
246
265
  if (typeof handler === 'function') {
247
266
  current = node
248
- batch(() => handler(event))
267
+ try {
268
+ batch(() => handler(event))
269
+ }
270
+ catch (err) {
271
+ errors.push(err)
272
+ }
249
273
  if (event.cancelBubble)
250
- return
274
+ break
251
275
  }
252
276
  node = (usePath ? path[++i] : (node as unknown as Node).parentNode) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
253
277
  }
@@ -258,6 +282,11 @@ function dispatchEvent(event: Event): void {
258
282
  else
259
283
  delete (event as unknown as Record<string, unknown>).currentTarget
260
284
  }
285
+ // Every handler ran: the first error is thrown as before, the others are reported.
286
+ for (let i = 1; i < errors.length; i++)
287
+ reportError(errors[i])
288
+ if (errors.length > 0)
289
+ throw errors[0]
261
290
  }
262
291
 
263
292
  export function delegate(events: string[]): void {