prunelle 0.8.0 → 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.
Files changed (184) hide show
  1. package/llms.txt +61 -44
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  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 +88 -134
  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 +20 -10
  15. package/src/build/islands.ts +4 -1
  16. package/src/build/key-types.ts +31 -0
  17. package/src/build/manifest.ts +19 -1
  18. package/src/build/plugin-host.ts +2 -0
  19. package/src/build/prerender.ts +2 -2
  20. package/src/build/reach.ts +14 -1
  21. package/src/build/report.ts +1 -1
  22. package/src/build/route-types.ts +16 -0
  23. package/src/build/routes.ts +24 -15
  24. package/src/build/seed-ids.ts +65 -0
  25. package/src/build/seed-writes.ts +111 -0
  26. package/src/build/static-headers.ts +2 -2
  27. package/src/build/static.ts +1 -1
  28. package/src/cli/check-cache.ts +51 -0
  29. package/src/cli/check-consent.ts +95 -0
  30. package/src/cli/check-forms.ts +2 -2
  31. package/src/cli/check-links-patterns.ts +101 -0
  32. package/src/cli/check-links.ts +16 -100
  33. package/src/cli/check-regions.ts +185 -0
  34. package/src/cli/check-security.ts +50 -6
  35. package/src/cli/check.ts +40 -18
  36. package/src/cli/commands.ts +134 -14
  37. package/src/cli/docs.ts +21 -2
  38. package/src/cli/index.ts +1 -1
  39. package/src/cli/inspect.ts +2 -0
  40. package/src/cli/mcp-tools.ts +2 -2
  41. package/src/cli/new.ts +9 -5
  42. package/src/cli/upgrade-names.ts +14 -2
  43. package/src/cli/upgrade.ts +3 -0
  44. package/src/compiler/analyze.ts +2 -2
  45. package/src/compiler/cacheability.ts +24 -2
  46. package/src/compiler/compliance-contrast.ts +284 -0
  47. package/src/compiler/compliance-empty.ts +24 -0
  48. package/src/compiler/compliance-rgaa-content.ts +95 -0
  49. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  50. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  51. package/src/compiler/compliance-rgaa.ts +19 -0
  52. package/src/compiler/compliance-third-party.ts +59 -0
  53. package/src/compiler/compliance-urls.ts +52 -0
  54. package/src/compiler/compliance.ts +70 -42
  55. package/src/compiler/cookie-inventory.ts +119 -0
  56. package/src/compiler/foreign-imports.ts +5 -3
  57. package/src/compiler/mistakes.ts +18 -9
  58. package/src/compiler/props-pattern.ts +211 -0
  59. package/src/compiler/props.ts +177 -346
  60. package/src/compiler/ssr-emit.ts +510 -0
  61. package/src/compiler/ssr-helpers.ts +170 -121
  62. package/src/compiler/ssr.ts +25 -440
  63. package/src/context.ts +14 -1
  64. package/src/dev/child.ts +1 -1
  65. package/src/dev/hot-islands.ts +71 -0
  66. package/src/dev/index.ts +31 -18
  67. package/src/dev/protocol.ts +1 -1
  68. package/src/dev/queue.ts +3 -2
  69. package/src/dev/reload.ts +1 -1
  70. package/src/dev/supervisor.ts +3 -1
  71. package/src/dev/watchers.ts +6 -2
  72. package/src/dom/action.ts +97 -14
  73. package/src/dom/extras.ts +2 -1
  74. package/src/dom/field-marks.ts +24 -0
  75. package/src/dom/hot.ts +9 -0
  76. package/src/dom/index.ts +25 -5
  77. package/src/dom/island-hot.ts +29 -0
  78. package/src/dom/island.ts +13 -2
  79. package/src/dom/prefetch.ts +132 -0
  80. package/src/dom/regions.ts +498 -0
  81. package/src/dom/swap.ts +245 -0
  82. package/src/dom/trusted.ts +22 -0
  83. package/src/dom/upload.ts +44 -0
  84. package/src/eco/declaration.ts +39 -40
  85. package/src/eco/index.ts +5 -5
  86. package/src/href.ts +31 -0
  87. package/src/index.ts +9 -3
  88. package/src/plugins/config.ts +1 -1
  89. package/src/plugins/context.ts +7 -1
  90. package/src/plugins/daily.ts +27 -0
  91. package/src/plugins/index.ts +3 -3
  92. package/src/plugins/order.ts +1 -1
  93. package/src/plugins/public.ts +8 -5
  94. package/src/plugins/services.ts +88 -14
  95. package/src/plugins/types.ts +120 -9
  96. package/src/reactivity/hmr.ts +90 -0
  97. package/src/reactivity/index.ts +38 -18
  98. package/src/reactivity/resource.ts +115 -0
  99. package/src/reactivity/seed.ts +39 -0
  100. package/src/reactivity/server-seed.ts +194 -0
  101. package/src/reactivity/store.ts +55 -1
  102. package/src/rgpd/draft.ts +171 -0
  103. package/src/rgpd/forms.ts +85 -0
  104. package/src/rgpd/index.ts +57 -0
  105. package/src/server/action-flash.ts +1 -0
  106. package/src/server/action-registry.ts +6 -8
  107. package/src/server/action.ts +51 -19
  108. package/src/server/app-secret.ts +14 -8
  109. package/src/server/cache-invalidation.ts +96 -0
  110. package/src/server/compress.ts +3 -1
  111. package/src/server/consent.ts +16 -2
  112. package/src/server/cookie-inventory.ts +78 -0
  113. package/src/server/cookies.ts +50 -0
  114. package/src/server/csp-report.ts +86 -0
  115. package/src/server/discard.ts +13 -0
  116. package/src/server/document.ts +2 -2
  117. package/src/server/env.ts +1 -1
  118. package/src/server/errors.ts +9 -2
  119. package/src/server/field-errors.ts +91 -0
  120. package/src/server/form-schema.ts +16 -11
  121. package/src/server/health.ts +33 -12
  122. package/src/server/http.ts +25 -10
  123. package/src/server/index.ts +101 -298
  124. package/src/server/loader.ts +1 -0
  125. package/src/server/page.ts +3 -9
  126. package/src/server/plugin-host.ts +26 -8
  127. package/src/server/public.ts +14 -3
  128. package/src/server/rate-limit.ts +39 -10
  129. package/src/server/region.ts +3 -0
  130. package/src/server/request-handler.ts +370 -0
  131. package/src/server/request-log.ts +94 -0
  132. package/src/server/route-cache.ts +41 -6
  133. package/src/server/route-input.ts +54 -0
  134. package/src/server/route-table.ts +35 -19
  135. package/src/server/routing.ts +12 -11
  136. package/src/server/sanitize-html.ts +1 -1
  137. package/src/server/security.ts +38 -8
  138. package/src/server/serve-handlers.ts +9 -5
  139. package/src/server/shared-store.ts +314 -0
  140. package/src/server/start.ts +12 -5
  141. package/src/server/static-dir.ts +14 -10
  142. package/src/server/stream.ts +2 -1
  143. package/src/server/surface.ts +39 -0
  144. package/src/server/webhook.ts +48 -0
  145. package/src/server/workers.ts +168 -0
  146. package/src/ssr/consent-banner.ts +20 -16
  147. package/src/ssr/consent-texts.ts +40 -0
  148. package/src/ssr/context.ts +26 -3
  149. package/src/ssr/cookie-table.ts +75 -0
  150. package/src/ssr/index.ts +23 -13
  151. package/src/ssr/navigation.ts +161 -14
  152. package/src/test/browser.ts +50 -22
  153. package/src/test/build-reuse.ts +70 -0
  154. package/src/test/index.ts +45 -6
  155. package/src/test/mount.ts +53 -0
  156. package/src/test/outside.ts +94 -0
  157. package/templates/_shared/AGENTS.md +1 -1
  158. package/templates/_shared/Dockerfile +22 -0
  159. package/templates/_shared/dockerignore +9 -0
  160. package/templates/_shared/gitignore +2 -0
  161. package/templates/app/.env.example +3 -1
  162. package/templates/app/compose.yaml +32 -0
  163. package/templates/app/db/migrations/001_notes.sql +7 -0
  164. package/templates/app/db/schema.ts +11 -0
  165. package/templates/app/package.json +1 -0
  166. package/templates/app/prunelle.config.ts +6 -0
  167. package/templates/app/src/actions/notes.ts +26 -0
  168. package/templates/app/src/auth.ts +4 -2
  169. package/templates/app/src/db.ts +5 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  171. package/templates/app/src/routes/privacy.tsx +6 -2
  172. package/templates/app/tests/app.test.ts +14 -3
  173. package/templates/plugin/AGENTS.md +11 -0
  174. package/templates/plugin/CLAUDE.md +1 -0
  175. package/templates/plugin/README.md +27 -0
  176. package/templates/plugin/gitignore +2 -0
  177. package/templates/plugin/llms.txt +19 -0
  178. package/templates/plugin/package.json +33 -0
  179. package/templates/plugin/src/index.ts +40 -0
  180. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  181. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  182. package/templates/plugin/tests/plugin.test.ts +42 -0
  183. package/templates/plugin/tsconfig.json +19 -0
  184. package/ts-plugin.cjs +3674 -2196
