prunelle 0.7.7 → 0.9.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.
- package/llms.txt +63 -46
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +15 -7
- package/src/build/index.ts +20 -10
- package/src/build/island-promote.ts +1 -1
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +57 -6
- package/src/cli/check.ts +40 -17
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +18 -4
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +72 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +4 -1
- package/src/compiler/emit.ts +1 -1
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/shared.ts +9 -16
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +8 -0
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +121 -10
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +22 -17
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +7 -4
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +35 -14
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +102 -299
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +11 -24
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +81 -20
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
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
|
|
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 &&
|
|
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
|
-
|
|
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,
|
|
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 = (
|
|
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
|
}
|
package/src/dev/protocol.ts
CHANGED
|
@@ -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
|
-
|
|
53
|
-
|
|
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
|
}
|
package/src/dev/supervisor.ts
CHANGED
|
@@ -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',
|
package/src/dev/watchers.ts
CHANGED
|
@@ -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
|
-
|
|
133
|
-
|
|
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
|
@@ -71,6 +71,14 @@ export function setProp(el: Element, name: string, value: unknown): void {
|
|
|
71
71
|
rec[name] = next
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
/** The `value` of a `<select multiple>`: an array selects the options it lists, as SSR renders them; anything else is a plain value. */
|
|
75
|
+
export function setSelectValues(el: HTMLSelectElement, value: unknown): void {
|
|
76
|
+
if (!Array.isArray(value) || !el.multiple)
|
|
77
|
+
return setProp(el, 'value', value)
|
|
78
|
+
for (const option of el.options)
|
|
79
|
+
option.selected = value.some(v => String(v) === option.value)
|
|
80
|
+
}
|
|
81
|
+
|
|
74
82
|
export function setStyle(el: HTMLElement, value: unknown): void {
|
|
75
83
|
if (value == null || value === false) {
|
|
76
84
|
el.removeAttribute('style')
|
package/src/dom/extras.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { assertRenderable } from '../unrenderable'
|
|
|
10
10
|
import { setAttr, setClass, setProp, setStyle } from './attrs'
|
|
11
11
|
import { claimInsert } from './claim'
|
|
12
12
|
import { claimRange, delegate, hydrateCursor, isHydrating, moveCursor, skipRange } from './index'
|
|
13
|
+
import { trustedHtml } from './trusted'
|
|
13
14
|
|
|
14
15
|
// A literal rather than a split string, so the bundler drops it from an island that imports this module for its chunk alone (#3683).
|
|
15
16
|
const DELEGATED_EVENTS = new Set(['beforeinput', 'click', 'dblclick', 'focusin', 'focusout', 'input', 'keydown', 'keyup', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'touchstart', 'touchend'])
|
|
@@ -31,7 +32,7 @@ export function setInnerHtml(el: Element, value: unknown): void {
|
|
|
31
32
|
else
|
|
32
33
|
html = String(value)
|
|
33
34
|
if (el.innerHTML !== html)
|
|
34
|
-
el.innerHTML = html
|
|
35
|
+
el.innerHTML = trustedHtml(html)
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
const EVENT_PROP = /^on([A-Z]\w*)$/
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Loaded by `useAction` only once a submit fails with field errors or left marks to undo, so a form that never fails ships none of it.
|
|
2
|
+
|
|
3
|
+
// Each field `errors` names gets `aria-invalid` and is described by the element of its form whose whole text is its message: the first after it, else the last before it (RGAA 11.10, 11.11). A field the app or `Field` marked itself is left alone; `data-pru-err` keeps what its `aria-describedby` was, to undo the marks at the next submit.
|
|
4
|
+
export function markFields(form: HTMLFormElement, errors: Record<string, string> = {}): void {
|
|
5
|
+
const all = [...form.querySelectorAll('*')]
|
|
6
|
+
for (const field of [...form.elements] as HTMLInputElement[]) {
|
|
7
|
+
const was = field.getAttribute('data-pru-err')
|
|
8
|
+
if (was !== null) {
|
|
9
|
+
field.removeAttribute('data-pru-err')
|
|
10
|
+
field.removeAttribute('aria-invalid')
|
|
11
|
+
was ? field.setAttribute('aria-describedby', was) : field.removeAttribute('aria-describedby')
|
|
12
|
+
}
|
|
13
|
+
const message = Object.hasOwn(errors, field.name) && errors[field.name]
|
|
14
|
+
if (!message || field.hasAttribute('aria-invalid'))
|
|
15
|
+
continue
|
|
16
|
+
const shows = (el: Element) => el.textContent!.trim() === message
|
|
17
|
+
const shown = all.find(el => shows(el) && field.compareDocumentPosition(el) & 4) ?? all.findLast(shows)
|
|
18
|
+
const before = field.getAttribute('aria-describedby') || ''
|
|
19
|
+
field.setAttribute('data-pru-err', before)
|
|
20
|
+
field.setAttribute('aria-invalid', 'true')
|
|
21
|
+
if (shown)
|
|
22
|
+
field.setAttribute('aria-describedby', `${before} ${shown.id ||= `pru-err-${field.name}`}`.trim())
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/dom/hot.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Dev only: the island chunks `prunelle dev` build export `hotMount` from here, which also puts the hooks that keep signals across a swap on the page.
|
|
2
|
+
|
|
3
|
+
import { hooks } from '../reactivity/hmr'
|
|
4
|
+
import { mount } from './index'
|
|
5
|
+
|
|
6
|
+
/** Renders an island again over the DOM it has, its signals starting from the values the render `previous` disposed ended with. */
|
|
7
|
+
export function hotMount(container: Element, render: () => Node | DocumentFragment | null, idPrefix: string | undefined, previous: () => void): () => void {
|
|
8
|
+
return hooks.restore(previous, () => mount(container, render, idPrefix))
|
|
9
|
+
}
|
package/src/dom/index.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
// Prunelle minimal DOM & hydration core. Every island imports it, so what only some islands need lives apart: attribute bindings in prunelle/internal/dom-attrs, claiming SSR lists and inserts in dom-claim, lists in dom-loop, inserts and spreads in dom-extras.
|
|
2
2
|
|
|
3
|
+
import type { HmrHost } from '../reactivity/hmr'
|
|
3
4
|
import { batch, createOwner, disposeOwner, getOwner, onCleanup, runWithOwner } from '../reactivity/index'
|
|
4
5
|
import { assertRenderable } from '../unrenderable'
|
|
6
|
+
import { trustedHtml } from './trusted'
|
|
5
7
|
|
|
6
8
|
export { effect } from '../reactivity/index'
|
|
7
9
|
|
|
8
10
|
let hydrating = false
|
|
11
|
+
let mounting = false
|
|
9
12
|
let hydrateNode: Node | null = null
|
|
10
13
|
let hydrateRoot: Element | null = null
|
|
11
14
|
let mismatchHook: ((parent: Node, stale: Node, node: Node) => void) | null = null
|
|
@@ -28,6 +31,11 @@ export function isHydrating(): boolean {
|
|
|
28
31
|
return hydrating
|
|
29
32
|
}
|
|
30
33
|
|
|
34
|
+
/** True while a client-only island renders for the first time. */
|
|
35
|
+
export function isMounting(): boolean {
|
|
36
|
+
return mounting
|
|
37
|
+
}
|
|
38
|
+
|
|
31
39
|
/** Points the hydration cursor at `node` (claiming SSR nodes when `on`) and returns the cursor it replaced, for the caller to restore. */
|
|
32
40
|
export function moveCursor(on: boolean, node: Node | null): [boolean, Node | null] {
|
|
33
41
|
const prev: [boolean, Node | null] = [hydrating, hydrateNode]
|
|
@@ -49,7 +57,7 @@ export function hydrate(container: Element, render: () => Node | DocumentFragmen
|
|
|
49
57
|
hydrateRoot = container
|
|
50
58
|
|
|
51
59
|
try {
|
|
52
|
-
const node = runWithOwner(owner, render)
|
|
60
|
+
const node = runWithOwner(owner, process.env.NODE_ENV !== 'production' ? (globalThis as HmrHost).__pruHmr?.wrap(render) ?? render : render)
|
|
53
61
|
if (node !== null && node.parentNode === null)
|
|
54
62
|
container.appendChild(node)
|
|
55
63
|
}
|
|
@@ -64,7 +72,8 @@ export function hydrate(container: Element, render: () => Node | DocumentFragmen
|
|
|
64
72
|
hydrateRoot = prevRoot
|
|
65
73
|
}
|
|
66
74
|
|
|
67
|
-
|
|
75
|
+
const dispose = () => disposeOwner(owner)
|
|
76
|
+
return process.env.NODE_ENV !== 'production' ? (globalThis as HmrHost).__pruHmr?.keep(dispose) ?? dispose : dispose
|
|
68
77
|
}
|
|
69
78
|
|
|
70
79
|
export function mount(container: Element, render: () => Node | DocumentFragment | null, idPrefix?: string): () => void {
|
|
@@ -72,9 +81,11 @@ export function mount(container: Element, render: () => Node | DocumentFragment
|
|
|
72
81
|
if (idPrefix !== undefined)
|
|
73
82
|
owner.id = { p: idPrefix, n: 0 }
|
|
74
83
|
const prevHydrating = hydrating
|
|
84
|
+
const prevMounting = mounting
|
|
75
85
|
hydrating = false
|
|
86
|
+
mounting = true
|
|
76
87
|
try {
|
|
77
|
-
const node = runWithOwner(owner, render)
|
|
88
|
+
const node = runWithOwner(owner, process.env.NODE_ENV !== 'production' ? (globalThis as HmrHost).__pruHmr?.wrap(render) ?? render : render)
|
|
78
89
|
container.textContent = ''
|
|
79
90
|
if (node !== null)
|
|
80
91
|
container.appendChild(node)
|
|
@@ -85,8 +96,10 @@ export function mount(container: Element, render: () => Node | DocumentFragment
|
|
|
85
96
|
}
|
|
86
97
|
finally {
|
|
87
98
|
hydrating = prevHydrating
|
|
99
|
+
mounting = prevMounting
|
|
88
100
|
}
|
|
89
|
-
|
|
101
|
+
const dispose = () => disposeOwner(owner)
|
|
102
|
+
return process.env.NODE_ENV !== 'production' ? (globalThis as HmrHost).__pruHmr?.keep(dispose) ?? dispose : dispose
|
|
90
103
|
}
|
|
91
104
|
|
|
92
105
|
function warnMismatch(node: Node, expectedTag: string, steppedOver: boolean): void {
|
|
@@ -108,7 +121,7 @@ export function template(html: string, isSvg?: boolean): () => Node {
|
|
|
108
121
|
const clone = (): Node => {
|
|
109
122
|
if (cached === undefined) {
|
|
110
123
|
const t = document.createElement('template')
|
|
111
|
-
t.innerHTML = isSvg ? `<svg>${html}</svg>` : html
|
|
124
|
+
t.innerHTML = trustedHtml(isSvg ? `<svg>${html}</svg>` : html)
|
|
112
125
|
cached = isSvg ? t.content.firstChild!.firstChild! : t.content.firstChild!
|
|
113
126
|
}
|
|
114
127
|
return cached.cloneNode(true)
|
|
@@ -260,6 +273,13 @@ export function setText(node: Text, value: unknown): void {
|
|
|
260
273
|
const delegated = new WeakMap<Document, Set<string>>()
|
|
261
274
|
|
|
262
275
|
function dispatchEvent(event: Event): void {
|
|
276
|
+
// A swapped island's chunk carries its own copy of this runtime, and with it another listener on the document.
|
|
277
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
278
|
+
const seen = event as Event & Record<symbol, boolean>
|
|
279
|
+
if (seen[Symbol.for('prunelle.dispatched')])
|
|
280
|
+
return
|
|
281
|
+
seen[Symbol.for('prunelle.dispatched')] = true
|
|
282
|
+
}
|
|
263
283
|
const key = `$$${event.type}`
|
|
264
284
|
let current: EventTarget | null = null
|
|
265
285
|
const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Dev only: `prunelle dev` swaps a hydrated island's code in the open page. island.ts reaches this behind `process.env.NODE_ENV !== 'production'`, so a production build holds none of it.
|
|
2
|
+
|
|
3
|
+
import type { hotMount } from './hot'
|
|
4
|
+
|
|
5
|
+
/** What the loader keeps of a hydrated island, for the swap to render it again. */
|
|
6
|
+
export interface HotRender { props: Record<string, unknown>, idPrefix: string }
|
|
7
|
+
|
|
8
|
+
export interface HotIsland extends HTMLElement {
|
|
9
|
+
_d: (() => void) | undefined
|
|
10
|
+
_hr: HotRender | undefined
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
type HotChunk = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null, hotMount: typeof hotMount }
|
|
14
|
+
|
|
15
|
+
/** Points `el` at the chunk the edit built and, when it has hydrated, renders it again from the new code with the values its signals held. */
|
|
16
|
+
export async function hotSwapIsland(el: HotIsland, chunk: string): Promise<void> {
|
|
17
|
+
el.setAttribute('c', chunk)
|
|
18
|
+
const previous = el._d
|
|
19
|
+
const kept = el._hr
|
|
20
|
+
// One still waiting for its strategy loads the new chunk when that fires.
|
|
21
|
+
if (previous === undefined || kept === undefined)
|
|
22
|
+
return
|
|
23
|
+
const loaded = await import(chunk) as HotChunk
|
|
24
|
+
if (el._d !== previous || !el.isConnected)
|
|
25
|
+
return
|
|
26
|
+
previous()
|
|
27
|
+
el._d = undefined
|
|
28
|
+
el._d = loaded.hotMount(el, () => loaded.default(kept.props), kept.idPrefix, previous)
|
|
29
|
+
}
|
package/src/dom/island.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Native <pru-island> Custom Element: the build defines which strategies an app uses, so the loader drops the code of the others.
|
|
2
2
|
|
|
3
3
|
import type { hydrate, mount } from './index'
|
|
4
|
+
import type { HotIsland, HotRender } from './island-hot'
|
|
5
|
+
import { hotSwapIsland } from './island-hot'
|
|
4
6
|
|
|
5
7
|
declare const PRUNELLE_VISIBLE: boolean | undefined
|
|
6
8
|
declare const PRUNELLE_IDLE: boolean | undefined
|
|
@@ -146,6 +148,9 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promi
|
|
|
146
148
|
function isAllowedChunkUrl(chunk: string): boolean {
|
|
147
149
|
if (/[\u0000-\u0020\u007F]/.test(chunk))
|
|
148
150
|
return false
|
|
151
|
+
// A browser reads `//host` and `/\host` as another site; any other path from `/` is this one, and the chunks prunelle writes are such paths.
|
|
152
|
+
if (chunk[0] === '/' && chunk[1] !== '/' && chunk[1] !== '\\')
|
|
153
|
+
return true
|
|
149
154
|
if (typeof location !== 'undefined' && location.origin && location.origin !== 'null') {
|
|
150
155
|
try {
|
|
151
156
|
return new URL(chunk, location.href).origin === location.origin
|
|
@@ -154,9 +159,8 @@ function isAllowedChunkUrl(chunk: string): boolean {
|
|
|
154
159
|
return false
|
|
155
160
|
}
|
|
156
161
|
}
|
|
157
|
-
// A browser reads `//host` and `/\host` as another site.
|
|
158
162
|
if (chunk[0] === '/')
|
|
159
|
-
return
|
|
163
|
+
return false
|
|
160
164
|
return !/^(?:javascript|data|vbscript):/i.test(chunk)
|
|
161
165
|
}
|
|
162
166
|
|
|
@@ -202,6 +206,8 @@ export function defineIslandElement(): void {
|
|
|
202
206
|
_slot: Element | undefined
|
|
203
207
|
_s = false
|
|
204
208
|
_t = 0
|
|
209
|
+
declare _hr?: HotRender
|
|
210
|
+
declare _h?: (chunk: string) => Promise<void>
|
|
205
211
|
|
|
206
212
|
_clearStrategy(token?: number): void {
|
|
207
213
|
if (token !== undefined && token !== this._t)
|
|
@@ -324,6 +330,8 @@ export function defineIslandElement(): void {
|
|
|
324
330
|
return true
|
|
325
331
|
}
|
|
326
332
|
this._d = dispose
|
|
333
|
+
if (process.env.NODE_ENV !== 'production')
|
|
334
|
+
this._hr = { props, idPrefix }
|
|
327
335
|
// Queued behind the component's `onMount` callbacks, so a listener it binds there hears the replayed event.
|
|
328
336
|
if (after)
|
|
329
337
|
queueMicrotask(after)
|
|
@@ -340,5 +348,8 @@ export function defineIslandElement(): void {
|
|
|
340
348
|
}
|
|
341
349
|
}
|
|
342
350
|
|
|
351
|
+
if (process.env.NODE_ENV !== 'production')
|
|
352
|
+
PrunelleIsland.prototype._h = function (this: PrunelleIsland, chunk) { return hotSwapIsland(this as unknown as HotIsland, chunk) }
|
|
353
|
+
|
|
343
354
|
customElements.define('pru-island', PrunelleIsland)
|
|
344
355
|
}
|