prunelle 0.8.0 → 0.10.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 (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +94 -136
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
package/src/dev/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { Server } from 'bun'
5
5
  import type { BuildCacheStats } from '../build/graph'
6
+
6
7
  import type { PrunelleApp } from '../server/index'
7
8
  import type { TrustProxy } from '../server/security'
8
9
  import type { RecycleReason } from './protocol'
@@ -17,6 +18,7 @@ import { createServer } from '../server/index'
17
18
  import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
18
19
  import { createModuleStore } from './modules'
19
20
  import { createDevHostCheck } from './host-check'
21
+ import { createHotSwaps } from './hot-islands'
20
22
  import { handleOpenEditorRequest } from './open-editor'
21
23
  import { DEV_CLIENT_IP_HEADER } from './protocol'
22
24
  import { createRebuildQueue } from './queue'
@@ -41,6 +43,24 @@ export interface DevServerOptions {
41
43
 
42
44
  const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
43
45
 
46
+ function allowedOriginsOf(cfg: { site?: string | undefined, trustedOrigins?: readonly string[] | undefined }): string[] {
47
+ return [cfg.site, ...cfg.trustedOrigins ?? []].filter((o): o is string => typeof o === 'string' && o !== '')
48
+ }
49
+
50
+ async function finishDevStop(queue: { stop: () => Promise<void> }, app: PrunelleApp | undefined, devRoot: string, recycled: boolean): Promise<void> {
51
+ await queue.stop()
52
+ try {
53
+ await app?.dispose?.()
54
+ }
55
+ catch (err) {
56
+ console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
57
+ }
58
+ if (recycled)
59
+ cleanDevArtifacts(devRoot)
60
+ else
61
+ rmSync(devRoot, { recursive: true, force: true })
62
+ }
63
+
44
64
  /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.jsonl` intact across child recycles. */
45
65
  function cleanDevArtifacts(devRoot: string): void {
46
66
  if (!existsSync(devRoot))
@@ -109,6 +129,7 @@ async function handleAppFetch(
109
129
  export async function devServer(options: DevServerOptions): Promise<{
110
130
  url: string
111
131
  assetPrefix: string
132
+ allowedOrigins: readonly string[]
112
133
  stop: () => Promise<void>
113
134
  rebuild: () => Promise<void>
114
135
  stats: () => BuildCacheStats
@@ -144,6 +165,7 @@ export async function devServer(options: DevServerOptions): Promise<{
144
165
 
145
166
  let buildNum = 0
146
167
  let current: { app: PrunelleApp, outDir: string } | undefined
168
+ const hotSwaps = createHotSwaps(buildCache)
147
169
  let lastError: string | undefined
148
170
  let stopped = false
149
171
 
@@ -161,14 +183,14 @@ export async function devServer(options: DevServerOptions): Promise<{
161
183
  async function runSingleBuild({ cssOnly, publicOnly, resetCache, reloadAll }: PendingBuild): Promise<void> {
162
184
  if (stopped)
163
185
  return
164
- const hadError = lastError !== undefined
165
- const hadApp = current !== undefined
186
+ const hadApp = current !== undefined && lastError === undefined
166
187
  const n = buildNum + 1
167
188
  const outDir = `.prunelle-dev/b${n}`
168
189
  const t0 = performance.now()
190
+ hotSwaps.start()
169
191
  try {
170
192
  // An edited `public/` file only needs the app's file table, and its ETag, built again.
171
- if (publicOnly && current !== undefined && !hadError) {
193
+ if (publicOnly && current !== undefined && hadApp) {
172
194
  await swapApp(current.outDir)
173
195
  broadcast('reload')
174
196
  return
@@ -199,7 +221,8 @@ export async function devServer(options: DevServerOptions): Promise<{
199
221
  if (n > 2)
200
222
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
201
223
  console.log(`[prunelle dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
202
- broadcast(cssOnly && hadApp && !hadError && manifest.styles.length > 0 ? `css:${JSON.stringify(manifest.styles)}` : 'reload')
224
+ const swaps = hotSwaps.land(manifest, hadApp && !resetCache && !reloadAll)
225
+ broadcast(cssOnly && hadApp && manifest.styles.length > 0 ? `css:${JSON.stringify(manifest.styles)}` : swaps !== undefined ? `island:${JSON.stringify(swaps)}` : 'reload')
203
226
  if (n > 1 && recycle !== undefined && options.maxRssMb !== undefined && process.memoryUsage().rss > options.maxRssMb * 1024 * 1024)
204
227
  recycle('memory')
205
228
  }
@@ -227,8 +250,9 @@ export async function devServer(options: DevServerOptions): Promise<{
227
250
  }
228
251
 
229
252
  const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
253
+ const allowedOrigins = allowedOriginsOf(activeCfg)
230
254
  // Behind the supervisor's socket, the supervisor has checked the Host already.
231
- const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, [initialCfg.site, ...initialCfg.trustedOrigins ?? []]) : undefined
255
+ const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, allowedOrigins) : undefined
232
256
  const { server, url } = startDevHttpServer(
233
257
  options,
234
258
  runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
@@ -240,6 +264,7 @@ export async function devServer(options: DevServerOptions): Promise<{
240
264
  return {
241
265
  url,
242
266
  assetPrefix: activeAssetPrefix,
267
+ allowedOrigins,
243
268
  rebuild: () => queue.now(),
244
269
  stats: () => ({ ...buildCache.stats }),
245
270
  stop() {
@@ -249,19 +274,7 @@ export async function devServer(options: DevServerOptions): Promise<{
249
274
  hub?.close()
250
275
  watchers.close()
251
276
  server.stop(true)
252
- stopPromise = (async () => {
253
- await queue.stop()
254
- try {
255
- await current?.app.dispose?.()
256
- }
257
- catch (err) {
258
- console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
259
- }
260
- if (recycled)
261
- cleanDevArtifacts(devRoot)
262
- else
263
- rmSync(devRoot, { recursive: true, force: true })
264
- })()
277
+ stopPromise = finishDevStop(queue, current?.app, devRoot, recycled)
265
278
  return stopPromise
266
279
  },
267
280
  }
@@ -19,6 +19,6 @@ export interface DevChildOptions {
19
19
  }
20
20
 
21
21
  export type DevChildMessage =
22
- | { t: 'ready', assetPrefix: string }
22
+ | { t: 'ready', assetPrefix: string, allowedOrigins?: readonly string[] | undefined }
23
23
  | { t: 'event', payload: string }
24
24
  | { t: 'recycle', reason: RecycleReason }
package/src/dev/queue.ts CHANGED
@@ -49,8 +49,9 @@ export function createRebuildQueue(run: (build: PendingBuild) => Promise<void>)
49
49
  }
50
50
 
51
51
  return {
52
- schedule(kind: ChangeKind): void {
53
- if (stopped)
52
+ /** Takes no kind for a change no build reads (a `.d.ts`). */
53
+ schedule(kind: ChangeKind | undefined): void {
54
+ if (stopped || kind === undefined)
54
55
  return
55
56
  if (kind === 'config')
56
57
  next.resetCache = true
package/src/dev/reload.ts CHANGED
@@ -10,7 +10,7 @@ export function makeDevReloadAssets(assetPrefix: string): { script: string, hash
10
10
  const prefix = assetPrefix.replace(/\/$/, '')
11
11
  const eventsPath = `${prefix}/dev-events`
12
12
  const openEditorPath = `${prefix}/${OPEN_EDITOR_SUBPATH}`
13
- const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map();for(const u of urls){const k=stem(u);byStem.set(k,byStem.has(k)?null:u);}const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m===null){location.reload();return;}if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};document.addEventListener('click',e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.button!==0)return;const t=e.target instanceof Element?e.target.closest('[data-pru-src]'):null;if(!t)return;e.preventDefault();e.stopImmediatePropagation();fetch(${JSON.stringify(openEditorPath)},{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({src:t.getAttribute('data-pru-src')})}).catch(()=>{});},true);})();`
13
+ const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('island:')){const m=JSON.parse(e.data.slice(7));Promise.all([...document.querySelectorAll('pru-island[c]')].filter(i=>m[i.getAttribute('c')]).map(async i=>i._h(m[i.getAttribute('c')]))).catch(()=>location.reload());return;}if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map();for(const u of urls){const k=stem(u);byStem.set(k,byStem.has(k)?null:u);}const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m===null){location.reload();return;}if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};document.addEventListener('click',e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.button!==0)return;const t=e.target instanceof Element?e.target.closest('[data-pru-src]'):null;if(!t)return;e.preventDefault();e.stopImmediatePropagation();fetch(${JSON.stringify(openEditorPath)},{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({src:t.getAttribute('data-pru-src')})}).catch(()=>{});},true);})();`
14
14
  const hash = cspSha256(js)