@@ -0,0 +1,115 @@
1
+ // `resource()`: async data in an island, fetched again when its source changes, the run it replaces aborted.
2
+
3
+ import type { ActionResult } from '../server/action'
4
+ import type { ReadonlySignal } from './graph'
5
+ import { batch, effect, signal, untrack } from './index'
6
+
7
+ export interface ResourceOptions<T> {
8
+ /** The value to start from, such as one `load()` gave the page: the server renders it, and the browser fetches only once the source changes. */
9
+ initial?: T | undefined
10
+ }
11
+
12
+ /** Reads as the last value fetched, `undefined` until one arrives. */
13
+ export interface Resource<T> extends ReadonlySignal<T | undefined> {
14
+ readonly loading: ReadonlySignal<boolean>
15
+ readonly error: ReadonlySignal<Error | undefined>
16
+ /** Runs the fetcher again with the source as it is. */
17
+ refetch(): void
18
+ }
19
+
20
+ export interface ResourceRun {
21
+ /** Aborted once the run is replaced or the island goes away: pass it to `fetch`. */
22
+ readonly signal: AbortSignal
23
+ }
24
+
25
+ type ActionCall<Input, Output> = ((input: Input, run?: ResourceRun) => Promise<ActionResult<Output>>) & { readonly url: string }
26
+
27
+ export function resource<T>(fetcher: (run: ResourceRun) => Promise<T>, options?: ResourceOptions<T>): Resource<T>
28
+ export function resource<S, Output>(source: () => S | undefined, action: ActionCall<S, Output>, options?: ResourceOptions<Output>): Resource<Output>
29
+ export function resource<S, T>(source: () => S | undefined, fetcher: (source: S, run: ResourceRun) => Promise<T>, options?: ResourceOptions<T>): Resource<T>
30
+ export function resource(
31
+ first: (() => unknown) | ((run: ResourceRun) => Promise<unknown>),
32
+ second?: ((source: unknown, run: ResourceRun) => Promise<unknown>) | ResourceOptions<unknown>,
33
+ third?: ResourceOptions<unknown>,
34
+ ): Resource<unknown> {
35
+ const alone = typeof second !== 'function'
36
+ // A fetcher given alone has no source: it runs once, and what it reads is not tracked.
37
+ const source = alone ? () => true : first as () => unknown
38
+ const fetcher = alone ? (_: unknown, run: ResourceRun) => (first as (run: ResourceRun) => Promise<unknown>)(run) : second
39
+ const options = alone ? second : third
40
+ const isAction = typeof (fetcher as { url?: unknown }).url === 'string'
41
+ const value = signal(options?.initial)
42
+ const loading = signal(false)
43
+ const error = signal<Error | undefined>(undefined)
44
+ let controller: AbortController | undefined
45
+ let input: unknown
46
+
47
+ function settle(mine: AbortController, apply: () => void): void {
48
+ if (controller !== mine)
49
+ return
50
+ controller = undefined
51
+ batch(() => {
52
+ apply()
53
+ loading.value = false
54
+ })
55
+ }
56
+
57
+ function run(): void {
58
+ controller?.abort()
59
+ controller = undefined
60
+ if (input === undefined) {
61
+ loading.value = false
62
+ return
63
+ }
64
+ const mine = controller = new AbortController()
65
+ loading.value = true
66
+ let pending: Promise<unknown>
67
+ try {
68
+ pending = fetcher(input, { signal: mine.signal })
69
+ }
70
+ catch (err) {
71
+ pending = Promise.reject(err)
72
+ }
73
+ pending.then((result) => {
74
+ settle(mine, () => {
75
+ const failed = isAction && !(result as ActionResult<unknown>).ok
76
+ error.value = failed ? new Error((result as Extract<ActionResult<unknown>, { ok: false }>).error) : undefined
77
+ if (!failed)
78
+ value.value = isAction ? (result as Extract<ActionResult<unknown>, { ok: true }>).data : result
79
+ })
80
+ }, (err: unknown) => {
81
+ settle(mine, () => {
82
+ error.value = err instanceof Error ? err : new Error(String(err))
83
+ })
84
+ })
85
+ }
86
+
87
+ // The value given stands for the first run, so the browser does not fetch what the server already rendered.
88
+ let given = options?.initial !== undefined
89
+ let ran = false
90
+ effect(() => {
91
+ ran = true
92
+ input = source()
93
+ const skip = given
94
+ given = false
95
+ if (!skip)
96
+ untrack(run)
97
+ return () => {
98
+ controller?.abort()
99
+ controller = undefined
100
+ }
101
+ })
102
+ // During SSR, `effect()` is skipped: reflect `loading` only when the resource has a defined source and no initial value.
103
+ if (!ran && options?.initial === undefined && (alone || untrack(source) !== undefined))
104
+ loading.value = true
105
+
106
+ return {
107
+ get value() {
108
+ return value.value
109
+ },
110
+ peek: () => value.peek(),
111
+ loading,
112
+ error,
113
+ refetch: () => untrack(run),
114
+ }
115
+ }
@@ -0,0 +1,39 @@
1
+ // What the compiler wraps a module's `signal()` and `store()` in: the server gives it the id the page hands the browser, and the browser starts from what the server rendered.
2
+
3
+ import type { Signal } from './index'
4
+ import { nameSeed } from './index'
5
+
6
+ declare const PRUNELLE_BROWSER: boolean | undefined
7
+
8
+ type Entry = [id: string, path: string[], value?: unknown, deleted?: 1]
9
+
10
+ // What the islands of the page say the server wrote to `id`, in page order: read when the module first runs, so a page a navigation brought in has its own.
11
+ function entriesOf(id: string): Entry[] {
12
+ return Array.from(document.querySelectorAll('pru-island[s]')).flatMap(el => (JSON.parse(el.getAttribute('s')!) as Entry[]).filter(e => e[0] === id))
13
+ }
14
+
15
+ export function seedSignal<T>(node: Signal<T>, id: string, label?: string): Signal<T> {
16
+ if (typeof PRUNELLE_BROWSER === 'undefined' || !PRUNELLE_BROWSER)
17
+ nameSeed(node, id, label)
18
+ else
19
+ entriesOf(id).forEach(e => node.value = e[2] as T)
20
+ return node
21
+ }
22
+
23
+ // Each written key is set where it was, so what the browser's store holds that the server's copy had changed since (state `load()` made) stays. The walk takes own keys only and never sets `__proto__`, so no path the page carries reaches a prototype (#375).
24
+ export function seedStore<T extends object>(node: T, id: string, label?: string): T {
25
+ if (typeof PRUNELLE_BROWSER === 'undefined' || !PRUNELLE_BROWSER)
26
+ nameSeed(node, id, label)
27
+ else {
28
+ for (const [, path, value, deleted] of entriesOf(id)) {
29
+ const at = path.slice(0, -1).reduce<unknown>((o, k) => typeof o === 'object' && o !== null && Object.hasOwn(o, k) ? (o as Record<string, unknown>)[k] : undefined, node)
30
+ if (typeof at === 'object' && at !== null && path.at(-1) !== '__proto__') {
31
+ if (deleted)
32
+ delete (at as Record<string, unknown>)[path.at(-1)!]
33
+ else
34
+ (at as Record<string, unknown>)[path.at(-1)!] = value
35
+ }
36
+ }
37
+ }
38
+ return node
39
+ }
@@ -0,0 +1,194 @@
1
+ // What an island's server render shares with the request around it: the module state it may write, kept per request and handed to the browser.
2
+
3
+ let serverRenders = 0
4
+ let replaying = false
5
+
6
+ /** Internal, server only: an island is rendering, where `effect` and `onMount` do nothing. */
7
+ export function inServerRender(): boolean {
8
+ return serverRenders > 0
9
+ }
10
+
11
+ /** Internal, server only: what the islands of one request wrote to state every request shares, in order, so each island renders with its predecessors' writes. */
12
+ export interface RequestSeeds {
13
+ ops: SharedWrite[]
14
+ /** What the island that rendered last wrote, for the browser: `[id, path, value]`, `[id, path]` for undefined, `[id, path, 0, 1]` for a deleted key. */
15
+ out: unknown[][] | undefined
16
+ }
17
+
18
+ interface SharedWrite {
19
+ /** The signal or store and the path in it, which a later write of the same place replaces in `out`. */
20
+ key: string
21
+ entry: unknown[]
22
+ redo: () => void
23
+ undo: () => void
24
+ }
25
+
26
+ function replay(ops: readonly SharedWrite[], to: number, step: 'redo' | 'undo'): void {
27
+ replaying = true
28
+ try {
29
+ if (step === 'redo') {
30
+ for (let i = 0; i < to; i++)
31
+ ops[i]!.redo()
32
+ }
33
+ else {
34
+ for (let i = to - 1; i >= 0; i--)
35
+ ops[i]!.undo()
36
+ }
37
+ }
38
+ finally {
39
+ replaying = false
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Internal: runs an island's server render, during which `effect` and `onMount` do nothing.
45
+ * The writes the request's earlier islands made to module state are applied first and the ones this render makes are undone after it, so the next request sees the module's own value.
46
+ */
47
+ export function renderOnServer<T>(fn: () => T, seeds?: RequestSeeds): T {
48
+ if (serverRenders > 0) {
49
+ serverRenders++
50
+ try {
51
+ return fn()
52
+ }
53
+ finally {
54
+ serverRenders--
55
+ }
56
+ }
57
+ const mine = seeds ?? { ops: [], out: undefined }
58
+ const start = mine.ops.length
59
+ mine.out = undefined
60
+ serverRenders++
61
+ seedsInUse = mine
62
+ let ok = false
63
+ try {
64
+ replay(mine.ops, start, 'redo')
65
+ const result = fn()
66
+ ok = true
67
+ return result
68
+ }
69
+ finally {
70
+ serverRenders--
71
+ seedsInUse = undefined
72
+ const end = mine.ops.length
73
+ if (ok && end > start) {
74
+ const out = new Map<string, unknown[]>()
75
+ for (let i = start; i < end; i++) {
76
+ out.delete(mine.ops[i]!.key)
77
+ out.set(mine.ops[i]!.key, mine.ops[i]!.entry)
78
+ }
79
+ mine.out = [...out.values()]
80
+ }
81
+ // Every write undone in reverse leaves each place on its first value, also when a redo above threw halfway.
82
+ try {
83
+ replay(mine.ops, end, 'undo')
84
+ }
85
+ finally {
86
+ if (!ok)
87
+ mine.ops.length = start
88
+ }
89
+ }
90
+ }
91
+
92
+ let seedsInUse: RequestSeeds | undefined
93
+ // The signals and store roots the compiler named: the id the browser seeds each by, and `file#name` for errors.
94
+ const seedIds = new WeakMap<object, { id: string, label: string }>()
95
+
96
+ /** Internal, server only: gives a module-level signal or store the id the browser seeds it by. */
97
+ export function nameSeed(node: object, id: string, label = id): void {
98
+ seedIds.set(node, { id, label })
99
+ }
100
+
101
+ // On the server, the signals and store objects made outside an island's render: at a module's top level, where every request of the process reads the same one.
102
+ const shared = new WeakSet<object>()
103
+ // A store object inside a shared store, to the object and key it was last read from.
104
+ const parents = new WeakMap<object, { parent: object, key: PropertyKey }>()
105
+
106
+ /** Internal, server only: marks `node` as shared by every request when it is made outside an island's render, or sits in a store object that is. */
107
+ export function shareOutsideRender(node: object, parent?: object, key?: PropertyKey): void {
108
+ if (parent !== undefined && shared.has(parent)) {
109
+ shared.add(node)
110
+ const at = parents.get(node)
111
+ if (node !== parent && (at === undefined || at.parent !== parent || at.key !== key))
112
+ parents.set(node, { parent, key: key! })
113
+ }
114
+ else if (serverRenders === 0) {
115
+ shared.add(node)
116
+ }
117
+ }
118
+
119
+ /** Internal, server only: the root store object `node` hangs from, and the keys down to it. */
120
+ export function sharedPath(node: object): { root: object, path: PropertyKey[] } {
121
+ const path: PropertyKey[] = []
122
+ let root = node
123
+ for (let at = parents.get(root); at !== undefined && path.length < 256; at = parents.get(root)) {
124
+ path.push(at.key)
125
+ root = at.parent
126
+ }
127
+ return { root, path: path.reverse() }
128
+ }
129
+
130
+ /** Internal, server only: true when an island renders on the server and `node` is state every request shares. */
131
+ export function isSharedWrite(node: object): boolean {
132
+ return serverRenders > 0 && !replaying && shared.has(node)
133
+ }
134
+
135
+ function describe(value: unknown): string {
136
+ switch (typeof value) {
137
+ case 'bigint': return 'a BigInt'
138
+ case 'function': return 'a function'
139
+ case 'symbol': return 'a symbol'
140
+ case 'number': return String(value)
141
+ case 'object': return `a ${Object.getPrototypeOf(value)?.constructor?.name ?? 'object'}`
142
+ default: return 'undefined'
143
+ }
144
+ }
145
+
146
+ /** A copy of `value` the browser can be handed as JSON; throws naming the first thing in it that JSON cannot carry. */
147
+ function carry(value: unknown, at: string, owner: string, up: object[] = []): unknown {
148
+ if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)))
149
+ return value
150
+ let what = describe(value)
151
+ if (typeof value === 'object') {
152
+ const proto = Object.getPrototypeOf(value)
153
+ if (up.includes(value)) {
154
+ what = 'a cycle'
155
+ }
156
+ else if (Array.isArray(value)) {
157
+ up.push(value)
158
+ const copy = value.map((item, i) => carry(item, `${at}.${i}`, owner, up))
159
+ up.pop()
160
+ return copy
161
+ }
162
+ else if (proto === Object.prototype || proto === null) {
163
+ up.push(value)
164
+ const copy: Record<string, unknown> = {}
165
+ for (const [k, v] of Object.entries(value))
166
+ copy[k] = carry(v, `${at}.${k}`, owner, up)
167
+ up.pop()
168
+ return copy
169
+ }
170
+ }
171
+ throw new Error(`prunelle: an island wrote ${what} to ${owner}${at === '' ? '' : ` (at ${at.slice(1)})`} while it rendered on the server, and ${what} cannot reach the browser as JSON. Write a number, string, boolean, null, plain object or array (a BigInt as a string, a Date as its ISO string), or write it in onMount() or an event handler.`)
172
+ }
173
+
174
+ /**
175
+ * Internal, server only: an island's write to state every request shares stays in this request, as the writes undone after the render, and reaches the browser by the id of `owner`.
176
+ * `owner` is the signal or the store's root proxy, `path` the keys down to what was written, `value` what it became and `deleted` a key removed.
177
+ */
178
+ export function recordSharedWrite(owner: object, path: readonly PropertyKey[], redo: () => void, undo: () => void, value: unknown, deleted = false): void {
179
+ const named = seedIds.get(owner)
180
+ if (named === undefined || seedsInUse === undefined)
181
+ throw new Error('prunelle: an island wrote a signal or store made outside its own render, and prunelle cannot hand its value to the browser, while it rendered on the server, where the next visitor could see the value. Make it with `const cart = signal(0)` or `store({ … })` at a module\'s top level (not in load() or another function that runs per request), write it in onMount() or an event handler, or make the signal inside the component.')
182
+ const [file, name = named.label] = named.label.split('#') as [string, string?]
183
+ const owned = name === named.label ? name : `${name} in ${file}`
184
+ const keys = path.map((k) => {
185
+ if (typeof k === 'symbol')
186
+ throw new Error(`prunelle: an island wrote a symbol key of ${owned} while it rendered on the server, and a symbol key cannot reach the browser as JSON. Use string keys, or write it in onMount() or an event handler.`)
187
+ if (k === '__proto__')
188
+ throw new Error(`prunelle: an island wrote the key __proto__ of ${owned} while it rendered on the server, which would change a prototype in the browser. Prefix keys that come from the request (\`user:\${name}\`), keep them in a Map, or write it in onMount() or an event handler.`)
189
+ return k
190
+ })
191
+ const entry = deleted ? [named.id, keys, 0, 1] : value === undefined ? [named.id, keys] : [named.id, keys, carry(value, '', owned)]
192
+ seedsInUse.ops.push({ key: JSON.stringify([named.id, keys]), entry, redo, undo })
193
+ }
194
+
@@ -1,7 +1,11 @@
1
1
  // Deep reactive proxy store (tree-shakable: 0 B if unused).
2
2
 
3
3
  import type { Signal } from './index'
4
- import { batch, isObserving, isTracking, signal, untrack, watchedSignal } from './index'
4
+ import { batch, isObserving, isSharedWrite, isTracking, recordSharedWrite, shareOutsideRender, sharedPath, signal, untrack, watchedSignal, writeRecorder } from './index'
5
+
6
+ declare const PRUNELLE_BROWSER: boolean | undefined
7
+ // The client build defines PRUNELLE_BROWSER, which drops what only the server checks.
8
+ const onServer = (): boolean => typeof PRUNELLE_BROWSER === 'undefined' || !PRUNELLE_BROWSER
5
9
 
6
10
  const RAW = Symbol('prunelle.store.raw')
7
11
  const OWN_KEYS = Symbol('prunelle.store.keys')
@@ -120,6 +124,12 @@ function evictTruncated(target: object, nextLen: number, prevLen: number): void
120
124
  bumpVer(target)
121
125
  }
122
126
 
127
+ // A write to a store every request shares, kept in the request: `redo` applies it again for the islands after, `undo` takes it back.
128
+ function recordWrite(obj: object, key: PropertyKey, redo: () => void, undo: () => void, value: unknown, deleted = false): void {
129
+ const { root, path } = sharedPath(obj)
130
+ recordSharedWrite(proxyCache.get(root)!, [...path, key], redo, undo, value, deleted)
131
+ }
132
+
123
133
  function wrap<T extends object>(target: T): T {
124
134
  const existing = proxyCache.get(target)
125
135
  if (existing !== undefined)
@@ -144,6 +154,8 @@ function wrap<T extends object>(target: T): T {
144
154
  const desc = Object.getOwnPropertyDescriptor(obj, key)
145
155
  if (desc !== undefined && !desc.configurable && !desc.writable && !desc.get)
146
156
  return value
157
+ if (onServer())
158
+ shareOutsideRender(value, obj, key)
147
159
  return wrap(value)
148
160
  },
149
161
  set(obj, key, value, receiver) {
@@ -152,11 +164,45 @@ function wrap<T extends object>(target: T): T {
152
164
  const prev = Reflect.get(obj, key, obj)
153
165
  const isArr = Array.isArray(obj)
154
166
  const prevLength = isArr ? obj.length : 0
167
+ const recorder = writeRecorder()
168
+ const isShared = onServer() && isSharedWrite(obj)
169
+ let dropped: [number, unknown][] | undefined
170
+ if (isArr && key === 'length' && (recorder || isShared)) {
171
+ const nextLen = typeof rawValue === 'number' || typeof rawValue === 'string' ? +rawValue : -1
172
+ if (Number.isInteger(nextLen) && nextLen >= 0 && nextLen < prevLength) {
173
+ dropped = []
174
+ for (let i = nextLen; i < prevLength; i++) {
175
+ if (Object.hasOwn(obj, i))
176
+ dropped.push([i, obj[i]])
177
+ }
178
+ }
179
+ }
180
+ const restore = (fixLen: boolean) => {
181
+ const self = proxy as Record<PropertyKey, unknown>
182
+ if (had)
183
+ self[key] = prev
184
+ else
185
+ delete self[key]
186
+ if (dropped) {
187
+ for (const [i, v] of dropped)
188
+ self[i] = v
189
+ }
190
+ else if (fixLen) {
191
+ self.length = prevLength
192
+ }
193
+ }
194
+ if (isShared && (!had || !Object.is(prev, rawValue))) {
195
+ const self = proxy as Record<PropertyKey, unknown>
196
+ recordWrite(obj, key, () => self[key] = rawValue, () => restore(isArr), rawValue)
197
+ }
155
198
  const ok = Reflect.set(obj, key, rawValue, receiver)
156
199
  if (!ok)
157
200
  return false
158
201
  const changed = !had || !Object.is(prev, rawValue)
159
202
  const lenChanged = isArr && obj.length !== prevLength
203
+ // Undone through the proxy so readers hear it; an index written past the end also grew `length`, and truncating `length` restores dropped elements.
204
+ if (changed)
205
+ recorder?.(() => restore(lenChanged))
160
206
  if (changed || lenChanged) {
161
207
  batch(() => {
162
208
  if (changed) {
@@ -177,8 +223,14 @@ function wrap<T extends object>(target: T): T {
177
223
  },
178
224
  deleteProperty(obj, key) {
179
225
  const had = Object.prototype.hasOwnProperty.call(obj, key)
226
+ const prev = Reflect.get(obj, key, obj)
227
+ if (had && onServer() && isSharedWrite(obj)) {
228
+ const self = proxy as Record<PropertyKey, unknown>
229
+ recordWrite(obj, key, () => delete self[key], () => self[key] = prev, undefined, true)
230
+ }
180
231
  const ok = Reflect.deleteProperty(obj, key)
181
232
  if (had && ok) {
233
+ writeRecorder()?.(() => (proxy as Record<PropertyKey, unknown>)[key] = prev)
182
234
  batch(() => {
183
235
  deleteDep(obj, key)
184
236
  notifyKey(obj, OWN_KEYS)
@@ -207,6 +259,8 @@ function wrap<T extends object>(target: T): T {
207
259
  export function store<T extends object>(initial: T): T {
208
260
  if (!isPlain(initial))
209
261
  return initial
262
+ if (onServer())
263
+ shareOutsideRender(initial)
210
264
  return wrap(initial)
211
265
  }
212
266
 
@@ -0,0 +1,171 @@
1
+ // Drafts the French privacy notice (RGPD art. 13) and the record of processing (art. 30) from what the plugins and the app's forms process.
2
+
3
+ import type { ProcessingDeclaration } from '../plugins/types'
4
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
5
+ import { dirname, resolve } from 'node:path'
6
+ import { escapeAttr, escapeJsxText, formatFrenchDate, layoutRendersMain, STATEMENT_PLACEHOLDER } from '../a11y/declaration'
7
+ import { relPosix } from '../build/files'
8
+
9
+ /** The record of processing, kept beside the code and out of the site: it is for the controller and the CNIL. */
10
+ export const REGISTER_PATH = 'registre-des-traitements.md'
11
+
12
+ export interface PrivacyNoticeOptions {
13
+ root: string
14
+ /** The notice's path from `root`; default `<routesDir>/confidentialite.tsx`. */
15
+ outPath?: string | undefined
16
+ /** Default `'src/routes'`. */
17
+ routesDir?: string | undefined
18
+ processing: readonly ProcessingDeclaration[]
19
+ organization?: string | undefined
20
+ contactEmail?: string | undefined
21
+ /** Day the drafts are dated (defaults to today). */
22
+ date?: Date | undefined
23
+ /** Write both files (default: `true`). */
24
+ write?: boolean | undefined
25
+ /** Overwrite files already there (default: `false`). */
26
+ force?: boolean | undefined
27
+ }
28
+
29
+ export interface DraftedFile {
30
+ path: string
31
+ /** From the app root, such as `'src/routes/confidentialite.tsx'`. */
32
+ relativePath: string
33
+ content: string
34
+ }
35
+
36
+ export interface PrivacyNoticeDraft {
37
+ notice: DraftedFile
38
+ register: DraftedFile
39
+ }
40
+
41
+ const todo = (what: string): string => `${STATEMENT_PLACEHOLDER} : ${what}]`
42
+ const NO_TRANSFER = todo('aucun, ou les pays et les garanties')
43
+
44
+ interface Details { purpose: string, data: string, people: string, legalBasis: string, retention: string, recipients: string }
45
+
46
+ function detailsOf(p: ProcessingDeclaration): Details {
47
+ return {
48
+ purpose: p.purpose,
49
+ data: p.data.join(' ; '),
50
+ people: p.people ?? todo('personnes concernées'),
51
+ legalBasis: p.legalBasis ?? todo('base légale (RGPD art. 6)'),
52
+ retention: p.retention ?? todo('durée de conservation'),
53
+ recipients: p.recipients === undefined || p.recipients.length === 0 ? todo('destinataires, ou aucun') : p.recipients.join(' ; '),
54
+ }
55
+ }
56
+
57
+ function noticeSection(p: ProcessingDeclaration): string {
58
+ const d = detailsOf(p)
59
+ const rows: [string, string][] = [['Finalité', d.purpose], ['Données', d.data], ['Personnes concernées', d.people], ['Base légale', d.legalBasis], ['Durée de conservation', d.retention], ['Destinataires', d.recipients]]
60
+ return [
61
+ ` <h3>${escapeJsxText(p.name)}</h3>`,
62
+ ' <dl>',
63
+ ...rows.map(([term, value]) => ` <dt>${term}</dt><dd>${escapeJsxText(value)}</dd>`),
64
+ ' </dl>',
65
+ ].join('\n')
66
+ }
67
+
68
+ function registerSection(p: ProcessingDeclaration): string {
69
+ const d = detailsOf(p)
70
+ const security = p.security === undefined || p.security.length === 0 ? todo('mesures de sécurité') : `${p.security.join(' ; ')} ; ${todo('autres mesures')}`
71
+ return [
72
+ `### ${p.name}`,
73
+ '',
74
+ `- Finalité : ${d.purpose}`,
75
+ `- Base légale : ${d.legalBasis}`,
76
+ `- Personnes concernées : ${d.people}`,
77
+ `- Données : ${d.data}`,
78
+ `- Destinataires : ${d.recipients}`,
79
+ `- Transferts hors de l'Union européenne : ${NO_TRANSFER}`,
80
+ `- Durée de conservation : ${d.retention}`,
81
+ `- Mesures de sécurité : ${security}`,
82
+ ].join('\n')
83
+ }
84
+
85
+ function noticeContent(options: PrivacyNoticeOptions, wrapper: string): string {
86
+ const org = options.organization?.trim() || todo('nom de la personne ou de l\'organisme qui publie le site')
87
+ const email = options.contactEmail?.trim()
88
+ const contact = email ? `<a href="mailto:${escapeAttr(email)}">${escapeJsxText(email)}</a>` : todo('adresse de contact')
89
+ const { iso, human } = formatFrenchDate(options.date ?? new Date())
90
+ const sections = options.processing.length === 0 ? ` <p>${todo('les traitements de données personnelles du site')}</p>` : options.processing.map(noticeSection).join('\n')
91
+ return `// Brouillon de politique de confidentialité (RGPD art. 13) généré par \`prunelle rgpd --draft\`, d'après les plugins et les formulaires de l'app.
92
+ // Remplacez chaque mention entre crochets avant publication : \`prunelle check\` signale celles qui restent.
93
+ // Le registre des traitements (RGPD art. 30) est dans ${REGISTER_PATH} : tenez-les à jour ensemble.
94
+
95
+ import { CookieTable, Head } from 'prunelle'
96
+
97
+ export const prerender = true
98
+
99
+ export default function Confidentialite() {
100
+ return (
101
+ <>
102
+ <Head>
103
+ <title>Politique de confidentialité</title>
104
+ </Head>
105
+ <${wrapper} lang="fr">
106
+ <h1>Politique de confidentialité</h1>
107
+ <p>Mise à jour le <time dateTime="${escapeAttr(iso)}">${escapeJsxText(human)}</time>.</p>
108
+ <h2>Responsable du traitement</h2>
109
+ <p>${escapeJsxText(org)} est responsable des traitements décrits sur cette page. Pour toute question sur vos données, ou pour exercer vos droits, écrivez à ${contact}.</p>
110
+ <p>Délégué à la protection des données : ${todo('son nom et son contact, ou aucun')}</p>
111
+ <h2>Données traitées</h2>
112
+ ${sections}
113
+ <h2>Cookies</h2>
114
+ <CookieTable />
115
+ <h2>Transferts hors de l'Union européenne</h2>
116
+ <p>${NO_TRANSFER}</p>
117
+ <h2>Vos droits</h2>
118
+ <p>Vous pouvez accéder à vos données, les faire rectifier ou effacer, limiter leur traitement ou vous y opposer et, dans les cas prévus par le RGPD, les recevoir dans un format réutilisable (articles 15 à 21). Si un traitement repose sur votre consentement, vous pouvez le retirer à tout moment. Vous pouvez aussi définir des directives sur le sort de vos données après votre décès.</p>
119
+ <p>Si vous estimez, après nous avoir écrit, que vos droits ne sont pas respectés, vous pouvez adresser une réclamation à la CNIL (<a href="https://www.cnil.fr">www.cnil.fr</a>).</p>
120
+ </${wrapper}>
121
+ </>
122
+ )
123
+ }
124
+ `
125
+ }
126
+
127
+ function registerContent(options: PrivacyNoticeOptions): string {
128
+ const { human } = formatFrenchDate(options.date ?? new Date())
129
+ const sections = options.processing.length === 0 ? todo('les traitements de données personnelles') : options.processing.map(registerSection).join('\n\n')
130
+ return `# Registre des activités de traitement
131
+
132
+ Brouillon généré par \`prunelle rgpd --draft\` le ${human}, d'après les plugins et les formulaires de l'app. Le RGPD (art. 30) demande au responsable du traitement de tenir ce registre à jour et de le présenter à la CNIL si elle le demande : il reste hors du site. Remplacez chaque mention entre crochets, et ajoutez les traitements que prunelle ne voit pas, comme la paie, le fichier clients ou la prospection.
133
+
134
+ ## Responsable du traitement
135
+
136
+ - Nom : ${options.organization?.trim() || todo('nom')}
137
+ - Adresse : ${todo('adresse')}
138
+ - Contact : ${options.contactEmail?.trim() || todo('adresse de contact')}
139
+ - Délégué à la protection des données : ${todo('nom et contact, ou aucun')}
140
+
141
+ ## Mesures de sécurité communes
142
+
143
+ - Par défaut, prunelle applique une politique de sécurité du contenu (CSP) stricte, protège les formulaires contre la falsification de requêtes (CSRF) et limite la taille des requêtes : vérifiez que la configuration de l'app n'en désactive aucune.
144
+ - ${todo('chiffrement des échanges (HTTPS), sauvegardes, accès au serveur, journalisation')}
145
+
146
+ ## Traitements
147
+
148
+ ${sections}
149
+ `
150
+ }
151
+
152
+ /** Drafts both files, and writes them unless `write` is false; refuses before writing either when one exists and `force` is not set. */
153
+ export function draftPrivacyNotice(options: PrivacyNoticeOptions): PrivacyNoticeDraft {
154
+ const root = resolve(options.root)
155
+ const routesDir = resolve(root, options.routesDir ?? 'src/routes')
156
+ const noticePath = options.outPath === undefined ? resolve(routesDir, 'confidentialite.tsx') : resolve(root, options.outPath)
157
+ const registerPath = resolve(root, REGISTER_PATH)
158
+ const wrapper = layoutRendersMain(root, noticePath) ? 'article' : 'main'
159
+ const notice = { path: noticePath, relativePath: relPosix(root, noticePath), content: noticeContent(options, wrapper) }
160
+ const register = { path: registerPath, relativePath: REGISTER_PATH, content: registerContent(options) }
161
+ if (options.write !== false) {
162
+ const taken = [notice, register].find(file => existsSync(file.path))
163
+ if (taken !== undefined && options.force !== true)
164
+ throw new Error(`prunelle: ${taken.relativePath} already exists: pass --force to overwrite it.`)
165
+ for (const file of [notice, register]) {
166
+ mkdirSync(dirname(file.path), { recursive: true })
167
+ writeFileSync(file.path, file.content)
168
+ }
169
+ }
170
+ return { notice, register }
171
+ }