15
15
  return { script: `<script>${js}</script>`, hash, eventsPath, openEditorPath }
16
16
  }
@@ -55,7 +55,10 @@ export function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScrip
55
55
  return
56
56
  }
57
57
  if (text.length > KEEP) {
58
- const split = text.length - KEEP
58
+ let split = text.length - KEEP
59
+ // A cut between the halves of an emoji would encode each half as U+FFFD.
60
+ if (text.charCodeAt(split) >= 0xDC00 && text.charCodeAt(split) <= 0xDFFF)
61
+ split--
59
62
  controller.enqueue(encoder.encode(text.slice(0, split)))
60
63
  tail = text.slice(split)
61
64
  }
@@ -62,6 +62,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
62
62
  const socketDir = mkdtempSync(join(tmpdir(), 'prunelle-dev-sockets-'))
63
63
  const hub = createReloadHub()
64
64
  let reloadAssets = makeDevReloadAssets('/_pru')
65
+ let checkHost = createDevHostCheck(options.hostname, options.allowedOrigins ?? [])
65
66
  let spawned = 0
66
67
  let live: Child | undefined
67
68
  let crashed: string | undefined
@@ -95,6 +96,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
95
96
  hub.broadcast(message.payload)
96
97
  else if (message.t === 'ready') {
97
98
  reloadAssets = makeDevReloadAssets(message.assetPrefix)
99
+ if (message.allowedOrigins !== undefined)
100
+ checkHost = createDevHostCheck(options.hostname, [...options.allowedOrigins ?? [], ...message.allowedOrigins])
98
101
  crashed = undefined
99
102
  recordDevCrashError(root, undefined)
100
103
  onReady(child)
@@ -144,7 +147,6 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
144
147
  ready = spawnChild()
145
148
  await ready
146
149
 
147
- const checkHost = createDevHostCheck(options.hostname, options.allowedOrigins ?? [])
148
150
  const server = Bun.serve({
149
151
  port: options.port ?? 3000,
150
152
  hostname: options.hostname ?? '127.0.0.1',
@@ -15,7 +15,10 @@ type PrunelleConfig = Awaited<ReturnType<typeof loadConfig>>
15
15
  // A source edit changes the bundled bytes; any other file (content, data, public/) may be read when a module loads.
16
16
  const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|css)$/
17
17
 
18
- export function srcChangeKind(name: string): ChangeKind {
18
+ export function srcChangeKind(name: string): ChangeKind | undefined {
19
+ // A declaration file changes no bundled byte: prunelle-routes.d.ts, which a build writes, must not set off the next one.
20
+ if (name.endsWith('.d.ts'))
21
+ return undefined
19
22
  if (name.endsWith('.css') && !name.endsWith('.module.css'))
20
23
  return 'css'
21
24
  return CODE_FILE_RE.test(name) ? 'code' : 'full'
@@ -111,10 +114,11 @@ export interface DevWatcherOptions {
111
114
  devRoot: string
112
115
  srcDir: string
113
116
  routesDir: string | undefined
114
- schedule: (kind: ChangeKind) => void
117
+ schedule: (kind: ChangeKind | undefined) => void
115
118
  }
116
119
 
117
120
  export function createDevWatchers({ root, devRoot, srcDir, routesDir, schedule }: DevWatcherOptions) {
121
+
118
122
  const rootWatchers: FSWatcher[] = []
119
123
  const dirWatchers = new Map<string, FSWatcher>()
120
124
  const pluginWatchers: FSWatcher[] = []
package/src/dom/action.ts CHANGED
@@ -1,17 +1,24 @@
1
1
  // Tiny client-side action stub (~300 B gzip, 0 B when no island imports an action).
2
2
 
3
- import type { ReadonlySignal } from '../reactivity/index'
3
+ import type { ReadonlySignal, Signal } from '../reactivity/index'
4
4
  import type { ActionResult, ServerAction } from '../server/action'
5
- import { batch, signal } from '../reactivity/index'
5
+ import { batch, recordWrites, signal } from '../reactivity/index'
6
+
7
+ export interface ClientActionOptions {
8
+ signal?: AbortSignal | undefined
9
+ onProgress?: ((fraction: number) => void) | undefined
10
+ }
6
11
 
7
12
  export interface ClientAction<Input, Output> {
8
- /** A FormData input is sent as multipart, so it can carry files. */
9
- (input: Input | FormData): Promise<ActionResult<Output>>
13
+ /** A FormData input is sent as multipart, so it can carry files; `onProgress` is called with the fraction uploaded (0 to 1) when it holds a `File`. */
14
+ (input: Input | FormData, options?: ((fraction: number) => void) | ClientActionOptions): Promise<ActionResult<Output>>
10
15
  readonly url: string
11
16
  toString(): string
12
17
  }
13
18
 
14
- export interface UseActionOptions<Output> {
19
+ export interface UseActionOptions<Output, Input = unknown> {
20
+ /** Changes the page as the request leaves, by writing signals or stores: the writes are undone if the action fails. */
21
+ optimistic?: ((input: Input | FormData) => void) | undefined
15
22
  /** Reset the submitted `<form>` element after a successful submission (default: false). */
16
23
  reset?: boolean | undefined
17
24
  /** Called with the typed action `data` when the action succeeds (`res.ok === true`). */
@@ -25,6 +32,8 @@ export interface ActionForm<Input, Output> {
25
32
  readonly error: ReadonlySignal<string>
26
33
  readonly fieldErrors: ReadonlySignal<Record<string, string>>
27
34
  readonly data: ReadonlySignal<Output | undefined>
35
+ /** The fraction uploaded (0 to 1) of a submit whose FormData holds a `File`; 0 otherwise, and again when the submit ends. */
36
+ readonly progress: ReadonlySignal<number>
28
37
  /** Action URL for progressive `<form action={form.action} method="post">` (or pass the action directly). */
29
38
  readonly action: string
30
39
  /** Progressive `<form onSubmit={form.onSubmit}>` handler that submits `FormData` via fetch when JS is loaded. */
@@ -38,15 +47,75 @@ export interface ActionForm<Input, Output> {
38
47
  const errMsg = (e: unknown): string => e instanceof Error ? e.message : String(e)
39
48
  const fail = (status: number, error: string) => ({ ok: false as const, status, error })
40
49
 
50
+ // An optimistic change: `r` makes it, `u` holds the undos of its last run, `d` is set once its action succeeded. The names are short because they ship to the browser.
51
+ interface Change { readonly r: () => void, u: (() => void)[], d?: boolean }
52
+
53
+ // The optimistic changes of the page still in flight, oldest first. One that fails is undone with every change made after it, which are then made again over what is left, so each keeps only its own effect.
54
+ const changes: Change[] = []
55
+
56
+ function undo(change: Change): void {
57
+ for (const restore of change.u.reverse())
58
+ restore()
59
+ }
60
+
61
+ function apply(change: Change): void {
62
+ let ret: unknown
63
+ try {
64
+ ret = recordWrites(change.r, change.u = [])
65
+ }
66
+ catch (err) {
67
+ undo(change)
68
+ throw err
69
+ }
70
+ // Writes after an await would land outside the recording and never be undone.
71
+ if (ret instanceof Promise) {
72
+ undo(change)
73
+ throw new Error('prunelle: useAction\'s `optimistic` returned a promise: change the page synchronously, and await in `onSuccess`.')
74
+ }
75
+ }
76
+
77
+ function settle(change: Change, ok: boolean, keep?: boolean): void {
78
+ if (!(change.d = ok)) {
79
+ batch(() => {
80
+ const later = changes.splice(changes.indexOf(change)).reverse()
81
+ later.forEach(undo)
82
+ later.pop()
83
+ for (const again of later.reverse()) {
84
+ apply(again)
85
+ changes.push(again)
86
+ }
87
+ })
88
+ }
89
+ else if (!keep) {
90
+ // Once `onSuccess` will reconcile confirmed state, never undo it or replay this stale draft over it if an earlier concurrent action fails.
91
+ const i = changes.indexOf(change)
92
+ if (i >= 0)
93
+ changes.splice(i, 1)
94
+ }
95
+ // A change that succeeded without `onSuccess` is kept for replay until no earlier one can fail.
96
+ while (changes[0]?.d)
97
+ changes.shift()
98
+ }
99
+
100
+ declare const PRUNELLE_FIELD_MARKS: string | undefined
101
+ // The XHR sender of an upload is fetched only when the app reads `progress`: the client build names its file through `PRUNELLE_UPLOAD`.
102
+ declare const PRUNELLE_UPLOAD: string | undefined
103
+
104
+ // The fields of a failed submit tied to their messages, and undone at the next submit, by a module fetched only then: the client build names its file through `PRUNELLE_FIELD_MARKS`.
105
+ const markFields = (form: HTMLFormElement, errors?: Record<string, string>): Promise<void> =>
106
+ (typeof PRUNELLE_FIELD_MARKS === 'undefined' ? import('./field-marks') : import(PRUNELLE_FIELD_MARKS) as Promise<typeof import('./field-marks')>).then(m => m.markFields(form, errors))
107
+
41
108
  /** Reactive progressive-enhancement form controller for a Prunelle server `action()`. */
42
109
  export function useAction<Input, Output>(
43
110
  action: ClientAction<Input, Output> | ServerAction<Input, Output>,
44
- options: UseActionOptions<Output> = {},
111
+ options: UseActionOptions<Output, Input> = {},
45
112
  ): ActionForm<Input, Output> {
46
113
  const pending = signal(false)
47
114
  const error = signal('')
48
115
  const fieldErrors = signal<Record<string, string>>({})
49
116
  const data = signal<Output | undefined>(undefined)
117
+ // Made at the first read, so a page that never shows the progress carries no signal for it.
118
+ let progress: Signal<number> | undefined
50
119
 
51
120
  const set = (p: boolean, e = '', f: Record<string, string> = {}) => batch(() => {
52
121
  pending.value = p
@@ -57,16 +126,28 @@ export function useAction<Input, Output>(
57
126
  const submit = async (input: Input | FormData, formEl?: HTMLFormElement): Promise<ActionResult<Output> | undefined> => {
58
127
  if (pending.peek())
59
128
  return undefined
129
+ const optimistic = options.optimistic
130
+ const change: Change | undefined = optimistic && { r: () => optimistic(input), u: [] }
131
+ if (change) {
132
+ apply(change)
133
+ changes.push(change)
134
+ }
60
135
  set(true)
136
+ if (formEl?.querySelector('[data-pru-err]'))
137
+ await markFields(formEl)
61
138
  let res: ActionResult<Output>
62
139
  try {
63
- res = await (action as ClientAction<Input, Output>)(input)
140
+ res = await (action as ClientAction<Input, Output>)(input, progress && (f => progress!.value = f))
64
141
  }
65
142
  catch (err) {
66
143
  res = fail(0, errMsg(err))
67
144
  }
145
+ if (change)
146
+ settle(change, res.ok, !options.onSuccess)
68
147
  if (!res.ok) {
69
148
  set(false, res.error, res.fieldErrors)
149
+ if (formEl && res.fieldErrors)
150
+ await markFields(formEl, res.fieldErrors)
70
151
  options.onError?.(res)
71
152
  return res
72
153
  }
@@ -85,6 +166,9 @@ export function useAction<Input, Output>(
85
166
  error,
86
167
  fieldErrors,
87
168
  data,
169
+ get progress() {
170
+ return progress ??= signal(0)
171
+ },
88
172
  get action() {
89
173
  const u = action.url || String(action)
90
174
  if ('__pruAction' in action)
@@ -122,19 +206,18 @@ function isSameDocHash(to: string): boolean {
122
206
  }
123
207
 
124
208
  export function actionStub<Input = unknown, Output = unknown>(url: string): ClientAction<Input, Output> {
125
- const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
209
+ const call = (async (input: Input | FormData, opts?: ((fraction: number) => void) | ClientActionOptions): Promise<ActionResult<Output>> => {
210
+ const isFn = typeof opts == 'function'
211
+ const onProgress = isFn ? opts : opts?.onProgress
212
+ const signal = isFn ? undefined : opts?.signal
126
213
  const isForm = typeof FormData !== 'undefined' && input instanceof FormData
127
214
  const headers: Record<string, string> = { 'accept': 'application/json', 'x-pru-action': '1' }
128
215
  if (!isForm)
129
216
  headers['content-type'] = 'application/json'
130
217
  let res: Response
131
218
  try {
132
- res = await fetch(url, {
133
- method: 'POST',
134
- headers,
135
- body: isForm ? input : input === undefined ? '{}' : JSON.stringify(input),
136
- redirect: 'manual',
137
- })
219
+ const init: RequestInit = { method: 'POST', headers, body: isForm ? input : input === undefined ? '{}' : JSON.stringify(input), redirect: 'manual', ...(signal && { signal }) }
220
+ res = await (typeof onProgress == 'function' ? (typeof PRUNELLE_UPLOAD === 'undefined' ? import('./upload') : import(PRUNELLE_UPLOAD) as Promise<typeof import('./upload')>).then(m => m.upload(url, init, onProgress)) : fetch(url, init))
138
221
  }
139
222
  catch (err) {
140
223
  return fail(0, errMsg(err))
package/src/dom/attrs.ts CHANGED
@@ -1,15 +1,17 @@
1
1
  // Attribute, class, property and style bindings, in a module of their own (`dom-attrs`): only the islands that bind one load it.
2
2
 
3
- import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
4
- import { styleText } from '../style'
3
+ import { isStringBoolAttr, isUnsafeUrlAttr, URL_ATTRS, VALID_ATTR_NAME } from '../attrs'
4
+ import { eachStyleProp } from '../style'
5
5
  import { assertRenderable } from '../unrenderable'
6
+ import { isHydrating } from './index'
6
7
 
7
8
  export function setClass(el: Element, value: unknown): void {
8
9
  if (process.env.NODE_ENV !== 'production')
9
10
  assertRenderable(value, 'class')
10
11
  const str = value == null || value === false ? '' : String(value)
11
- if (typeof el.className === 'string') {
12
- if (el.className !== str) {
12
+ const cur = el.className
13
+ if (typeof cur === 'string') {
14
+ if (cur !== str) {
13
15
  if (str === '')
14
16
  el.removeAttribute('class')
15
17
  else
@@ -26,39 +28,53 @@ export function setClass(el: Element, value: unknown): void {
26
28
 
27
29
  const XLINK_NS = 'http://www.w3.org/1999/xlink'
28
30
 
31
+ function removeAttr(el: Element, name: string, isXlink: boolean): void {
32
+ if (isXlink) {
33
+ if (el.hasAttributeNS(XLINK_NS, 'href'))
34
+ el.removeAttributeNS(XLINK_NS, 'href')
35
+ }
36
+ else if (el.hasAttribute(name)) {
37
+ el.removeAttribute(name)
38
+ }
39
+ }
40
+
41
+ function writeAttr(el: Element, name: string, isXlink: boolean, next: string): void {
42
+ if (isXlink) {
43
+ if (el.getAttributeNS(XLINK_NS, 'href') !== next)
44
+ el.setAttributeNS(XLINK_NS, name, next)
45
+ }
46
+ else if (el.getAttribute(name) !== next) {
47
+ el.setAttribute(name, next)
48
+ }
49
+ }
50
+
29
51
  export function setAttr(el: Element, name: string, value: unknown): void {
30
- if (isBlockedAttr(name))
52
+ if (!VALID_ATTR_NAME.test(name))
53
+ return
54
+ const lower = name.toLowerCase()
55
+ if (lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc')
31
56
  return
32
57
  if (process.env.NODE_ENV !== 'production')
33
58
  assertRenderable(value, name)
34
59
  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
- }
41
60
  if (value == null) {
42
- remove()
61
+ removeAttr(el, name, isXlink)
43
62
  }
44
63
  else if (typeof value === 'boolean') {
45
- if (isStringBoolAttr(name))
46
- el.setAttribute(name, value ? 'true' : 'false')
64
+ if (isStringBoolAttr(lower))
65
+ writeAttr(el, name, isXlink, value ? 'true' : 'false')
47
66
  else if (value)
48
- el.setAttribute(name, '')
67
+ writeAttr(el, name, isXlink, '')
49
68
  else
50
- remove()
69
+ removeAttr(el, name, isXlink)
51
70
  }
52
- else if (isUnsafeUrlAttr(name, value, el.tagName)) {
71
+ else if (URL_ATTRS.has(lower) && isUnsafeUrlAttr(lower, value, el.tagName)) {
53
72
  if (process.env.NODE_ENV !== 'production')
54
73
  console.warn(`prunelle: dropped unsafe URL on <${el.tagName.toLowerCase()} ${name}>.`)
55
- remove()
56
- }
57
- else if (isXlink) {
58
- el.setAttributeNS(XLINK_NS, name, String(value))
74
+ removeAttr(el, name, isXlink)
59
75
  }
60
76
  else {
61
- el.setAttribute(name, String(value))
77
+ writeAttr(el, name, isXlink, String(value))
62
78
  }
63
79
  }
64
80
 
@@ -79,14 +95,66 @@ export function setSelectValues(el: HTMLSelectElement, value: unknown): void {
79
95
  option.selected = value.some(v => String(v) === option.value)
80
96
  }
81
97
 
98
+ const IMPORTANT = /\s*!\s*important\s*$/i
99
+ let prevStyles: WeakMap<Element, Record<string, string> | string> | undefined
100
+
101
+ function applyProp(style: CSSStyleDeclaration, prop: string, raw: string): void {
102
+ const important = IMPORTANT.test(raw)
103
+ const val = important ? raw.replace(IMPORTANT, '') : raw
104
+ const priority = important ? 'important' : ''
105
+ if (style.getPropertyValue(prop) !== val || style.getPropertyPriority(prop) !== priority)
106
+ style.setProperty(prop, val, priority)
107
+ }
108
+
82
109
  export function setStyle(el: HTMLElement, value: unknown): void {
110
+ const prev = prevStyles?.get(el)
83
111
  if (value == null || value === false) {
84
- el.removeAttribute('style')
112
+ prevStyles?.delete(el)
113
+ if (prev !== undefined && typeof prev === 'object') {
114
+ for (const prop in prev)
115
+ el.style.removeProperty(prop)
116
+ if (el.style.cssText === '' && el.hasAttribute('style'))
117
+ el.removeAttribute('style')
118
+ }
119
+ else if (el.hasAttribute('style')) {
120
+ el.removeAttribute('style')
121
+ }
85
122
  }
86
123
  else if (typeof value === 'string') {
87
- el.style.cssText = value
124
+ if (prev === value)
125
+ return
126
+ ;(prevStyles ??= new WeakMap()).set(el, value)
127
+ if (el.style.cssText !== value)
128
+ el.style.cssText = value
88
129
  }
89
130
  else if (typeof value === 'object') {
90
- el.style.cssText = styleText(value as Record<string, unknown>)
131
+ const next = Object.create(null) as Record<string, string>
132
+ eachStyleProp(value as Record<string, unknown>, (prop, raw) => {
133
+ next[prop] = raw
134
+ })
135
+ let prevObj = typeof prev === 'object' ? prev : undefined
136
+ if (prev === undefined && isHydrating() && el.style.length > 0) {
137
+ prevObj = Object.create(null) as Record<string, string>
138
+ for (let i = 0; i < el.style.length; i++) {
139
+ const prop = el.style.item(i)
140
+ const val = el.style.getPropertyValue(prop)
141
+ const prio = el.style.getPropertyPriority(prop)
142
+ prevObj[prop] = prio ? `${val} !${prio}` : val
143
+ }
144
+ }
145
+ if (typeof prev === 'string' && prev !== '')
146
+ el.style.cssText = ''
147
+ if (prevObj !== undefined) {
148
+ for (const prop in prevObj) {
149
+ if (!(prop in next))
150
+ el.style.removeProperty(prop)
151
+ }
152
+ }
153
+ for (const prop in next) {
154
+ const raw = next[prop]!
155
+ if (prevObj === undefined || prevObj[prop] !== raw)
156
+ applyProp(el.style, prop, raw)
157
+ }
158
+ ;(prevStyles ??= new WeakMap()).set(el, next)
91
159
  }
92
160
  }