@vielzeug/codex 26.10.5 → 26.10.6
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/data/catalog.json +81 -42
- package/data/llms-full.txt +1472 -18
- package/data/llms.txt +2 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +76 -0
- package/data/packages/arsenal.json +18 -4
- package/data/packages/courier.json +3 -3
- package/data/packages/prism.json +55 -52
- package/data/packages/refine.json +2 -2
- package/data/packages/tandem.json +1 -1
- package/data/refine.json +3872 -3722
- package/data/search.json +35 -14
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +2 -1
package/data/llms-full.txt
CHANGED
|
@@ -1,6 +1,1301 @@
|
|
|
1
1
|
# Vielzeug: Full Documentation
|
|
2
2
|
|
|
3
|
-
> Complete documentation for
|
|
3
|
+
> Complete documentation for 42 packages. Version: 26.10.6
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## @vielzeug/archive
|
|
8
|
+
|
|
9
|
+
**Category:** utilities
|
|
10
|
+
|
|
11
|
+
### Overview
|
|
12
|
+
|
|
13
|
+
## Why Archive?
|
|
14
|
+
|
|
15
|
+
You can share content entries with ranked browsing, filters, likes and account
|
|
16
|
+
erasure on Cloudflare Workers + D1. `defineArchiveCollection` supplies your JSON
|
|
17
|
+
payload schema and indexing rules; the Worker supplies sessions, guards,
|
|
18
|
+
idempotent publishing, cursors and rate limits.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
// Before: each deployment repeats validation, indexing and route plumbing.
|
|
22
|
+
|
|
23
|
+
// After: the deployment is one collection definition plus one factory call.
|
|
24
|
+
import { defineArchiveCollection } from '@vielzeug/archive';
|
|
25
|
+
import { createArchiveWorker } from '@vielzeug/archive/worker';
|
|
26
|
+
import { s } from '@vielzeug/spell';
|
|
27
|
+
|
|
28
|
+
const notes = defineArchiveCollection({
|
|
29
|
+
name: 'notes', contentVersion: 1,
|
|
30
|
+
payloadSchema: s.object({ title: s.string().min(1).max(128) }),
|
|
31
|
+
index: ({ title }) => ({ title, filter: null, tags: [] }),
|
|
32
|
+
});
|
|
33
|
+
export default createArchiveWorker([notes]);
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
| Feature | Archive | Hand-rolled Worker | BaaS (Firebase/Supabase) |
|
|
37
|
+
| ------------------------------------ | -------------------------------------------------------- | ------------------------------------ | ------------------------------------- |
|
|
38
|
+
| Bundle size (core) | | Depends on deployment code | Depends on selected SDK |
|
|
39
|
+
| Zero dependencies | No — Spell and jose | Depends on implementation | No — client SDK |
|
|
40
|
+
| Content knowledge in the core | none — one collection seam | baked in | rules everywhere |
|
|
41
|
+
| Canonical fresh-database D1 schema | in the package | Deployment-owned | Not a D1 backend |
|
|
42
|
+
| Idempotent publish w/ tombstones | built-in | rebuild it | rebuild it |
|
|
43
|
+
| GDPR erasure / export endpoints | built-in | rebuild it | partial |
|
|
44
|
+
| Strict DTO re-validation on read | every entry | optional | optional |
|
|
45
|
+
|
|
46
|
+
**Use Archive when** an app needs a shareable, ranked, liked community space for
|
|
47
|
+
content entries on Cloudflare Workers + D1, and can express its content as one strict
|
|
48
|
+
payload schema.
|
|
49
|
+
**Consider alternatives when** you need rich queries beyond filter/tag/search, live
|
|
50
|
+
collaboration, or a backend you do not control — Archive is deliberately one narrow,
|
|
51
|
+
hardened surface.
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
|
|
55
|
+
```sh [pnpm]
|
|
56
|
+
pnpm add @vielzeug/archive @vielzeug/spell
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```sh [npm]
|
|
60
|
+
npm install @vielzeug/archive @vielzeug/spell
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```sh [yarn]
|
|
64
|
+
yarn add @vielzeug/archive @vielzeug/spell
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Quick Start
|
|
68
|
+
|
|
69
|
+
A deployment is one collection definition plus one factory call. The definition
|
|
70
|
+
brings the payload schema and what to index; everything else — the emitted-entry
|
|
71
|
+
envelope, the content hash, the wire contract, the routes — is composed for you.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { defineArchiveCollection } from '@vielzeug/archive';
|
|
75
|
+
import { createArchiveWorker } from '@vielzeug/archive/worker';
|
|
76
|
+
import { s } from '@vielzeug/spell';
|
|
77
|
+
|
|
78
|
+
// The collection's payload: one strict schema is the whole content contract.
|
|
79
|
+
const payloadSchema = s.object({
|
|
80
|
+
cuisine: s.enum(['italian', 'japanese']),
|
|
81
|
+
ingredients: s.array(s.string().trim().min(1).max(64)).min(1).max(20),
|
|
82
|
+
name: s.string().trim().min(1).max(32),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const recipesCollection = defineArchiveCollection({
|
|
86
|
+
canonicalize: (payload) => ({ ...payload, ingredients: [...payload.ingredients].sort() }),
|
|
87
|
+
contentVersion: 1,
|
|
88
|
+
filters: ['italian', 'japanese'],
|
|
89
|
+
index: (payload) => ({
|
|
90
|
+
filter: payload.cuisine,
|
|
91
|
+
tags: [payload.ingredients.length ({ title, filter: null, tags: [] }),
|
|
92
|
+
});
|
|
93
|
+
const response = await fetch('/api/v1/collections/notes/entries?sort=liked');
|
|
94
|
+
if (!response.ok) throw new Error('Archive unavailable');
|
|
95
|
+
const parsed = notes.contract.page.parse(await response.json());
|
|
96
|
+
console.log(parsed.entries);
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Features
|
|
100
|
+
|
|
101
|
+
- `defineArchiveCollection` — the one content seam: payload schema, canonicalization, filter/tag/title derivation, union-typed vocabularies
|
|
102
|
+
- `createArchiveWorker` — the whole routes/auth/limits/SQL stack from registered collections
|
|
103
|
+
- `collection.contract` — entry, page, publish/update input schemas shared by client and Worker
|
|
104
|
+
- `ARCHIVE_LIMITS` + `archiveHealthSchema` — the application bounds, advertised by health and validated on both sides
|
|
105
|
+
- `archiveAuthHealthSchema` + `AUTH_SCHEMA_VERSION` — typed issuer readiness checked against the issuer DDL stamp
|
|
106
|
+
- `archiveErrorResponseSchema` — the one error envelope, code-typed across the wire
|
|
107
|
+
- `createAuthWorker` — scanner-safe confirmation, live session-version enforcement, durable budgets, metadata export and coordinated erasure
|
|
108
|
+
- `AUTH_ISSUER_SERVICE` — required uncached issuer check after local catalog JWT verification
|
|
109
|
+
- `ArchiveDerivationError` — distinguishes faulty collection code from invalid submitted content
|
|
110
|
+
- Moderation — reader reports, the operator soft-hide and the report queue, keyed on a verified `roles` claim
|
|
111
|
+
- `worker.tap()` / `issuer.tap()` — typed sanitized runtime events; neither core logs by default
|
|
112
|
+
- `migrations/` — canonical fresh-database DDL with the storage stamp health reads back; no upgrade framework
|
|
113
|
+
|
|
114
|
+
## Documentation
|
|
115
|
+
|
|
116
|
+
- [Usage Guide](./usage.md) — stand up a collection, deploy the Worker, wire the client.
|
|
117
|
+
- [API Reference](./api.md) — every export, all three entry points, the full route table.
|
|
118
|
+
- [Examples](./examples.md) — recipes from first deployment to GDPR erasure.
|
|
119
|
+
- [Release Status](./migration.md) — unreleased package and fresh-database scope.
|
|
120
|
+
|
|
121
|
+
## See Also
|
|
122
|
+
|
|
123
|
+
- [Spell](/spell/) — every payload schema here is a spell schema; the core composes envelopes from it.
|
|
124
|
+
- [Courier](/courier/) — the HTTP client shape an app's frontend mirrors to consume these routes.
|
|
125
|
+
- [Rune](/rune/) — the structured logger a deployment points `worker.tap()` events at.
|
|
126
|
+
|
|
127
|
+
### API Reference
|
|
128
|
+
|
|
129
|
+
## API Overview
|
|
130
|
+
|
|
131
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
132
|
+
| --- | --- | --- | --- |
|
|
133
|
+
| `defineArchiveCollection` | Compose validation, indexing, identity and wire schemas | Sync | Invalid content derives to `null`; callback faults throw |
|
|
134
|
+
| `createArchiveWorker` | Build the catalog Worker | Sync | Collection names must be unique |
|
|
135
|
+
| `createAuthWorker` | Build the passwordless issuer | Sync | `AUTH_ARCHIVE` is required |
|
|
136
|
+
| `worker.tap`, `issuer.tap` | Observe sanitized runtime outcomes | Sync | Neither core logs by default; observer exceptions are swallowed |
|
|
137
|
+
| `ArchiveDerivationError` | Identify a collection implementation/runtime fault | Sync | Faults become sanitized 500s, not content-validation 422s |
|
|
138
|
+
| `ARCHIVE_LIMITS` | Shared application bounds | Sync | Page bounds do not cap total exports |
|
|
139
|
+
| `archiveErrorResponseSchema`, `archiveAuthHealthSchema` | Validate error and issuer-health responses | Sync | Unknown error codes and health states reject |
|
|
140
|
+
| `ArchiveError`, `ArchiveDefinitionError` | Public base and invalid-definition errors | Sync | Thrown locally, not transmitted as error objects |
|
|
141
|
+
| `sessionCookieValue` | Compose shared session-cookie attributes | Sync | Deployments must choose `secure` from their environment |
|
|
142
|
+
| `isWellFormedText` | Check control characters and lone surrogates | Sync | Does not trim or impose a length bound |
|
|
143
|
+
|
|
144
|
+
## Package Entry Point
|
|
145
|
+
|
|
146
|
+
| Import | Purpose |
|
|
147
|
+
| --- | --- |
|
|
148
|
+
| `@vielzeug/archive` | Browser-safe collections, constants, schemas and errors |
|
|
149
|
+
| `@vielzeug/archive/worker` | Catalog factory, issuer-session service binding and event types |
|
|
150
|
+
| `@vielzeug/archive/auth` | Issuer factory, operator lifetime and binding types |
|
|
151
|
+
|
|
152
|
+
## Collections
|
|
153
|
+
|
|
154
|
+
### `defineArchiveCollection`
|
|
155
|
+
|
|
156
|
+
Creates a frozen collection and its contract; malformed names, versions or vocabularies throw `ArchiveDefinitionError`.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
function defineArchiveCollection(definition: ArchiveCollectionDefinition): ArchiveCollection;
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
| Parameter | Contract |
|
|
163
|
+
| --- | --- |
|
|
164
|
+
| `name` | Lowercase `[a-z0-9-]{1,32}` |
|
|
165
|
+
| `contentVersion` | Positive safe integer |
|
|
166
|
+
| `payloadSchema` | Spell schema whose output is a stable JSON object |
|
|
167
|
+
| `filters`, `tags` | Optional readonly arrays; omitted means empty vocabulary |
|
|
168
|
+
| `canonicalize` | Optional pure, idempotent, schema-valid normalization |
|
|
169
|
+
| `index` | Derive `filter`, `tags` and searchable `title` without mutating the payload |
|
|
170
|
+
|
|
171
|
+
**Returns:** `ArchiveCollection`.
|
|
172
|
+
|
|
173
|
+
**Example:** define and derive one collection without Worker bindings.
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import { defineArchiveCollection } from '@vielzeug/archive';
|
|
177
|
+
import { s } from '@vielzeug/spell';
|
|
178
|
+
|
|
179
|
+
const recipes = defineArchiveCollection({
|
|
180
|
+
name: 'recipes',
|
|
181
|
+
contentVersion: 1,
|
|
182
|
+
payloadSchema: s.object({ name: s.string().min(1).max(32) }),
|
|
183
|
+
index: (payload) => ({ filter: null, tags: [], title: payload.name }),
|
|
184
|
+
});
|
|
185
|
+
const derived = await recipes.derive({ name: 'Rice' });
|
|
186
|
+
if (derived === null) throw new Error('Invalid recipe');
|
|
187
|
+
console.log(derived.contentHash);
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
| Method / property | Result |
|
|
191
|
+
| --- | --- |
|
|
192
|
+
| `derive(raw)` | `Promise` |
|
|
193
|
+
| `contract.entry` | Public entry schema |
|
|
194
|
+
| `contract.ownedEntry`, `ownedEntries` | Owner view with `clientKey` and `hidden` |
|
|
195
|
+
| `contract.page` | Entries and forward/backward cursors |
|
|
196
|
+
| `contract.publishInput`, `updateInput` | Publish and revision-guarded update request schemas |
|
|
197
|
+
| `filters`, `tags` | Frozen vocabulary snapshots |
|
|
198
|
+
|
|
199
|
+
`derive` returns `null` for invalid JSON objects, schema-invalid input, invalid titles, too many tags and oversized canonical payloads. Unexpected schema, callback or hashing failures throw `ArchiveDerivationError`. Non-idempotent or schema-invalid canonicalization, unstable schema transformations, index mutation and out-of-vocabulary projections are also derivation faults. Routes map `null` to 422 `invalid-payload` and faults to a sanitized 500 `internal`.
|
|
200
|
+
Schema output that is lossy or no longer JSON is a derivation fault, not invalid
|
|
201
|
+
submitted content. Invalid index-result shapes also throw.
|
|
202
|
+
|
|
203
|
+
Const generics preserve the content-version literal and infer filter/tag unions from vocabulary arrays without `as const`. `NoInfer` prevents `index` from widening those unions; omitted arrays infer `never`, permitting only `filter: null` and empty tags.
|
|
204
|
+
|
|
205
|
+
Objects serialize with recursively sorted keys; arrays preserve order unless your canonicalizer changes it. SHA-256 hashes the core-owned `{contentVersion, payload}` envelope. Response schemas require stored payloads to remain stable under parsing; a response-validation fault has stage `response`.
|
|
206
|
+
|
|
207
|
+
`filter`, tags and searchable title are persisted projections, not computed during reads. Changing `index` or its vocabulary does not update stored rows. The active definition and persisted dataset must remain consistent; Archive has no projection-update or historical-schema API.
|
|
208
|
+
|
|
209
|
+
## Worker and Maintenance
|
|
210
|
+
|
|
211
|
+
### `createArchiveWorker`
|
|
212
|
+
|
|
213
|
+
Returns the catalog request/scheduled handler and its observation side channel.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
function createArchiveWorker(
|
|
217
|
+
collections: readonly ArchiveCollection[],
|
|
218
|
+
): ArchiveWorkerHandler;
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
**Returns:** `ArchiveWorkerHandler`; duplicate names throw `ArchiveDefinitionError` at registration.
|
|
222
|
+
|
|
223
|
+
**Example:** export a deployable Worker using the package's structural bindings.
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import { defineArchiveCollection } from '@vielzeug/archive';
|
|
227
|
+
import { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';
|
|
228
|
+
import { s } from '@vielzeug/spell';
|
|
229
|
+
|
|
230
|
+
const notes = defineArchiveCollection({
|
|
231
|
+
name: 'notes', contentVersion: 1,
|
|
232
|
+
payloadSchema: s.object({ title: s.string().min(1).max(128) }),
|
|
233
|
+
index: ({ title }) => ({ title, filter: null, tags: [] }),
|
|
234
|
+
});
|
|
235
|
+
export default createArchiveWorker([notes]);
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
| Method | Contract |
|
|
239
|
+
| --- | --- |
|
|
240
|
+
| `fetch(request, env, ctx)` | Returns `Promise` |
|
|
241
|
+
| `scheduled(controller, env, ctx)` | Sweeps expired retry keys and revocation tombstones; emits failures and rethrows |
|
|
242
|
+
| `tap(handler, { signal? }?)` | Returns unsubscribe; a pre-aborted signal registers nothing |
|
|
243
|
+
|
|
244
|
+
`AUTH_ISSUER_SERVICE` is a required `fetch`-shaped service binding to the issuer.
|
|
245
|
+
The catalog verifies the signed JWT locally, then asks the issuer to validate its
|
|
246
|
+
current account session version. It does not cache successful issuer verdicts.
|
|
247
|
+
If the service exchange fails or exceeds its fixed 5000 ms timeout (body decoding
|
|
248
|
+
included), the catalog returns `503 auth-unavailable`; the timeout does not cancel
|
|
249
|
+
work already started by the issuer.
|
|
250
|
+
|
|
251
|
+
Only anonymous entry lists can use the 30-second edge cache. Any `Cookie` or `Authorization` header disables caching, even if invalid or empty. Detail, metadata, private and error responses are `no-store`. Public reads do not verify sessions.
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
### `worker.tap`
|
|
256
|
+
|
|
257
|
+
Observes typed request, scheduled and cache-failure events without affecting request behavior.
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
tap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
**Returns:** an unsubscribe function; abort detaches the observer. Diagnostics contain categories and trusted configuration field names, never raw errors, SQL, subjects, aliases, tokens or URLs.
|
|
264
|
+
|
|
265
|
+
**Example:** observe a Worker and detach explicitly.
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
import { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';
|
|
269
|
+
|
|
270
|
+
const worker = createArchiveWorker([]);
|
|
271
|
+
const stop = worker.tap((event) => console.log(JSON.stringify(event)));
|
|
272
|
+
stop();
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
---
|
|
276
|
+
|
|
277
|
+
## Identity Issuer
|
|
278
|
+
|
|
279
|
+
### `createAuthWorker`
|
|
280
|
+
|
|
281
|
+
Returns the passwordless email issuer with account export and coordinated erasure.
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
function createAuthWorker(): AuthWorkerHandler;
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
**Returns:** `AuthWorkerHandler`.
|
|
288
|
+
|
|
289
|
+
**Example:** export an issuer configured through deployment bindings.
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import { createAuthWorker, type AuthWorkerEnv } from '@vielzeug/archive/auth';
|
|
293
|
+
|
|
294
|
+
export default createAuthWorker();
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
| Method | Contract |
|
|
298
|
+
| --- | --- |
|
|
299
|
+
| `fetch(request, env, ctx?)` | Returns `Promise` |
|
|
300
|
+
| `scheduled(controller, env, ctx?)` | Removes expired links, closed send windows and unverified unreferenced accounts |
|
|
301
|
+
| `tap(handler, { signal? }?)` | Observes typed `AuthEvent`; returns unsubscribe; pre-aborted signals are inert |
|
|
302
|
+
|
|
303
|
+
Magic links expire after 15 minutes and work once. The durable per-email budget allows three sends per hour; consumption, expiration and send failure do not refund it. Ordinary sessions last at most 30 days. Operator sessions use `OPERATOR_SESSION_MAX_AGE_SECONDS` (900 seconds). `OPERATOR_EMAILS` controls newly minted role claims.
|
|
304
|
+
|
|
305
|
+
The issuer-global admission budget is durable D1 state in `auth_sign_in_budget`:
|
|
306
|
+
20 requests per 60-second window before account creation or email delivery.
|
|
307
|
+
This supplements, rather than replaces, the durable per-email budget. No external
|
|
308
|
+
rate-limiter binding is required.
|
|
309
|
+
Admission spends are not refunded after later database or email failures.
|
|
310
|
+
Request emails are trimmed and lowercased before validation. `SENDER_ADDRESS`
|
|
311
|
+
must already be canonical; `OPERATOR_EMAILS` entries are trimmed and lowercased
|
|
312
|
+
before validation.
|
|
313
|
+
|
|
314
|
+
Sign-in requests create pending account rows with `lastSignInAt: null`. Successful
|
|
315
|
+
redemption atomically claims the one-use link and stamps the account's sign-in
|
|
316
|
+
time. The sweep deletes expired links and closed per-user send windows, then
|
|
317
|
+
unverified accounts with neither remaining links nor send-budget references.
|
|
318
|
+
Verified accounts are retained until explicit account deletion.
|
|
319
|
+
|
|
320
|
+
`@vielzeug/archive/auth` exports `OPERATOR_SESSION_MAX_AGE_SECONDS = 900` alongside
|
|
321
|
+
the factory and issuer binding types.
|
|
322
|
+
|
|
323
|
+
`AUTH_JWT_PREVIOUS_PUBLIC_JWKS` optionally publishes retired public RS256 keys and verifies sessions minted before rotation; private members reject configuration. The package has no demo sign-in routes.
|
|
324
|
+
|
|
325
|
+
Opening a magic link performs a safe GET that displays a click-confirmation page,
|
|
326
|
+
not redemption. Only a marked POST from an exact allowed origin or
|
|
327
|
+
`PUBLIC_ORIGIN` consumes `{ token }` and returns 204 with the session cookie. The
|
|
328
|
+
confirmation page navigates to `/signed-in` after success; the POST is not a
|
|
329
|
+
redirect. Confirmation responses are `no-store` with no-referrer and restrictive
|
|
330
|
+
CSP; the page removes the token from the address bar and loads no external assets.
|
|
331
|
+
GET displays confirmation for any syntactically valid token, including a used
|
|
332
|
+
token; only POST establishes whether the link is still redeemable. POST accepts
|
|
333
|
+
exactly `{ token }` and rejects query parameters.
|
|
334
|
+
|
|
335
|
+
The issuer never logs directly. `tap` emits sanitized request and scheduled
|
|
336
|
+
outcomes; observer failures are swallowed, abort detaches the observer and failed
|
|
337
|
+
scheduled work emits then rethrows. `AuthDiagnostic` reports only a category.
|
|
338
|
+
|
|
339
|
+
## HTTP Routes
|
|
340
|
+
|
|
341
|
+
Every route below is mounted under `/api/v1`. Mutation guards require an exact allowed `Origin` and `x-archive-request: 1`. Registered publishers pin `x-archive-publisher` to the identity captured when preparing private requests. The header is a freshness precondition, not authority.
|
|
342
|
+
|
|
343
|
+
| Route | Contract |
|
|
344
|
+
| --- | --- |
|
|
345
|
+
| `GET /health` | Public catalog readiness; 200 `ok` or 503 `degraded` |
|
|
346
|
+
| `POST /sign-out` | Catalog-local sign-out; `{ ok: true }` and expired session cookie, without issuer access |
|
|
347
|
+
| `GET /collections/:collection` | Collection metadata |
|
|
348
|
+
| `GET /collections/:collection/entries` | `author`, `filter`, `tag`, `search`, `sort`, `cursor`, `limit`; bidirectional entry page |
|
|
349
|
+
| `POST /collections/:collection/entries` | `{ clientKey, payload }`; 201 create or 200 replay |
|
|
350
|
+
| `GET /collections/:collection/entries/:id` | Public entry; always `no-store` |
|
|
351
|
+
| `PUT /collections/:collection/entries/:id` | Owner-only `{ expectedRevision, payload }` |
|
|
352
|
+
| `DELETE /collections/:collection/entries/:id` | Owner or operator removal; 204 |
|
|
353
|
+
| `PUT` / `DELETE /collections/:collection/entries/:id/like` | Like / unlike visible entries only; guarded write and response; like-state response |
|
|
354
|
+
| `POST /collections/:collection/entries/:id/report` | `{ reason }`; idempotent per entry/reporter; 204 |
|
|
355
|
+
| `PUT` / `DELETE /collections/:collection/entries/:id/hidden` | Operator hide / unhide; 204 |
|
|
356
|
+
| `GET /collections/:collection/reports` | Operator page; `status=unresolved` (default) or `resolved`, `cursor`, `limit` |
|
|
357
|
+
| `PUT /collections/:collection/reports/:id/resolved` | Operator resolves report by its unique report ID; idempotent 204 |
|
|
358
|
+
| `DELETE /publishers/:id` | Operator erases Archive profile; not issuer account |
|
|
359
|
+
| `GET /moderation-log` | Operator forward page; `cursor`, `limit` |
|
|
360
|
+
| `GET` / `POST` / `PUT /me` | Identity, register with optional `{ name }`, rename with required `{ name }` |
|
|
361
|
+
| `DELETE /me` | Profile-only cascade; 204; does not clear cookie |
|
|
362
|
+
| `DELETE /me/account` | Revoke issuer/subject and atomically erase profile; 204; coordinated issuer-erasure seam |
|
|
363
|
+
| `GET /me/publications?collection=…` | Owner entries including hidden state and retry keys |
|
|
364
|
+
| `GET /me/likes` | Forward page `{ ids, cursor }`; `cursor`, `limit` |
|
|
365
|
+
| `GET /me/likes?ids=…` | Subset lookup `{ ids }`; at most `likeStateIds` input IDs |
|
|
366
|
+
| `GET /me/reports` | Own forward report page across collections; `cursor`, `limit` |
|
|
367
|
+
| `GET /auth/health` | Public issuer readiness; typed `AuthHealth`, 200 `ok` or 503 `degraded`; no email or peer probe |
|
|
368
|
+
| `GET /auth/session` | Internal issuer-session check for the catalog service binding; exact `{ ok: true }`, `no-store`, no PII; 401 for an invalid, stale or absent-account session |
|
|
369
|
+
| `POST /auth/sign-out-all` | Requires marker, exact origin, session and captured `ACCOUNT_HEADER`; atomically increments `session_version`, deletes outstanding links, preserves account and catalog data; 200 `{ ok: true }` with an expired cookie only on durable success |
|
|
370
|
+
| `GET /auth/jwks.json` | Active and configured retired public verification keys |
|
|
371
|
+
| `POST /auth/sign-in` | `{ email }` (trimmed and lowercased); 202 `{ ok: true }` |
|
|
372
|
+
| `GET /auth/verify?token=…` | Safe no-store click-confirmation page; no token consumption or session change |
|
|
373
|
+
| `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |
|
|
374
|
+
| `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |
|
|
375
|
+
| `DELETE /auth/account` | Requires `ACCOUNT_HEADER` with the captured issuer account UUID; catalog `/me/account` via `AUTH_ARCHIVE`, require exact 204, then issuer user and cookie clear; 204 |
|
|
376
|
+
|
|
377
|
+
Forward pages are newest first with opaque context-bound keyset cursors. Keep the same query context when following a cursor; end at `cursor: null`. `maxPageSize` bounds each page, not the total number of liked IDs, reports or audit actions you can export. The subset-like query is not a page and cannot combine `ids` with `cursor` or `limit`.
|
|
378
|
+
|
|
379
|
+
Full erasure creates an issuer/subject revocation tombstone for 30 days plus ten
|
|
380
|
+
seconds and deletes the profile in the same transaction. Catalog authentication
|
|
381
|
+
rejects that subject with 401 on ordinary private routes; registration also checks
|
|
382
|
+
revocation in SQL to prevent resurrection races. Only `DELETE /me/account` may
|
|
383
|
+
bypass the issuer session lookup, and only to retry erasure with the original
|
|
384
|
+
signed session of the same principal while its existing revocation tombstone is
|
|
385
|
+
valid; JWT signature and claims are still verified. It is not a general
|
|
386
|
+
stale-session exception: initial erasure validates the issuer session. The
|
|
387
|
+
issuer-facing `DELETE /auth/account` always checks the current session version
|
|
388
|
+
before calling the catalog, so retrying it after completed erasure returns 401
|
|
389
|
+
because the account is absent.
|
|
390
|
+
Direct profile-only `DELETE /me` allows later registration using the same session.
|
|
391
|
+
The sweep removes expired tombstones. Re-enrollment through the reference issuer
|
|
392
|
+
creates a fresh account UUID subject; an external issuer must issue a new subject
|
|
393
|
+
to re-enroll during the revocation window.
|
|
394
|
+
|
|
395
|
+
The issuer stores `auth_users.session_version` as a safe non-negative integer,
|
|
396
|
+
defaulting to `0`. Every session JWT carries the current value as the required
|
|
397
|
+
`sessionVersion` claim. Each ordinary issuer-authenticated route compares that
|
|
398
|
+
claim to the current account row; a mismatch is unauthenticated. `POST
|
|
399
|
+
/api/v1/auth/sign-out-all` checks the captured issuer account UUID against the
|
|
400
|
+
verified subject before atomically incrementing the version and deleting pending
|
|
401
|
+
links. A changed account answers 409 `account-changed`; a failed request does not
|
|
402
|
+
clear the cookie. This revokes all sessions, including the caller's, after a
|
|
403
|
+
successful response. Requests authorized before revocation may finish; there is
|
|
404
|
+
no cross-database transactional or in-flight cancellation guarantee.
|
|
405
|
+
|
|
406
|
+
The catalog requires `AUTH_ISSUER_SERVICE`, a service binding to the issuer. After
|
|
407
|
+
local JWT signature/claims verification, it requests
|
|
408
|
+
`GET /api/v1/auth/session` through that binding on every private request. Only a
|
|
409
|
+
strictly validated 401 `unauthenticated` remains a 401. Malformed, unexpected,
|
|
410
|
+
provider and 5xx responses become 503 `auth-unavailable`; there is no authority
|
|
411
|
+
cache. Both service directions use a fixed 5000 ms timeout that includes body
|
|
412
|
+
decoding. The issuer's `/api/v1/auth/session` is an internal
|
|
413
|
+
service contract, not a frontend session API.
|
|
414
|
+
|
|
415
|
+
Issuer readiness is independent of catalog readiness. `GET
|
|
416
|
+
/api/v1/auth/health` returns `archiveAuthHealthSchema` as `AuthHealth`; its
|
|
417
|
+
read-only probe checks configuration, a signing and verification key proof,
|
|
418
|
+
binding shapes, the singleton `auth_schema_meta` stamp against
|
|
419
|
+
`AUTH_SCHEMA_VERSION`, and readability of expected tables, columns and triggers.
|
|
420
|
+
It does not write, send email or probe the catalog service. Responses are
|
|
421
|
+
sanitized.
|
|
422
|
+
Configuration failure, database failure and schema mismatch return HTTP 503
|
|
423
|
+
with `status: 'degraded'` and the corresponding reason.
|
|
424
|
+
|
|
425
|
+
Effective hide, unhide, operator removal and publisher erasure append audit rows atomically with the state transition. Concurrent idempotent no-ops append nothing. Audit rows contain opaque IDs, not names or content, and have no foreign keys so they outlive erasure. Resolving a report sets `resolvedAt`; it is not one of the four audit action kinds.
|
|
426
|
+
|
|
427
|
+
## Constants and Schemas
|
|
428
|
+
|
|
429
|
+
| Export | Value or parsed output |
|
|
430
|
+
| --- | --- |
|
|
431
|
+
| `ARCHIVE_CONTRACT_VERSION`, `ARCHIVE_SCHEMA_VERSION` | Both debut at `1`; wire and storage versions are independent |
|
|
432
|
+
| `AUTH_SCHEMA_VERSION` | `1`; issuer DDL stamp checked by `/auth/health` |
|
|
433
|
+
| `ARCHIVE_COLLECTION_NAME_PATTERN` | `/^[a-z0-9-]{1,32}$/` |
|
|
434
|
+
| `ARCHIVE_OPERATOR_ROLE` | `'archive-operator'` |
|
|
435
|
+
| `SESSION_COOKIE_NAME`, `SESSION_COOKIE_PATH` | `'archive_session'`, `'/api/v1'` |
|
|
436
|
+
| `SESSION_MAX_AGE_SECONDS` | `2592000` |
|
|
437
|
+
| `OPERATOR_SESSION_MAX_AGE_SECONDS` | `900`; shared root contract, also re-exported by `/auth` |
|
|
438
|
+
| `ACCOUNT_HEADER` | `'X-Archive-Account'`; required issuer-account UUID on coordinated erasure |
|
|
439
|
+
| `PUBLISHER_HEADER`, `REQUEST_MARKER_HEADER` | `'x-archive-publisher'`, `'x-archive-request'` |
|
|
440
|
+
| `ILL_FORMED_TEXT`, `isWellFormedText(value: string): boolean` | Reject control characters and lone UTF-16 surrogates |
|
|
441
|
+
| `uuidSchema`, `isoTimestampSchema`, `hex64Schema` | UUID, ISO timestamp, lowercase SHA-256 hex strings |
|
|
442
|
+
| `archiveAliasSchema` | Trimmed, well-formed alias of at most 24 characters |
|
|
443
|
+
| `archiveAuthorSchema` | `{ id: string; name: string }` |
|
|
444
|
+
| `archiveIdentitySchema` | `ArchiveIdentity` |
|
|
445
|
+
| `archiveAccountSchema` | `ArchiveAccount`; issuer metadata, excluding private fields |
|
|
446
|
+
| `archiveLimitsSchema` | All numeric `ARCHIVE_LIMITS` fields |
|
|
447
|
+
| `archiveHealthSchema` | `ArchiveHealth` |
|
|
448
|
+
| `archiveAuthHealthSchema` | `AuthHealth` |
|
|
449
|
+
| `archiveErrorResponseSchema` | `ArchiveErrorResponse` |
|
|
450
|
+
| `archiveOkSchema` | `{ ok: true }` |
|
|
451
|
+
| `archiveCollectionMetaSchema` | `ArchiveCollectionMeta` |
|
|
452
|
+
| `archiveLikedIdsSchema` | `{ ids: string[] }` subset response |
|
|
453
|
+
| `archiveLikesPageSchema` | `ArchiveLikesPage` |
|
|
454
|
+
| `archiveLikeStateSchema` | `{ id: string; likeCount: number; liked: boolean }` |
|
|
455
|
+
| `archiveReportsSchema`, `archiveOwnReportsSchema` | `ArchiveReports`, `ArchiveOwnReports` |
|
|
456
|
+
| `archiveModerationLogSchema` | `ArchiveModerationLog` |
|
|
457
|
+
| `archiveSortSchema` | `ArchiveSort` |
|
|
458
|
+
| `ARCHIVE_ERROR_CODES` | Values of `ArchiveErrorCode` below |
|
|
459
|
+
| `ARCHIVE_MODERATION_ACTIONS` | `['hide', 'unhide', 'remove', 'erase-publisher']` |
|
|
460
|
+
|
|
461
|
+
### `sessionCookieValue`
|
|
462
|
+
|
|
463
|
+
Composes a session cookie using the shared security attributes.
|
|
464
|
+
|
|
465
|
+
```ts
|
|
466
|
+
function sessionCookieValue(token: string, options: { maxAgeSeconds: number; secure: boolean }): string;
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
| Parameter | Contract |
|
|
470
|
+
| --- | --- |
|
|
471
|
+
| `token` | Session token, or empty string when clearing |
|
|
472
|
+
| `options.maxAgeSeconds` | Cookie lifetime; `0` clears it |
|
|
473
|
+
| `options.secure` | Include `Secure` for production HTTPS |
|
|
474
|
+
|
|
475
|
+
**Returns:** the `Set-Cookie` value with `HttpOnly`, `SameSite=Strict`, the shared path and optional `Secure`.
|
|
476
|
+
|
|
477
|
+
**Example:** clear the production cookie.
|
|
478
|
+
|
|
479
|
+
```ts
|
|
480
|
+
import { sessionCookieValue } from '@vielzeug/archive';
|
|
481
|
+
|
|
482
|
+
const expiredCookie = sessionCookieValue('', { maxAgeSeconds: 0, secure: true });
|
|
483
|
+
console.log(expiredCookie);
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
---
|
|
487
|
+
|
|
488
|
+
### `isWellFormedText`
|
|
489
|
+
|
|
490
|
+
Checks text for control characters and lone UTF-16 surrogates.
|
|
491
|
+
|
|
492
|
+
```ts
|
|
493
|
+
function isWellFormedText(value: string): boolean;
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
**Returns:** `true` when `ILL_FORMED_TEXT` does not match; it does not trim or impose bounds.
|
|
497
|
+
|
|
498
|
+
**Example:** validate text independently of the alias schema.
|
|
499
|
+
|
|
500
|
+
```ts
|
|
501
|
+
import { isWellFormedText } from '@vielzeug/archive';
|
|
502
|
+
|
|
503
|
+
console.log(isWellFormedText('Rice'), isWellFormedText('\u0000'));
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
### `ARCHIVE_LIMITS`
|
|
507
|
+
|
|
508
|
+
`ARCHIVE_LIMITS` is frozen with these values:
|
|
509
|
+
|
|
510
|
+
```ts
|
|
511
|
+
const limits = {
|
|
512
|
+
aliasChars: 24, cursorChars: 1024, idempotencyRetentionMs: 172800000,
|
|
513
|
+
likeStateIds: 50, maxPageSize: 50, maxPublications: 50, pageSize: 10,
|
|
514
|
+
payloadBytes: 8192, publicCacheSeconds: 30, reportReasonChars: 256,
|
|
515
|
+
requestBytes: 12288, searchChars: 64, searchTerms: 6, tagsPerEntry: 16,
|
|
516
|
+
titleChars: 128, vocabChars: 64,
|
|
517
|
+
};
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
## Types
|
|
521
|
+
|
|
522
|
+
The following definitions use `Schema` from `@vielzeug/spell`. Schema-derived aliases show their complete output shape.
|
|
523
|
+
|
|
524
|
+
```ts
|
|
525
|
+
interface ArchiveIndexing {
|
|
526
|
+
filter: F | null;
|
|
527
|
+
tags: readonly T[];
|
|
528
|
+
title: string;
|
|
529
|
+
}
|
|
530
|
+
interface ArchiveCollectionDefinition {
|
|
531
|
+
canonicalize?(payload: P): P;
|
|
532
|
+
contentVersion: C;
|
|
533
|
+
filters?: readonly F[];
|
|
534
|
+
index(payload: P): ArchiveIndexing, NoInfer>;
|
|
535
|
+
name: string;
|
|
536
|
+
payloadSchema: Schema;
|
|
537
|
+
tags?: readonly T[];
|
|
538
|
+
}
|
|
539
|
+
interface ArchiveDerivation {
|
|
540
|
+
canonicalJson: string;
|
|
541
|
+
contentHash: string;
|
|
542
|
+
contentVersion: number;
|
|
543
|
+
filter: string | null;
|
|
544
|
+
tags: readonly string[];
|
|
545
|
+
title: string;
|
|
546
|
+
}
|
|
547
|
+
interface ArchiveEntry {
|
|
548
|
+
author: { id: string; name: string };
|
|
549
|
+
contentHash: string;
|
|
550
|
+
contentVersion: C;
|
|
551
|
+
id: string;
|
|
552
|
+
likeCount: number;
|
|
553
|
+
payload: P;
|
|
554
|
+
publishedAt: string;
|
|
555
|
+
revision: number;
|
|
556
|
+
schemaVersion: typeof ARCHIVE_CONTRACT_VERSION;
|
|
557
|
+
updatedAt: string;
|
|
558
|
+
}
|
|
559
|
+
interface ArchiveOwnedEntry extends ArchiveEntry {
|
|
560
|
+
clientKey: string;
|
|
561
|
+
hidden: boolean;
|
|
562
|
+
}
|
|
563
|
+
interface ArchiveContract {
|
|
564
|
+
entry: Schema>;
|
|
565
|
+
ownedEntries: Schema[] }>;
|
|
566
|
+
ownedEntry: Schema>;
|
|
567
|
+
page: Schema>>;
|
|
568
|
+
publishInput: Schema;
|
|
569
|
+
updateInput: Schema;
|
|
570
|
+
}
|
|
571
|
+
interface ArchiveCollection {
|
|
572
|
+
readonly contentVersion: C;
|
|
573
|
+
readonly contract: ArchiveContract;
|
|
574
|
+
readonly derive: (raw: unknown) => Promise;
|
|
575
|
+
readonly filters: readonly string[];
|
|
576
|
+
readonly name: string;
|
|
577
|
+
readonly tags: readonly string[];
|
|
578
|
+
}
|
|
579
|
+
interface ArchivePage {
|
|
580
|
+
cursor: string | null;
|
|
581
|
+
entries: readonly T[];
|
|
582
|
+
previous: string | null;
|
|
583
|
+
}
|
|
584
|
+
type ArchiveSort = 'liked' | 'recent';
|
|
585
|
+
type ArchiveDerivationStage = 'schema' | 'canonicalize' | 'index' | 'hash' | 'response';
|
|
586
|
+
type ArchiveIdentity = { id: string; name: string; operator: boolean } | null;
|
|
587
|
+
type ArchiveAccount = {
|
|
588
|
+
id: string; email: string; createdAt: string; lastSignInAt: string | null;
|
|
589
|
+
};
|
|
590
|
+
type ArchiveCollectionMeta = { filters: string[]; name: string; tags: string[] };
|
|
591
|
+
type ArchiveLikesPage = { cursor: string | null; ids: string[] };
|
|
592
|
+
type ArchiveErrorCode =
|
|
593
|
+
| 'account-changed' | 'auth-unavailable' | 'bad-request' | 'conflict' | 'forbidden' | 'gone'
|
|
594
|
+
| 'internal' | 'invalid-payload' | 'likes-disabled' | 'method-not-allowed'
|
|
595
|
+
| 'not-found' | 'publisher-changed' | 'publishing-disabled' | 'quota'
|
|
596
|
+
| 'rate-limited' | 'record-unavailable' | 'timeout' | 'too-large'
|
|
597
|
+
| 'unauthenticated' | 'unavailable' | 'unsupported-media';
|
|
598
|
+
type ArchiveErrorResponse = {
|
|
599
|
+
error: { code: ArchiveErrorCode; message: string; requestId: string };
|
|
600
|
+
};
|
|
601
|
+
type ArchiveHealth = {
|
|
602
|
+
dbSchemaVersion: number | null;
|
|
603
|
+
features: { likes: boolean; publishing: boolean };
|
|
604
|
+
limits: {
|
|
605
|
+
aliasChars: number; cursorChars: number; idempotencyRetentionMs: number;
|
|
606
|
+
likeStateIds: number; maxPageSize: number; maxPublications: number;
|
|
607
|
+
pageSize: number; payloadBytes: number; publicCacheSeconds: number;
|
|
608
|
+
reportReasonChars: number; requestBytes: number; searchChars: number;
|
|
609
|
+
searchTerms: number; tagsPerEntry: number; titleChars: number; vocabChars: number;
|
|
610
|
+
};
|
|
611
|
+
schemaVersion: 1;
|
|
612
|
+
status: 'ok' | 'degraded';
|
|
613
|
+
reason: 'database-unavailable' | 'schema-mismatch' | null;
|
|
614
|
+
};
|
|
615
|
+
type AuthHealth = {
|
|
616
|
+
dbSchemaVersion: number | null;
|
|
617
|
+
schemaVersion: 1;
|
|
618
|
+
status: 'ok' | 'degraded';
|
|
619
|
+
reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null;
|
|
620
|
+
};
|
|
621
|
+
type ArchiveReports = {
|
|
622
|
+
cursor: string | null;
|
|
623
|
+
reports: {
|
|
624
|
+
id: string; createdAt: string; entryId: string; entryTitle: string;
|
|
625
|
+
reason: string; reporter: { id: string; name: string }; resolvedAt: string | null;
|
|
626
|
+
}[];
|
|
627
|
+
};
|
|
628
|
+
type ArchiveOwnReports = {
|
|
629
|
+
cursor: string | null;
|
|
630
|
+
reports: {
|
|
631
|
+
collection: string; createdAt: string; entryId: string; id: string;
|
|
632
|
+
reason: string; resolvedAt: string | null;
|
|
633
|
+
}[];
|
|
634
|
+
};
|
|
635
|
+
type ArchiveModerationAction = 'hide' | 'unhide' | 'remove' | 'erase-publisher';
|
|
636
|
+
type ArchiveModerationLog = {
|
|
637
|
+
cursor: string | null;
|
|
638
|
+
actions: {
|
|
639
|
+
id: string; action: ArchiveModerationAction; collection: string | null;
|
|
640
|
+
createdAt: string; operatorId: string; targetId: string;
|
|
641
|
+
}[];
|
|
642
|
+
};
|
|
643
|
+
```
|
|
644
|
+
|
|
645
|
+
Worker subpath types model only the binding methods the catalog calls.
|
|
646
|
+
|
|
647
|
+
```ts
|
|
648
|
+
interface D1Statement {
|
|
649
|
+
all(): Promise;
|
|
650
|
+
bind(...params: (string | number | null)[]): D1Statement;
|
|
651
|
+
first(): Promise;
|
|
652
|
+
run(): Promise;
|
|
653
|
+
}
|
|
654
|
+
interface D1Like {
|
|
655
|
+
batch(statements: D1Statement[]): Promise;
|
|
656
|
+
prepare(sql: string): D1Statement;
|
|
657
|
+
}
|
|
658
|
+
interface RateLimiterBinding {
|
|
659
|
+
limit(input: { key: string }): Promise;
|
|
660
|
+
}
|
|
661
|
+
interface ArchiveWorkerEnv {
|
|
662
|
+
AUTH_ISSUER_SERVICE: AuthIssuerServiceBinding;
|
|
663
|
+
ALLOWED_ORIGINS: string;
|
|
664
|
+
APP_ENV: string;
|
|
665
|
+
DB: D1Like;
|
|
666
|
+
JWT_AUDIENCE: string;
|
|
667
|
+
JWT_ISSUER: string;
|
|
668
|
+
JWT_JWKS_URL: string;
|
|
669
|
+
LIKES_ENABLED: string;
|
|
670
|
+
PUBLISHING_ENABLED: string;
|
|
671
|
+
RATE_LIMIT_KEY_SECRET: string;
|
|
672
|
+
READ_LIMIT: RateLimiterBinding;
|
|
673
|
+
WRITE_LIMIT: RateLimiterBinding;
|
|
674
|
+
}
|
|
675
|
+
interface AuthIssuerServiceBinding {
|
|
676
|
+
fetch(request: Request): Promise;
|
|
677
|
+
}
|
|
678
|
+
interface ArchiveExecutionContext {
|
|
679
|
+
waitUntil(promise: Promise): void;
|
|
680
|
+
}
|
|
681
|
+
type ArchiveDiagnostic =
|
|
682
|
+
| { readonly kind: 'configuration'; readonly field: string }
|
|
683
|
+
| { readonly kind: 'database' | 'record' | 'schema' | 'internal' | 'cache' | 'collection' };
|
|
684
|
+
interface ArchiveRequestEvent {
|
|
685
|
+
code: ArchiveErrorCode | 'ok';
|
|
686
|
+
diagnostic?: ArchiveDiagnostic;
|
|
687
|
+
ms: number;
|
|
688
|
+
requestId: string;
|
|
689
|
+
route: string;
|
|
690
|
+
status: number;
|
|
691
|
+
type: 'request';
|
|
692
|
+
}
|
|
693
|
+
type ArchiveScheduledEvent =
|
|
694
|
+
| { removed: number; type: 'scheduled'; status: 'ok' }
|
|
695
|
+
| { type: 'scheduled'; status: 'failed'; diagnostic: ArchiveDiagnostic };
|
|
696
|
+
type ArchiveEvent =
|
|
697
|
+
| ArchiveRequestEvent
|
|
698
|
+
| ArchiveScheduledEvent
|
|
699
|
+
| { readonly type: 'cache-error'; readonly diagnostic: ArchiveDiagnostic };
|
|
700
|
+
interface ArchiveWorkerHandler {
|
|
701
|
+
fetch(request: Request, env: E, ctx: ArchiveExecutionContext): Promise;
|
|
702
|
+
scheduled?(controller: unknown, env: E, ctx: ArchiveExecutionContext): void | Promise;
|
|
703
|
+
tap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;
|
|
704
|
+
}
|
|
705
|
+
```
|
|
706
|
+
|
|
707
|
+
Scheduled `removed` counts the combined expired retry-key and revocation rows.
|
|
708
|
+
|
|
709
|
+
Auth subpath types describe the sibling issuer and its required service binding.
|
|
710
|
+
|
|
711
|
+
```ts
|
|
712
|
+
interface SendEmail {
|
|
713
|
+
send(message: { from: string; html?: string; subject: string; text: string; to: string }): Promise;
|
|
714
|
+
}
|
|
715
|
+
interface AuthArchiveBinding {
|
|
716
|
+
fetch(request: Request): Promise;
|
|
717
|
+
}
|
|
718
|
+
interface AuthWorkerEnv {
|
|
719
|
+
ALLOWED_ORIGINS: string;
|
|
720
|
+
APP_ENV: string;
|
|
721
|
+
APP_NAME: string;
|
|
722
|
+
AUDIENCE: string;
|
|
723
|
+
AUTH_ARCHIVE: AuthArchiveBinding;
|
|
724
|
+
AUTH_DB: D1Like;
|
|
725
|
+
AUTH_EMAIL: SendEmail;
|
|
726
|
+
AUTH_ISSUER: string;
|
|
727
|
+
AUTH_JWT_PREVIOUS_PUBLIC_JWKS?: string;
|
|
728
|
+
AUTH_JWT_PRIVATE_JWK: string;
|
|
729
|
+
OPERATOR_EMAILS: string;
|
|
730
|
+
PUBLIC_ORIGIN: string;
|
|
731
|
+
SENDER_ADDRESS: string;
|
|
732
|
+
}
|
|
733
|
+
interface AuthWorkerHandler {
|
|
734
|
+
fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise;
|
|
735
|
+
scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise;
|
|
736
|
+
tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;
|
|
737
|
+
}
|
|
738
|
+
type AuthDiagnostic = {
|
|
739
|
+
readonly kind: 'configuration' | 'database' | 'email' | 'catalog' | 'internal';
|
|
740
|
+
};
|
|
741
|
+
type AuthEvent =
|
|
742
|
+
| {
|
|
743
|
+
readonly type: 'request';
|
|
744
|
+
readonly requestId: string;
|
|
745
|
+
readonly route:
|
|
746
|
+
| '/auth/account'
|
|
747
|
+
| '/auth/health'
|
|
748
|
+
| '/auth/jwks.json'
|
|
749
|
+
| '/auth/session'
|
|
750
|
+
| '/auth/sign-in'
|
|
751
|
+
| '/auth/sign-out-all'
|
|
752
|
+
| '/auth/verify'
|
|
753
|
+
| 'unmatched';
|
|
754
|
+
readonly status: number;
|
|
755
|
+
readonly code: ArchiveErrorCode | 'ok';
|
|
756
|
+
readonly ms: number;
|
|
757
|
+
readonly diagnostic?: AuthDiagnostic;
|
|
758
|
+
}
|
|
759
|
+
| { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }
|
|
760
|
+
| { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };
|
|
761
|
+
```
|
|
762
|
+
|
|
763
|
+
Issuer scheduled `removed` counts expired token rows, closed per-user send windows
|
|
764
|
+
and deleted unverified accounts. The singleton admission row is retained and its
|
|
765
|
+
window resets atomically on a later sign-in request.
|
|
766
|
+
|
|
767
|
+
## Errors
|
|
768
|
+
|
|
769
|
+
| Exported class | Trigger | Properties |
|
|
770
|
+
| --- | --- | --- |
|
|
771
|
+
| `ArchiveError` | Base for public package errors | `name`, `message`, optional `cause` |
|
|
772
|
+
| `ArchiveDefinitionError` | Invalid collection definition or duplicate registered collection names | Extends `ArchiveError` |
|
|
773
|
+
| `ArchiveDerivationError` | Unexpected schema/canonicalization/index/hash/response fault or violated collection invariant | Extends `ArchiveError`; readonly `stage: ArchiveDerivationStage`; optional `cause` |
|
|
774
|
+
|
|
775
|
+
`ArchiveError` and `ArchiveDefinitionError` accept `(message: string, opts?: ErrorOptions)`.
|
|
776
|
+
`ArchiveDerivationError` accepts `(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions)`.
|
|
777
|
+
Its message and cause are local diagnostics, not response content. Worker request
|
|
778
|
+
failures use the wire envelope, not these thrown classes. Internal `ApiError` and
|
|
779
|
+
`AuthOperationError` are not exported.
|
|
780
|
+
|
|
781
|
+
Stored entries that fail the current wire schema return 503 `record-unavailable`.
|
|
782
|
+
Unexpected exceptions in the collection's response-payload callbacks instead
|
|
783
|
+
throw `ArchiveDerivationError` with stage `response` and become sanitized 500s.
|
|
784
|
+
|
|
785
|
+
The complete public error signatures are:
|
|
786
|
+
|
|
787
|
+
```ts
|
|
788
|
+
class ArchiveError extends Error {
|
|
789
|
+
constructor(message: string, opts?: ErrorOptions);
|
|
790
|
+
}
|
|
791
|
+
class ArchiveDefinitionError extends ArchiveError {}
|
|
792
|
+
class ArchiveDerivationError extends ArchiveError {
|
|
793
|
+
readonly stage: ArchiveDerivationStage;
|
|
794
|
+
constructor(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions);
|
|
795
|
+
}
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
Catalog rate-limit responses use `Retry-After: 60`; configure catalog limiter periods to 60 seconds. Issuer admission/send-budget responses instead carry seconds until their durable window reopens. Health's degraded response is the health DTO, not an error envelope: schema mismatch reports the observed version; database unavailability reports `dbSchemaVersion: null`.
|
|
799
|
+
|
|
800
|
+
### Usage Guide
|
|
801
|
+
|
|
802
|
+
## Basic Usage
|
|
803
|
+
|
|
804
|
+
A deployment is a collection definition plus one factory call. Put the definition in a
|
|
805
|
+
module both sides import — the browser needs the composed schemas, the Worker needs
|
|
806
|
+
the collection itself.
|
|
807
|
+
|
|
808
|
+
```ts
|
|
809
|
+
// recipes-collection.ts — the one content contract, shared by both sides.
|
|
810
|
+
import { defineArchiveCollection } from '@vielzeug/archive';
|
|
811
|
+
import { s } from '@vielzeug/spell';
|
|
812
|
+
|
|
813
|
+
const payloadSchema = s.object({
|
|
814
|
+
cuisine: s.enum(['italian', 'japanese']),
|
|
815
|
+
ingredients: s.array(s.string().trim().min(1).max(64)).min(1).max(20),
|
|
816
|
+
name: s.string().trim().min(1).max(32),
|
|
817
|
+
});
|
|
818
|
+
|
|
819
|
+
export const recipesCollection = defineArchiveCollection({
|
|
820
|
+
// Ingredient order is not identity: the canonical form sorts, so reordered
|
|
821
|
+
// content hashes identically and updates as a no-op.
|
|
822
|
+
canonicalize: (payload) => ({ ...payload, ingredients: [...payload.ingredients].sort() }),
|
|
823
|
+
contentVersion: 1,
|
|
824
|
+
filters: ['italian', 'japanese'],
|
|
825
|
+
index: (payload) => ({
|
|
826
|
+
filter: payload.cuisine,
|
|
827
|
+
tags: [payload.ingredients.length console.log(JSON.stringify(event)));
|
|
828
|
+
|
|
829
|
+
export default worker;
|
|
830
|
+
```
|
|
831
|
+
|
|
832
|
+
The browser imports the same collection for its schemas — never the worker subpath:
|
|
833
|
+
|
|
834
|
+
```ts
|
|
835
|
+
import { recipesCollection } from './recipes-collection';
|
|
836
|
+
import { archiveIdentitySchema, PUBLISHER_HEADER } from '@vielzeug/archive';
|
|
837
|
+
|
|
838
|
+
const response = await fetch('/api/v1/collections/recipes/entries');
|
|
839
|
+
if (!response.ok) throw new Error('Archive unavailable');
|
|
840
|
+
const page = recipesCollection.contract.page.parse(await response.json());
|
|
841
|
+
const meResponse = await fetch('/api/v1/me', { credentials: 'same-origin' });
|
|
842
|
+
if (!meResponse.ok) throw new Error('Identity unavailable');
|
|
843
|
+
const me = archiveIdentitySchema.parse(await meResponse.json());
|
|
844
|
+
if (me === null) throw new Error('Register a publisher first');
|
|
845
|
+
const mineResponse = await fetch('/api/v1/me/publications?collection=recipes', {
|
|
846
|
+
credentials: 'same-origin', headers: { [PUBLISHER_HEADER]: me.id },
|
|
847
|
+
});
|
|
848
|
+
if (!mineResponse.ok) throw new Error('Own publications unavailable');
|
|
849
|
+
const owned = recipesCollection.contract.ownedEntries.parse(await mineResponse.json());
|
|
850
|
+
console.log(page.entries, owned.entries);
|
|
851
|
+
```
|
|
852
|
+
|
|
853
|
+
## The collection contract
|
|
854
|
+
|
|
855
|
+
`defineArchiveCollection` is the only place content knowledge lives. The definition is
|
|
856
|
+
validated at registration — a bad `name`, `contentVersion`, or any vocabulary value
|
|
857
|
+
(well-formed text, 1..`vocabChars` chars) throws there, never mid-request — and every
|
|
858
|
+
ordinary invalid content returns `null` → `422 invalid-payload`. Collection
|
|
859
|
+
implementation faults instead throw `ArchiveDerivationError` → sanitized
|
|
860
|
+
`500 internal`:
|
|
861
|
+
|
|
862
|
+
- **Parse** — accept stable JSON objects only; schema outputs must remain JSON.
|
|
863
|
+
- **Canonicalize** — optional; a result that leaves the payload schema throws, so a
|
|
864
|
+
broken normalizer can never store invalid content.
|
|
865
|
+
- **Index** — the returned `filter` must be declared in `filters`, every `tag` in
|
|
866
|
+
`tags` (duplicates collapse), and the `title` is trimmed and bounded
|
|
867
|
+
(`titleChars`, well-formed text). A derivation outside the declared vocabulary
|
|
868
|
+
would store a row no list query can reach — it throws instead.
|
|
869
|
+
- **Size** — the canonical JSON must fit `payloadBytes`.
|
|
870
|
+
- **Identity** — the content hash is SHA-256 over `{contentVersion, payload}`:
|
|
871
|
+
identical content hashes identically, a real edit always re-identifies, and the
|
|
872
|
+
core owns the envelope so collections cannot drift it.
|
|
873
|
+
|
|
874
|
+
Declare vocabularies with readonly arrays (`['fire', 'ice']`) for automatic
|
|
875
|
+
literal-union inference. Const generics retain the version literal and vocabulary
|
|
876
|
+
unions; `NoInfer` prevents the index callback from widening them. Omitted arrays
|
|
877
|
+
mean empty vocabularies: return `null` for
|
|
878
|
+
the filter and no tags. Object keys are recursively sorted by the core; schema
|
|
879
|
+
transformations must stabilize and `canonicalize` must be pure and idempotent.
|
|
880
|
+
Non-JSON input returns `null`. Unexpected callback, schema or hashing failures,
|
|
881
|
+
unstable transformations, non-idempotent canonicalization and index mutation throw
|
|
882
|
+
`ArchiveDerivationError`; its `stage` identifies the failing phase.
|
|
883
|
+
Lossy or non-JSON schema output and invalid index-result shapes also throw.
|
|
884
|
+
|
|
885
|
+
`contentVersion` participates in content identity. Request handling validates
|
|
886
|
+
only the current collection definition; it does not interpret historical schemas.
|
|
887
|
+
Archive is unreleased and provides no content-upgrade APIs.
|
|
888
|
+
|
|
889
|
+
Filters, tags and searchable titles are persisted data derived at publish/update
|
|
890
|
+
time. Editing `index` or its vocabularies does not recompute existing projections.
|
|
891
|
+
Keep the active definition and dataset consistent. For an unreleased development
|
|
892
|
+
deployment, deliberately reset and reseed a fresh database when you change payload
|
|
893
|
+
or projection semantics; the package does not supply a migration framework.
|
|
894
|
+
Resetting destroys existing data. Perform it only as an explicit, deliberate
|
|
895
|
+
development operation, not automatically during startup or deployment.
|
|
896
|
+
|
|
897
|
+
**Payloads carry decisions, not content.** The payload schema should accept
|
|
898
|
+
user-authored choices expressed as IDs plus user-written text — never the content's
|
|
899
|
+
own copyrighted expression (card text, artwork, rules), never more than the game's
|
|
900
|
+
own identifiers. For games with paid or DLC content this is the whole answer:
|
|
901
|
+
ownership resolves on each viewer's device against their own library, the service
|
|
902
|
+
never learns what anyone owns, and the strict schema is the enforcement seam —
|
|
903
|
+
use a strict schema that rejects unknown fields, so a collection that only models IDs cannot
|
|
904
|
+
accidentally start shipping paid content. For example, published game builds can
|
|
905
|
+
reference cards, equipment and potions by ID plus a user-written name. The client
|
|
906
|
+
renders pieces the viewer does not own as unavailable. Keep the browser-safe
|
|
907
|
+
publication contract in a shared domain module consumed by both the frontend and
|
|
908
|
+
its backend, without importing frontend application code into the Worker.
|
|
909
|
+
|
|
910
|
+
## The Worker and its environment
|
|
911
|
+
|
|
912
|
+
`createArchiveWorker(collections)` returns the full handler: anonymous public reads,
|
|
913
|
+
cookie-authenticated mutations behind exact-origin and request-marker guards, local
|
|
914
|
+
RS256/JWKS verification followed by an uncached issuer session-version check,
|
|
915
|
+
per-IP read limits and per-subject write limits keyed by peppered HMACs, the
|
|
916
|
+
30-second anonymous cache on public entry lists only, operator moderation, and a
|
|
917
|
+
scheduled expiry sweep for retired publish retry keys and revocation tombstones.
|
|
918
|
+
Health sits outside the rate-limit and session pipelines: probes never burn the
|
|
919
|
+
anonymous read budget or call the issuer.
|
|
920
|
+
|
|
921
|
+
The Worker reads its environment fail-closed — every binding must be present and
|
|
922
|
+
well-formed, or the route answers 503 without naming what is missing:
|
|
923
|
+
|
|
924
|
+
| Variable | Meaning |
|
|
925
|
+
| ------------------------ | ---------------------------------------------------------------- |
|
|
926
|
+
| `APP_ENV` | `local` or `production` (transport rules and the pepper policy) |
|
|
927
|
+
| `ALLOWED_ORIGINS` | Exact canonical origins; never wildcards |
|
|
928
|
+
| `JWT_ISSUER` / `JWT_AUDIENCE` / `JWT_JWKS_URL` | Your identity provider |
|
|
929
|
+
| `AUTH_ISSUER_SERVICE` | Required issuer service binding for live session-version checks |
|
|
930
|
+
| `LIKES_ENABLED` / `PUBLISHING_ENABLED` | Feature flags |
|
|
931
|
+
| `RATE_LIMIT_KEY_SECRET` | HMAC pepper. Required ≥ 32 chars in production; local may fall back |
|
|
932
|
+
| `DB` / `READ_LIMIT` / `WRITE_LIMIT` | D1 + rate-limit bindings |
|
|
933
|
+
|
|
934
|
+
Both limiter bindings must run 60-second windows (`simple` limiters:
|
|
935
|
+
`period: 60`): the platform binding does not expose its period at runtime, so the
|
|
936
|
+
Worker's 429 `Retry-After` header is fixed at 60 seconds — a longer window would
|
|
937
|
+
make the header lie.
|
|
938
|
+
|
|
939
|
+
Generated Env types (wrangler's `worker-configuration.d.ts`) satisfy the package's
|
|
940
|
+
structural `ArchiveWorkerEnv` — no `@cloudflare/workers-types` dependency, no casts.
|
|
941
|
+
|
|
942
|
+
## The auth issuer
|
|
943
|
+
|
|
944
|
+
`createAuthWorker()` from `@vielzeug/archive/auth` is the reference passwordless
|
|
945
|
+
identity issuer a deployment runs beside the catalog Worker: one POST with an email
|
|
946
|
+
sends a single-use magic link, and explicitly confirming it sets the `archive_session`
|
|
947
|
+
cookie. The catalog verifies the JWT locally, then calls the issuer through
|
|
948
|
+
`AUTH_ISSUER_SERVICE` to check the account's current session version. Requests create
|
|
949
|
+
pending account rows; explicit link redemption atomically stamps the account's
|
|
950
|
+
sign-in time and claims the token. The issuer's D1 schema ships at
|
|
951
|
+
`node_modules/@vielzeug/archive/migrations/auth/`; point the issuer's
|
|
952
|
+
`migrations_dir` there. The catalog's `JWT_ISSUER` and `JWT_JWKS_URL` must identify
|
|
953
|
+
the issuer, and its audience must match the issuer's `AUDIENCE`.
|
|
954
|
+
|
|
955
|
+
| Variable | Meaning |
|
|
956
|
+
| --- | --- |
|
|
957
|
+
| `APP_NAME` | The app's display name: the magic-link email's subject and copy name it |
|
|
958
|
+
| `ALLOWED_ORIGINS` | Exact origins allowed to trigger unsafe routes (the app origin(s)) |
|
|
959
|
+
| `APP_ENV` | `local` or `production` — production requires HTTPS and sets Secure cookies |
|
|
960
|
+
| `AUDIENCE` / `AUTH_ISSUER` | The claims every minted session carries; the catalog verifies the same pair |
|
|
961
|
+
| `AUTH_DB` / `AUTH_EMAIL` | The issuer's D1 and send-email bindings |
|
|
962
|
+
| `AUTH_ARCHIVE` | Required service binding to the catalog Worker; deletion calls its profile-erasure route |
|
|
963
|
+
| `AUTH_JWT_PRIVATE_JWK` | The RS256 private key as a JWK JSON string: a wrangler secret in production |
|
|
964
|
+
| `AUTH_JWT_PREVIOUS_PUBLIC_JWKS` | Optional retired public RS256 JWKS; publish during rotation until old sessions expire |
|
|
965
|
+
| `OPERATOR_EMAILS` | Comma-separated emails whose newly minted sessions carry the operator role |
|
|
966
|
+
| `PUBLIC_ORIGIN` | App origin for links, confirmation POST origin checks and client navigation after sign-in |
|
|
967
|
+
| `SENDER_ADDRESS` | The address magic links come from: a domain onboarded to Cloudflare Email Service |
|
|
968
|
+
|
|
969
|
+
Under `wrangler dev` the send-email binding is simulated — the link prints to the
|
|
970
|
+
issuer's console, so that console is the inbox. Demo-only Alice/Bob routes are
|
|
971
|
+
deployment wrappers, not package APIs.
|
|
972
|
+
|
|
973
|
+
The issuer first admits sign-in requests through its singleton durable
|
|
974
|
+
`auth_sign_in_budget` table: 20 requests per 60 seconds before creating accounts
|
|
975
|
+
or delivering email. No rate-limiter binding is required. It then
|
|
976
|
+
permits three sign-in emails per email in an hourly durable window.
|
|
977
|
+
Later database or delivery failures do not refund global admission.
|
|
978
|
+
Using or expiring a link never refunds sends; failed delivery also spends the
|
|
979
|
+
allowance. Links expire after 15 minutes. Operator sessions expire after 900
|
|
980
|
+
seconds, ordinary sessions after at most 30 days. Retain retired public keys during
|
|
981
|
+
rotation; the active private key signs every new session. Sign-in input trims and
|
|
982
|
+
lowercases email before validation. `SENDER_ADDRESS` must already be canonical;
|
|
983
|
+
`OPERATOR_EMAILS` entries are trimmed and lowercased before validation.
|
|
984
|
+
|
|
985
|
+
The scheduled sweep deletes expired links and closed per-user send windows, then
|
|
986
|
+
pending accounts only when neither a link nor send-budget row still references
|
|
987
|
+
them. Failed delivery deletes the unusable token but retains the spent allowance;
|
|
988
|
+
it does not immediately remove the pending account. Verified accounts stay until
|
|
989
|
+
explicit erasure. The singleton admission row remains and resets its window on a
|
|
990
|
+
later admitted request.
|
|
991
|
+
|
|
992
|
+
Opening `GET /auth/verify?token=…` renders a no-store confirmation page and does
|
|
993
|
+
not consume the link or change the session, so email scanners cannot sign in by
|
|
994
|
+
fetching it. A deliberate click sends `POST /auth/verify` with JSON `{ token }`,
|
|
995
|
+
the request marker and an exact allowed origin or `PUBLIC_ORIGIN`.
|
|
996
|
+
Success is 204 with Set-Cookie; the page then navigates to `/signed-in`. The
|
|
997
|
+
redemption update and account sign-in stamp are trigger-backed and atomic.
|
|
998
|
+
The page removes the token from the address bar, loads no external assets, and
|
|
999
|
+
sets a restrictive CSP and `Referrer-Policy: no-referrer`.
|
|
1000
|
+
|
|
1001
|
+
`GET /auth/account` exports account metadata only. For full erasure, call
|
|
1002
|
+
`DELETE /auth/account` with `ACCOUNT_HEADER` (`X-Archive-Account`) set to the
|
|
1003
|
+
issuer account UUID captured from `GET /auth/account` before confirmation.
|
|
1004
|
+
The issuer rejects missing or invalid UUIDs with 400 and a different signed-in
|
|
1005
|
+
account with 409 `account-changed`, before any erasure. This guard applies even
|
|
1006
|
+
before publisher registration and must stay pinned across retries.
|
|
1007
|
+
The issuer forwards the caller's session and publisher
|
|
1008
|
+
precondition through `AUTH_ARCHIVE` to `DELETE /me/account`, requires exactly 204,
|
|
1009
|
+
then deletes its
|
|
1010
|
+
own user and clears the cookie. Failure preserves the session for retry. Direct
|
|
1011
|
+
`DELETE /me` removes only the Archive profile and leaves the cookie intact.
|
|
1012
|
+
|
|
1013
|
+
Several game frontends can share one issuer and catalog. Keep the cookie
|
|
1014
|
+
host-only on the central API host, use `credentials: 'include'` from same-site
|
|
1015
|
+
HTTPS game subdomains, and allow each exact frontend origin in both Workers.
|
|
1016
|
+
Do not share cookies through a parent-domain `Domain` attribute. The
|
|
1017
|
+
[multi-collection recipe](./examples/multi-collection-deployment.md) describes
|
|
1018
|
+
the topology, session revalidation and platform-wide account boundary.
|
|
1019
|
+
|
|
1020
|
+
`DELETE /me/account` atomically revokes the issuer/subject and cascades profile
|
|
1021
|
+
deletion. Its tombstone lasts 30 days plus ten seconds; old sessions cannot read
|
|
1022
|
+
private data or register again, including a racing registration. The dedicated
|
|
1023
|
+
account-erasure route alone may bypass the issuer lookup, and only to retry with
|
|
1024
|
+
the same principal's original signed session while its existing tombstone is
|
|
1025
|
+
valid; signature and claims are still verified, and initial erasure validates the
|
|
1026
|
+
issuer. The issuer's `DELETE /auth/account` checks the current version before
|
|
1027
|
+
starting erasure; after completed erasure a retry there returns 401. A fresh
|
|
1028
|
+
issuer account gets a new UUID subject. External issuers must use a new subject to
|
|
1029
|
+
re-enroll during the revocation window. Profile-only deletion does not revoke the
|
|
1030
|
+
subject and permits re-registration with existing credentials.
|
|
1031
|
+
|
|
1032
|
+
Each JWT also carries the issuer account's required safe-integer `sessionVersion`.
|
|
1033
|
+
The issuer compares it with `auth_users.session_version` on every ordinary
|
|
1034
|
+
authenticated route. A JWT with an old version is unauthenticated even before its
|
|
1035
|
+
expiry; the catalog asks the issuer on every private request and does not cache a
|
|
1036
|
+
successful verdict. A valid local JWT with an unavailable, malformed, 5xx or
|
|
1037
|
+
timed-out (fixed 5000 ms, including body decoding) issuer response becomes
|
|
1038
|
+
`503 auth-unavailable`, not anonymous identity.
|
|
1039
|
+
|
|
1040
|
+
## The database
|
|
1041
|
+
|
|
1042
|
+
The package ships the canonical catalog migration:
|
|
1043
|
+
`node_modules/@vielzeug/archive/migrations/0001_community_archive.sql` — the whole schema,
|
|
1044
|
+
moderation included, as one designed file. The runtime SQL in the package is
|
|
1045
|
+
written against exactly this schema, and the package's own integration suite runs
|
|
1046
|
+
against the same file. Point wrangler at the directory:
|
|
1047
|
+
|
|
1048
|
+
```jsonc
|
|
1049
|
+
// wrangler.jsonc — the deployment owns its D1 database, not its DDL.
|
|
1050
|
+
{
|
|
1051
|
+
"d1_databases": [
|
|
1052
|
+
{
|
|
1053
|
+
"binding": "DB",
|
|
1054
|
+
"database_name": "my-app",
|
|
1055
|
+
"migrations_dir": "./node_modules/@vielzeug/archive/migrations"
|
|
1056
|
+
}
|
|
1057
|
+
]
|
|
1058
|
+
}
|
|
1059
|
+
```
|
|
1060
|
+
|
|
1061
|
+
The issuer points to
|
|
1062
|
+
`node_modules/@vielzeug/archive/migrations/auth/0001_auth.sql`. Both files are
|
|
1063
|
+
fresh-database initialization definitions, not upgrades. The issuer DDL initializes
|
|
1064
|
+
`auth_users.session_version` to `0` and stamps `auth_schema_meta.applied` as
|
|
1065
|
+
`AUTH_SCHEMA_VERSION` (`1`). Neither file automatically deletes or resets data.
|
|
1066
|
+
While Archive is unreleased, its
|
|
1067
|
+
canonical initial schemas are edited directly. Reset and reseed an unreleased
|
|
1068
|
+
development database deliberately when its schema or collection semantics no
|
|
1069
|
+
longer match; reapplying the initial file does not update an existing dataset.
|
|
1070
|
+
The initialization file also stamps the storage schema
|
|
1071
|
+
(`archive_schema_meta`) at `ARCHIVE_SCHEMA_VERSION`, and health reads it back: a
|
|
1072
|
+
database with a mismatched stamp answers `status: 'degraded'` with the
|
|
1073
|
+
observed `dbSchemaVersion` and HTTP 503 (`reason: 'schema-mismatch'`).
|
|
1074
|
+
An unavailable database produces HTTP 503 with `dbSchemaVersion: null` and
|
|
1075
|
+
`reason: 'database-unavailable'`. The debut storage stamp is `1`. A unit
|
|
1076
|
+
test pins the shipped DDL's `CHECK` bounds to `ARCHIVE_LIMITS`, so the two can never
|
|
1077
|
+
drift silently. The stamp does not detect changes in your collection's payload
|
|
1078
|
+
schema, vocabulary or indexing function; you own that dataset consistency.
|
|
1079
|
+
|
|
1080
|
+
## Routes and wire names
|
|
1081
|
+
|
|
1082
|
+
```
|
|
1083
|
+
GET /api/v1/health
|
|
1084
|
+
POST /api/v1/sign-out
|
|
1085
|
+
GET /api/v1/auth/health
|
|
1086
|
+
GET /api/v1/auth/session (internal issuer check)
|
|
1087
|
+
POST /api/v1/auth/sign-out-all (revoke every session)
|
|
1088
|
+
GET /api/v1/collections/:collection (self-description)
|
|
1089
|
+
GET /api/v1/collections/:collection/entries (author, filter, tag, search, sort, cursor, limit)
|
|
1090
|
+
POST /api/v1/collections/:collection/entries
|
|
1091
|
+
GET /api/v1/collections/:collection/entries/:id
|
|
1092
|
+
PUT /api/v1/collections/:collection/entries/:id (expectedRevision)
|
|
1093
|
+
DELETE /api/v1/collections/:collection/entries/:id
|
|
1094
|
+
PUT /api/v1/collections/:collection/entries/:id/like
|
|
1095
|
+
DELETE /api/v1/collections/:collection/entries/:id/like
|
|
1096
|
+
POST /api/v1/collections/:collection/entries/:id/report (reason)
|
|
1097
|
+
PUT /api/v1/collections/:collection/entries/:id/hidden (operator)
|
|
1098
|
+
DELETE /api/v1/collections/:collection/entries/:id/hidden (operator)
|
|
1099
|
+
GET /api/v1/collections/:collection/reports (operator: status, cursor, limit)
|
|
1100
|
+
PUT /api/v1/collections/:collection/reports/:id/resolved (operator: report ID)
|
|
1101
|
+
DELETE /api/v1/publishers/:id (operator: erase any publisher)
|
|
1102
|
+
GET /api/v1/moderation-log (operator: cursor, limit)
|
|
1103
|
+
GET /api/v1/me POST /me PUT /me DELETE /me
|
|
1104
|
+
GET /api/v1/me/publications?collection=:collection GET /api/v1/me/likes[?ids=…]
|
|
1105
|
+
GET /api/v1/me/reports (cursor, limit)
|
|
1106
|
+
GET /api/v1/auth/account
|
|
1107
|
+
GET /api/v1/auth/jwks.json
|
|
1108
|
+
POST /api/v1/auth/sign-in (email)
|
|
1109
|
+
DELETE /api/v1/auth/account (coordinated full erasure)
|
|
1110
|
+
DELETE /api/v1/me/account (issuer erasure seam; revokes subject)
|
|
1111
|
+
GET /api/v1/auth/verify?token=… (confirmation only)
|
|
1112
|
+
POST /api/v1/auth/verify (guarded {token} redemption)
|
|
1113
|
+
```
|
|
1114
|
+
|
|
1115
|
+
Publishing is bounded by `maxPublications` live entries per `(collection, owner)`.
|
|
1116
|
+
The quota check runs inside the guarded insert.
|
|
1117
|
+
|
|
1118
|
+
`/me/likes` without `ids`, `/me/reports`, operator reports and `/moderation-log`
|
|
1119
|
+
use forward keyset pages: follow `cursor` until `null`, preserving query context.
|
|
1120
|
+
`limit` defaults to `pageSize` and is at most `maxPageSize`; there is no total
|
|
1121
|
+
export bound. `/me/likes?ids=…` remains a subset lookup returning `{ ids }`, not a
|
|
1122
|
+
page, and cannot combine `ids` with `cursor` or `limit`.
|
|
1123
|
+
|
|
1124
|
+
Shared wire names live in the package — `archive_session` cookie,
|
|
1125
|
+
`x-archive-publisher` and `x-archive-request` headers, `ARCHIVE_ERROR_CODES`, and
|
|
1126
|
+
`ARCHIVE_LIMITS` — so a client and the Worker cannot drift. Parse failures with the
|
|
1127
|
+
collection's composed schemas; parse errors with `archiveErrorResponseSchema`, the
|
|
1128
|
+
sign-out body with `archiveOkSchema`, a collection's self-description with
|
|
1129
|
+
`archiveCollectionMetaSchema` and the operator queue with `archiveReportsSchema`.
|
|
1130
|
+
Every entry's `schemaVersion` is the archive contract's version, not the
|
|
1131
|
+
collection's; the collection's own format version lives in its hash envelope and in
|
|
1132
|
+
each entry's `contentVersion`.
|
|
1133
|
+
|
|
1134
|
+
Only anonymous entry lists carry a 30-second edge-cache contract
|
|
1135
|
+
(`publicCacheSeconds`). Detail is always `no-store`. Any Cookie or Authorization
|
|
1136
|
+
header disables caching, regardless of validity; metadata, private and error
|
|
1137
|
+
responses also use `no-store`.
|
|
1138
|
+
|
|
1139
|
+
Implement UI ownership checks in your application by comparing the current
|
|
1140
|
+
publisher ID to the entry's `author.id`; there is no package action-policy helper.
|
|
1141
|
+
Server mutations remain authoritative.
|
|
1142
|
+
|
|
1143
|
+
`POST /api/v1/sign-out` is deliberately local: it clears only this browser's
|
|
1144
|
+
cookie and does not contact the issuer or revoke copied sessions. To revoke every
|
|
1145
|
+
session, post to `/api/v1/auth/sign-out-all` with the mutation marker, an exact
|
|
1146
|
+
allowed `Origin`, and the issuer account UUID captured from
|
|
1147
|
+
`GET /api/v1/auth/account` in `X-Archive-Account`. The issuer returns 409
|
|
1148
|
+
`account-changed` if the active subject differs. On success it atomically increments
|
|
1149
|
+
`session_version`, deletes outstanding links, preserves account and catalog data,
|
|
1150
|
+
and returns `{ ok: true }` with an expired cookie. Requests authorized before
|
|
1151
|
+
revocation may finish; there is no cross-database cancellation guarantee.
|
|
1152
|
+
|
|
1153
|
+
`GET /api/v1/auth/health` is public and read-only. It validates issuer
|
|
1154
|
+
configuration, key signing/verification, binding shapes, the `auth_schema_meta`
|
|
1155
|
+
stamp and expected tables, columns and triggers, returns `AuthHealth` through
|
|
1156
|
+
`archiveAuthHealthSchema`, and answers 503 `degraded` for configuration,
|
|
1157
|
+
database or schema failures. It never writes, sends email or probes the catalog.
|
|
1158
|
+
|
|
1159
|
+
## Moderation
|
|
1160
|
+
|
|
1161
|
+
Operator authority is the session token's optional `roles` claim carrying
|
|
1162
|
+
`ARCHIVE_OPERATOR_ROLE` (`'archive-operator'`) — minted by your issuer, verified with
|
|
1163
|
+
the same signature, audience and issuer checks as any session, and never a separate
|
|
1164
|
+
credential. Moderation routes additionally require a registered publisher row: one
|
|
1165
|
+
accountable identity per action.
|
|
1166
|
+
|
|
1167
|
+
- **Report** — any registered publisher reports a visible entry with a bounded
|
|
1168
|
+
free-text reason (`reportReasonChars`). Idempotent per (entry, reporter): the same
|
|
1169
|
+
report twice is the same 204. Missing or hidden entries answer 404 — there is
|
|
1170
|
+
nothing left to report.
|
|
1171
|
+
- **Hide** — an operator removes an entry from every public surface (list, detail,
|
|
1172
|
+
likes) with a soft-hide: the row, its likes and its retry key stay intact. The
|
|
1173
|
+
owner still sees the entry in `/me/publications` with `hidden: true`, edits and
|
|
1174
|
+
key replay are frozen (403), removal stays allowed, and unhiding restores
|
|
1175
|
+
everything. Already hidden or already visible answer the same 204.
|
|
1176
|
+
- **Queue** — the operator pages newest reports with entry title and reporter
|
|
1177
|
+
identity; `status` is `unresolved` (default) or `resolved`. Each report has its
|
|
1178
|
+
own `id` and nullable `resolvedAt`. Resolve it with
|
|
1179
|
+
`PUT /collections/:collection/reports/:id/resolved`; repeating is a 204 no-op.
|
|
1180
|
+
- **Log** — every effective moderation action (hide, unhide, removal, publisher
|
|
1181
|
+
erasure) appends one accountability row in the same transaction that applies it,
|
|
1182
|
+
and `GET /api/v1/moderation-log` pages the newest actions to
|
|
1183
|
+
operators. Rows carry only ids, the action kind and the time — no names (they
|
|
1184
|
+
change), no content — and no foreign keys: the audit must outlive the erasures it
|
|
1185
|
+
records. Idempotent repeats (hiding an already-hidden entry, erasing an
|
|
1186
|
+
already-erased publisher) answer the same 204 with no new row, including
|
|
1187
|
+
concurrent repeats: audit insertion tests the effective state inside the batch.
|
|
1188
|
+
|
|
1189
|
+
Like and unlike both require a visible entry. Their SQL guards visibility during
|
|
1190
|
+
the mutation, and the response checks it again; hiding or deleting an entry
|
|
1191
|
+
cannot turn a racing unlike into a successful response for unavailable content.
|
|
1192
|
+
|
|
1193
|
+
## Observability
|
|
1194
|
+
|
|
1195
|
+
The core never logs. `worker.tap(handler, { signal? })` emits one `ArchiveEvent` per
|
|
1196
|
+
request — `{ type: 'request', code, ms, requestId, route, status, diagnostic? }` —
|
|
1197
|
+
and successful sweep — `{ type: 'scheduled', status: 'ok', removed }`. Failed
|
|
1198
|
+
sweeps emit `{ type: 'scheduled', status: 'failed', diagnostic }` and rethrow so
|
|
1199
|
+
the runtime sees failure. Cache failures emit `{ type: 'cache-error', diagnostic }`.
|
|
1200
|
+
The Worker swallows observer errors so
|
|
1201
|
+
observability cannot affect the Worker. With no handlers registered there is zero
|
|
1202
|
+
work. Route is a finite class like `/collections/:collection/entries`, never a
|
|
1203
|
+
raw path; no event carries a URL, cookie, subject, alias or token. Diagnostics are
|
|
1204
|
+
typed sanitized categories, not raw exceptions. A pre-aborted tap signal is inert.
|
|
1205
|
+
The sweep's `removed` counts expired retry keys and revocation tombstones together.
|
|
1206
|
+
|
|
1207
|
+
The issuer also exposes `tap()` with `AuthEvent` from `@vielzeug/archive/auth`.
|
|
1208
|
+
It never logs directly. Events contain finite route labels, codes, counts,
|
|
1209
|
+
duration and sanitized `AuthDiagnostic` categories, never emails, tokens or raw
|
|
1210
|
+
exceptions. Scheduled failures emit then rethrow; pre-aborted taps are inert.
|
|
1211
|
+
Issuer sweep counts include expired tokens, closed per-user send windows and
|
|
1212
|
+
removed pending accounts; the singleton admission row is not removed.
|
|
1213
|
+
|
|
1214
|
+
```ts
|
|
1215
|
+
import { createLogger } from '@vielzeug/rune';
|
|
1216
|
+
import { createArchiveWorker } from '@vielzeug/archive/worker';
|
|
1217
|
+
import { recipesCollection } from './recipes-collection';
|
|
1218
|
+
|
|
1219
|
+
const log = createLogger({ namespace: 'recipes' });
|
|
1220
|
+
const worker = createArchiveWorker([recipesCollection]);
|
|
1221
|
+
worker.tap((event) => log.debug(event, `archive:${event.type}`));
|
|
1222
|
+
export default worker;
|
|
1223
|
+
```
|
|
1224
|
+
|
|
1225
|
+
## Testing
|
|
1226
|
+
|
|
1227
|
+
The package proves itself against real workerd + local D1:
|
|
1228
|
+
|
|
1229
|
+
```sh
|
|
1230
|
+
pnpm vitest run packages/archive/src/__tests__/ # fast unit suite
|
|
1231
|
+
pnpm --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage
|
|
1232
|
+
pnpm --filter @vielzeug/archive test:types # strict types over src and the integration suite
|
|
1233
|
+
```
|
|
1234
|
+
|
|
1235
|
+
Prove your own collection the way the reference deployment does: a slim deployment
|
|
1236
|
+
suite that publishes over your real vocabulary and asserts the derivation, plus the
|
|
1237
|
+
package's generic suite for the core behavior. A collection with an `index` that can
|
|
1238
|
+
drift out of vocabulary should unit-test `derive` directly: ordinary invalid input
|
|
1239
|
+
returns `null`, while implementation faults throw `ArchiveDerivationError`.
|
|
1240
|
+
Direct DDL tests exercise the shipped schema rather than a duplicate schema.
|
|
1241
|
+
|
|
1242
|
+
## Framework Integration
|
|
1243
|
+
|
|
1244
|
+
The root entry is plain TypeScript with no framework coupling; Vue, React and Svelte
|
|
1245
|
+
apps all consume the composed schemas the same way. A Vue 3 composable that pages a
|
|
1246
|
+
collection:
|
|
1247
|
+
|
|
1248
|
+
```ts
|
|
1249
|
+
// useRecipes.ts — one collection's typed client in any component tree.
|
|
1250
|
+
import { recipesCollection } from './recipes-collection';
|
|
1251
|
+
import { ref, shallowRef } from 'vue';
|
|
1252
|
+
|
|
1253
|
+
export function useRecipes() {
|
|
1254
|
+
const entries = shallowRef[]>([]);
|
|
1255
|
+
const cursor = ref(null);
|
|
1256
|
+
async function load(sort: 'liked' | 'recent') {
|
|
1257
|
+
const params = new URLSearchParams({ sort });
|
|
1258
|
+
if (cursor.value !== null) params.set('cursor', cursor.value);
|
|
1259
|
+
const response = await fetch(`/api/v1/collections/recipes/entries?${params}`);
|
|
1260
|
+
if (!response.ok) throw new Error('The archive is unavailable.');
|
|
1261
|
+
const page = recipesCollection.contract.page.parse(await response.json());
|
|
1262
|
+
entries.value = [...entries.value, ...page.entries];
|
|
1263
|
+
cursor.value = page.cursor;
|
|
1264
|
+
}
|
|
1265
|
+
return { cursor, entries, load };
|
|
1266
|
+
}
|
|
1267
|
+
```
|
|
1268
|
+
|
|
1269
|
+
## Working with Other Vielzeug Libraries
|
|
1270
|
+
|
|
1271
|
+
- [Spell](/spell/) — the payload schema a collection declares; the core composes the
|
|
1272
|
+
envelope schemas from it, so the wire and the types cannot drift.
|
|
1273
|
+
- [Courier](/courier/) — the HTTP client shape an app's frontend mirrors to consume
|
|
1274
|
+
these routes: strict response schemas over one typed port.
|
|
1275
|
+
- [Rune](/rune/) — the structured logger a deployment points `tap()` events at.
|
|
1276
|
+
|
|
1277
|
+
## Best Practices
|
|
1278
|
+
|
|
1279
|
+
- Compose client schemas from `collection.contract`; never hand-write the envelope.
|
|
1280
|
+
- Declare exactly the vocabulary your `index` derives, with union types where you
|
|
1281
|
+
have them; a value outside it rejects loudly.
|
|
1282
|
+
- Keep `canonicalize` pure and schema-true: reordered lists in, canonical form out.
|
|
1283
|
+
- Initialize fresh databases with the shipped DDL and deliberately reset/reseed
|
|
1284
|
+
unreleased development data when collection or storage semantics change.
|
|
1285
|
+
- Treat `ARCHIVE_ERROR_CODES` and `archiveErrorResponseSchema` as one tested contract.
|
|
1286
|
+
- Pin the expected-publisher header from the identity you captured at sign-in, never from storage alone.
|
|
1287
|
+
- Grant the operator role claim only through your issuer, and only to accounts that
|
|
1288
|
+
are also registered publishers.
|
|
1289
|
+
- Wire a sanitized `tap()` sink and register the rate-limit pepper as a production secret.
|
|
1290
|
+
|
|
1291
|
+
### Examples
|
|
1292
|
+
|
|
1293
|
+
- [Stand Up a Content Archive](./examples/stand-up-a-content-archive.md)
|
|
1294
|
+
- [Content Identity and Versions](./examples/content-identity-and-versions.md)
|
|
1295
|
+
- [Multi-Collection Deployment](./examples/multi-collection-deployment.md)
|
|
1296
|
+
- [Moderate Content](./examples/moderate-content.md)
|
|
1297
|
+
- [Client Error Mapping](./examples/client-error-mapping.md)
|
|
1298
|
+
- [GDPR Erasure and Export](./examples/gdpr-erasure-and-export.md)
|
|
4
1299
|
|
|
5
1300
|
---
|
|
6
1301
|
|
|
@@ -119,6 +1414,8 @@ console.log(byRole, health, profile);
|
|
|
119
1414
|
| `allocate` | Lossless proportional distribution | Sync | Available from `/math` |
|
|
120
1415
|
| `isEqual` | Structural equality | Sync | Root export |
|
|
121
1416
|
| `hash` | Deterministic serialization for cache keys | Sync | Available from `/object` |
|
|
1417
|
+
| `compressBytes` / `decompressBytes` | Native byte compression with bounded decompression | Async | Requires native compression streams; decoding requires an output limit |
|
|
1418
|
+
| `pack` / `unpack` | Versioned, compressed, URL-safe payload envelope | Async | Both sides bound the payload with `maxBytes`; compression falls back to raw |
|
|
122
1419
|
|
|
123
1420
|
## Package Entry Points
|
|
124
1421
|
|
|
@@ -128,6 +1425,7 @@ console.log(byRole, health, profile);
|
|
|
128
1425
|
| `@vielzeug/arsenal/array` | Immutable transforms, set operations, sorting, fuzzy search |
|
|
129
1426
|
| `@vielzeug/arsenal/async` | Retry, cancellation, task pool, timing |
|
|
130
1427
|
| `@vielzeug/arsenal/cache` | In-memory cache and memoization |
|
|
1428
|
+
| `@vielzeug/arsenal/encoding` | Base64url and native byte compression |
|
|
131
1429
|
| `@vielzeug/arsenal/function` | Assertions, composition, timing, teardown |
|
|
132
1430
|
| `@vielzeug/arsenal/guards` | Type guards, predicate combinators, equality guards |
|
|
133
1431
|
| `@vielzeug/arsenal/math` | Ranges, aggregation, statistics, interpolation, exact allocation |
|
|
@@ -245,6 +1543,101 @@ base64UrlToBytes(code); // throws on characters outside the alphabet
|
|
|
245
1543
|
utf8Bytes('Hunter äöü'); // 11: byte length of a UTF-8 string
|
|
246
1544
|
```
|
|
247
1545
|
|
|
1546
|
+
### compressBytes
|
|
1547
|
+
|
|
1548
|
+
```ts
|
|
1549
|
+
compressBytes(bytes: Uint8Array, options?: CompressionOptions): Promise
|
|
1550
|
+
```
|
|
1551
|
+
|
|
1552
|
+
Compresses bytes using the native `CompressionStream` API without modifying the input.
|
|
1553
|
+
|
|
1554
|
+
| Option | Type | Default | Meaning |
|
|
1555
|
+
| --- | --- | --- | --- |
|
|
1556
|
+
| `format` | `CompressionFormat` | `'deflate-raw'` | Compression format; the receiver must use the same format |
|
|
1557
|
+
|
|
1558
|
+
**Returns:** Compressed bytes. Rejects with `ArsenalSerializationError` when the format or capability is unavailable, or stream processing fails. Does not fall back to another format.
|
|
1559
|
+
|
|
1560
|
+
**Example:** Encode compressed bytes for a URL.
|
|
1561
|
+
|
|
1562
|
+
```ts
|
|
1563
|
+
import { bytesToBase64Url, compressBytes } from '@vielzeug/arsenal';
|
|
1564
|
+
|
|
1565
|
+
const bytes = new TextEncoder().encode(JSON.stringify({ name: 'Hunters' }));
|
|
1566
|
+
const code = bytesToBase64Url(await compressBytes(bytes));
|
|
1567
|
+
```
|
|
1568
|
+
|
|
1569
|
+
---
|
|
1570
|
+
|
|
1571
|
+
### decompressBytes
|
|
1572
|
+
|
|
1573
|
+
```ts
|
|
1574
|
+
decompressBytes(bytes: Uint8Array, options: DecompressionOptions): Promise
|
|
1575
|
+
```
|
|
1576
|
+
|
|
1577
|
+
Decompresses bytes using the native `DecompressionStream` API, enforcing the output limit while reading chunks.
|
|
1578
|
+
|
|
1579
|
+
| Option | Type | Default | Meaning |
|
|
1580
|
+
| --- | --- | --- | --- |
|
|
1581
|
+
| `format` | `CompressionFormat` | `'deflate-raw'` | Format used by the sender |
|
|
1582
|
+
| `maxOutputBytes` | `number` | Required | Non-negative safe integer; maximum decoded byte length |
|
|
1583
|
+
|
|
1584
|
+
**Returns:** Decompressed bytes. Rejects with `ArsenalSerializationError` for invalid limits, corrupt or truncated data, unavailable formats/capabilities, or output exceeding the limit. A failed stream is canceled and its reader lock released. Bound encoded input separately before calling this function.
|
|
1585
|
+
|
|
1586
|
+
**Example:** Decode text within an application-defined byte limit.
|
|
1587
|
+
|
|
1588
|
+
```ts
|
|
1589
|
+
import { compressBytes, decompressBytes } from '@vielzeug/arsenal';
|
|
1590
|
+
|
|
1591
|
+
const compressed = await compressBytes(new TextEncoder().encode('Hunters'));
|
|
1592
|
+
const bytes = await decompressBytes(compressed, { maxOutputBytes: 8192 });
|
|
1593
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
1594
|
+
```
|
|
1595
|
+
|
|
1596
|
+
---
|
|
1597
|
+
|
|
1598
|
+
### pack
|
|
1599
|
+
|
|
1600
|
+
```ts
|
|
1601
|
+
pack(payload: unknown, options: ShareCodeOptions): Promise
|
|
1602
|
+
```
|
|
1603
|
+
|
|
1604
|
+
Serializes `payload` as JSON and encodes it into a compact share code: `prefix` + mode marker + base64url bytes, compressed with raw DEFLATE when the compressed form is shorter and the runtime supports the streams.
|
|
1605
|
+
|
|
1606
|
+
| Option | Type | Meaning |
|
|
1607
|
+
| --- | --- | --- |
|
|
1608
|
+
| `maxBytes` | `number` | Positive safe integer; maximum serialized payload size |
|
|
1609
|
+
| `prefix` | `string` | 1–8 alphanumeric characters identifying the code family and version |
|
|
1610
|
+
|
|
1611
|
+
**Returns:** The shorter of the raw (`prefix` + `r`) and compressed (`prefix` + `d`) representations. Throws `ShareCodeError` (`too-large`, `invalid`) for oversized payloads and misconfigured options.
|
|
1612
|
+
|
|
1613
|
+
**Example:** Encode a shareable build as a code small enough for a URL.
|
|
1614
|
+
|
|
1615
|
+
```ts
|
|
1616
|
+
import { pack } from '@vielzeug/arsenal';
|
|
1617
|
+
|
|
1618
|
+
const code = await pack({ cards: ['slash', 'guard'] }, { maxBytes: 8192, prefix: 'ab1' });
|
|
1619
|
+
```
|
|
1620
|
+
|
|
1621
|
+
---
|
|
1622
|
+
|
|
1623
|
+
### unpack
|
|
1624
|
+
|
|
1625
|
+
```ts
|
|
1626
|
+
unpack(code: string, options: ShareCodeOptions): Promise
|
|
1627
|
+
```
|
|
1628
|
+
|
|
1629
|
+
Decodes a share code produced by `pack` with the same options. Both sides are bounded: input longer than `maxBytes` could carry is refused up front, streamed decompression stops at `maxBytes`, and non-canonical base64url is rejected by round-trip.
|
|
1630
|
+
|
|
1631
|
+
**Returns:** The parsed JSON payload. Throws `ShareCodeError` (`invalid` for foreign or malformed codes, `too-large` for budget overruns, `compression-unavailable` when a compressed code arrives on a runtime without `DecompressionStream`). Underlying compression failures surface as `ArsenalSerializationError`.
|
|
1632
|
+
|
|
1633
|
+
**Example:** Decode untrusted input within the byte budget.
|
|
1634
|
+
|
|
1635
|
+
```ts
|
|
1636
|
+
import { unpack } from '@vielzeug/arsenal';
|
|
1637
|
+
|
|
1638
|
+
const payload = await unpack(code, { maxBytes: 8192, prefix: 'ab1' });
|
|
1639
|
+
```
|
|
1640
|
+
|
|
248
1641
|
## Object
|
|
249
1642
|
|
|
250
1643
|
### tryParseJson
|
|
@@ -327,13 +1720,22 @@ type CacheOptions = {
|
|
|
327
1720
|
now?: () => number;
|
|
328
1721
|
ttlMs?: number;
|
|
329
1722
|
};
|
|
1723
|
+
|
|
1724
|
+
interface CompressionOptions {
|
|
1725
|
+
format?: CompressionFormat;
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
interface DecompressionOptions extends CompressionOptions {
|
|
1729
|
+
maxOutputBytes: number;
|
|
1730
|
+
}
|
|
330
1731
|
```
|
|
331
1732
|
|
|
332
1733
|
## Errors
|
|
333
1734
|
|
|
334
1735
|
- `RangeError`: invalid numeric bounds, capacity, concurrency, or retry count.
|
|
335
1736
|
- `TypeError`: invalid value types, unsupported comparison, or required path missing.
|
|
336
|
-
- `ArsenalSerializationError`: memo or hash cannot serialize supplied input.
|
|
1737
|
+
- `ArsenalSerializationError`: memo or hash cannot serialize supplied input; compression fails, is unavailable, receives an invalid output limit, or exceeds that limit. Stream failures retain the original error as `cause`.
|
|
1738
|
+
- `ShareCodeError`: a share code cannot be encoded or decoded; the `reason` field is `invalid`, `too-large`, or `compression-unavailable`.
|
|
337
1739
|
|
|
338
1740
|
### Usage Guide
|
|
339
1741
|
|
|
@@ -500,6 +1902,27 @@ const payload = JSON.parse(base64UrlToText(code));
|
|
|
500
1902
|
|
|
501
1903
|
Decoding throws on characters outside the base64url alphabet, so corrupted input fails loudly instead of decoding to garbage.
|
|
502
1904
|
|
|
1905
|
+
## Compress Share Payloads
|
|
1906
|
+
|
|
1907
|
+
Compress UTF-8 bytes before Base64url encoding. Set a decoded-byte limit before accepting compressed input from another device.
|
|
1908
|
+
|
|
1909
|
+
```ts
|
|
1910
|
+
import { base64UrlToBytes, bytesToBase64Url, compressBytes, decompressBytes } from '@vielzeug/arsenal';
|
|
1911
|
+
|
|
1912
|
+
const payload = JSON.stringify({ name: 'Hunters', notes: 'An expedition through Alborea. '.repeat(20) });
|
|
1913
|
+
const compressed = await compressBytes(new TextEncoder().encode(payload));
|
|
1914
|
+
const code = bytesToBase64Url(compressed);
|
|
1915
|
+
const bytes = await decompressBytes(base64UrlToBytes(code), { maxOutputBytes: 8192 });
|
|
1916
|
+
const restored = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
1917
|
+
console.log(restored === payload);
|
|
1918
|
+
```
|
|
1919
|
+
|
|
1920
|
+
Both helpers default to `deflate-raw`. You can explicitly select `gzip` or `deflate`; use the same format at both ends. The helpers reject when native streams do not support the selected format. They do not choose a fallback or define a wire protocol.
|
|
1921
|
+
|
|
1922
|
+
For a complete versioned envelope over these primitives — prefix, compression mode marker, byte budgets on both sides — see [`pack` / `unpack`](./api.md#pack).
|
|
1923
|
+
|
|
1924
|
+
Compression can enlarge small inputs. Compare the final encoded strings, including any format marker, before choosing a representation. Bound input size before decoding Base64url and validate decompressed JSON against your schema. The decompression limit bounds retained output, not native stream working memory.
|
|
1925
|
+
|
|
503
1926
|
## Working with Other Vielzeug Libraries
|
|
504
1927
|
|
|
505
1928
|
Use Spell after `tryParseJson` for typed external data. Use Vault instead of `cache` when data must survive reloads or process restart.
|
|
@@ -533,6 +1956,7 @@ const settings = parsed.ok ? Settings.parse(parsed.value) : { theme: 'system' };
|
|
|
533
1956
|
- [Array utilities](./examples/array.md)
|
|
534
1957
|
- [Async utilities](./examples/async.md)
|
|
535
1958
|
- [Cache utilities](./examples/cache.md)
|
|
1959
|
+
- [Encoding utilities](./examples/encoding.md)
|
|
536
1960
|
- [Function utilities](./examples/function.md)
|
|
537
1961
|
- [Guards / Typed predicates](./examples/typed.md)
|
|
538
1962
|
- [Math utilities](./examples/math.md)
|
|
@@ -555,6 +1979,7 @@ const settings = parsed.ok ? Settings.parse(parsed.value) : { theme: 'system' };
|
|
|
555
1979
|
- taskPool - Bounded concurrent work (id: `async-queue`)
|
|
556
1980
|
- retry - Retry failed operations (id: `async-retry`)
|
|
557
1981
|
- waitFor - Poll until condition is true or timeout/abort fires (id: `async-waitFor`)
|
|
1982
|
+
- compressBytes - Bounded share payload compression (id: `encoding-compression`)
|
|
558
1983
|
- debounce - Trailing (default) and leading-edge options (id: `function-debounce`)
|
|
559
1984
|
- memo - LRU cache with size tracking and invalidation (id: `function-memo`)
|
|
560
1985
|
- pipe - Left-to-right function composition (id: `function-pipe`)
|
|
@@ -3207,7 +4632,13 @@ Sends one HTTP request. `config.method` defaults to `GET`; pass any method (incl
|
|
|
3207
4632
|
| `timeout` | `number` | Integer milliseconds from 1 to 2,147,483,647, or `Infinity`; overrides default |
|
|
3208
4633
|
| `fetchInit` | `Omit` | Raw fetch options for advanced use |
|
|
3209
4634
|
|
|
3210
|
-
**Returns:** Parsed response body (or `undefined` for empty bodies).
|
|
4635
|
+
**Returns:** Parsed response body (or `undefined` for empty bodies). With
|
|
4636
|
+
`responseType: 'raw'` the resolved value is the `Response` itself; a `204`/`205`
|
|
4637
|
+
answer whose transport carried an unexpected empty body stream is normalized to
|
|
4638
|
+
`body: null` — the stray stream is cancelled and headers, status, statusText,
|
|
4639
|
+
URL, redirect and type metadata are preserved (on the response and its clones).
|
|
4640
|
+
A null-body raw response owns no pending resource, so no consumption is required
|
|
4641
|
+
to release the request.
|
|
3211
4642
|
|
|
3212
4643
|
```ts
|
|
3213
4644
|
const created = await courier.request('/users', {
|
|
@@ -3487,7 +4918,7 @@ Concurrent callers share physical work but own their own signal and timeout. One
|
|
|
3487
4918
|
|
|
3488
4919
|
## Response Parsing
|
|
3489
4920
|
|
|
3490
|
-
Courier parses successful 2xx response bodies automatically based on `content-type`, unless you set `responseType` explicitly (`'json'`, `'text'`, `'blob'`, `'arrayBuffer'`, or `'raw'` for the `Response` itself). Empty JSON bodies return `undefined` instead of throwing. Raw response bodies remain owned by Courier until consumed or cancelled, so `cancelAll()` and `dispose()` still abort them. Raw responses cannot be combined with `schema`. Always consume or cancel the body to release request ownership, and set `timeout: Infinity` for intentionally long-lived streams. Courier preserves URL, redirect, and type metadata on tracked responses and their clones.
|
|
4921
|
+
Courier parses successful 2xx response bodies automatically based on `content-type`, unless you set `responseType` explicitly (`'json'`, `'text'`, `'blob'`, `'arrayBuffer'`, or `'raw'` for the `Response` itself). Empty JSON bodies return `undefined` instead of throwing. Raw response bodies remain owned by Courier until consumed or cancelled, so `cancelAll()` and `dispose()` still abort them. Raw responses cannot be combined with `schema`. Always consume or cancel the body to release request ownership, and set `timeout: Infinity` for intentionally long-lived streams. Courier preserves URL, redirect, and type metadata on tracked responses and their clones. A `204`/`205` raw answer is normalized to `body: null` — a stray empty transport stream is cancelled for you — so a null-body raw response never carries pending body ownership and needs no consumption.
|
|
3491
4922
|
|
|
3492
4923
|
```ts
|
|
3493
4924
|
const buffer = await courier.request('/files/{id}', {
|
|
@@ -3670,6 +5101,7 @@ There is no `use()` method. To change middleware, create a new client. This keep
|
|
|
3670
5101
|
## Examples
|
|
3671
5102
|
|
|
3672
5103
|
- [Authentication](./examples/authentication.md)
|
|
5104
|
+
- [Service Discovery and Custom Fetch](./examples/service-discovery-and-custom-fetch.md)
|
|
3673
5105
|
- [CRUD Operations](./examples/crud-operations.md)
|
|
3674
5106
|
- [Disposal](./examples/disposal.md)
|
|
3675
5107
|
- [Error Handling Patterns](./examples/error-handling-patterns.md)
|
|
@@ -16668,7 +18100,7 @@ const chart = createScatterChart(host, {
|
|
|
16668
18100
|
chart.dispose();
|
|
16669
18101
|
```
|
|
16670
18102
|
|
|
16671
|
-
Scatter interaction reports
|
|
18103
|
+
Scatter interaction reports the datum and series of the point nearest the pointer in two dimensions, without a `values` array. Keyboard navigation visits points across series in x order. Tooltip `titleFormat` receives the x-value and `valueFormat` the y-value. On mount, points grow from radius zero at their final positions; updates slide existing points and grow new ones.
|
|
16672
18104
|
|
|
16673
18105
|
### `createBarChart()`
|
|
16674
18106
|
|
|
@@ -16992,7 +18424,7 @@ export interface TransitionConfig {
|
|
|
16992
18424
|
easing?: EasingName | ((t: number) => number);
|
|
16993
18425
|
/** `system` skips animation when reduced motion is preferred. */
|
|
16994
18426
|
preference?: 'always' | 'never' | 'system';
|
|
16995
|
-
/** Per-bar delay on bar charts or per-series delay on radar charts. */
|
|
18427
|
+
/** Per-bar delay on bar charts, per-entering-point delay (x order) on scatter charts, or per-series delay on radar charts. Bar and scatter charts cap the total added delay at about 400 ms. */
|
|
16996
18428
|
stagger?: number;
|
|
16997
18429
|
}
|
|
16998
18430
|
|
|
@@ -17171,6 +18603,7 @@ export interface AxisConfig {
|
|
|
17171
18603
|
position?: TPosition;
|
|
17172
18604
|
tickCount?: number;
|
|
17173
18605
|
tickFormat?: (value: Date | number | string) => string;
|
|
18606
|
+
tickValues?: ReadonlyArray;
|
|
17174
18607
|
}
|
|
17175
18608
|
|
|
17176
18609
|
export type XAxisConfig = AxisConfig;
|
|
@@ -17179,6 +18612,8 @@ export type YAxisConfig = AxisConfig;
|
|
|
17179
18612
|
export interface TooltipConfig {
|
|
17180
18613
|
offset?: number;
|
|
17181
18614
|
render?: (datum: Datum, series: Series) => Node | string;
|
|
18615
|
+
titleFormat?: (key: Date | number | string) => string;
|
|
18616
|
+
valueFormat?: (value: number, datum: Datum, series: Series) => string;
|
|
17182
18617
|
}
|
|
17183
18618
|
|
|
17184
18619
|
export interface CrosshairConfig {
|
|
@@ -17196,7 +18631,11 @@ export interface LegendConfig {
|
|
|
17196
18631
|
|
|
17197
18632
|
The crosshair defaults to a vertical line that snaps to the nearest datum; the horizontal line is hidden by default. With `snap: false`, only the guide follows the pointer—tooltip and callback data still refer to the nearest datum.
|
|
17198
18633
|
|
|
17199
|
-
|
|
18634
|
+
`tickValues` renders exactly the given ticks instead of scale-generated ones, and gridlines follow the same list. Values must match the axis's scale kind (numbers on a linear axis, `Date`s on a time axis, category strings on a band axis); an off-scale value warns in development. Without it, ticks come from the scale as before.
|
|
18635
|
+
|
|
18636
|
+
Numeric tick labels at a magnitude of 1e5 or above default to compact notation (`123K`, `1.23M`) so long numbers fit the default value-axis margin; pass `tickFormat: String` for raw labels. Supplying a partial `yAxis` (or the value axis of a horizontal bar chart) merges over the default, so `{ tickFormat }` alone keeps the default grid lines.
|
|
18637
|
+
|
|
18638
|
+
`titleFormat` and `valueFormat` shape the default comparison tooltip on line, area, and bar charts—the title from the focused key and each row's value—and the same formatting is applied to the tooltip's spoken summary. `render` still replaces the whole tooltip body and takes precedence. Tooltip strings are assigned as text, not parsed as HTML. For a radar chart, `tooltip.render` receives a datum whose `meta` contains the active axis, all series values, and the default announcement text.
|
|
17200
18639
|
|
|
17201
18640
|
### Chart Configuration Types
|
|
17202
18641
|
|
|
@@ -17519,7 +18958,17 @@ const chart = createLineChart(container, {
|
|
|
17519
18958
|
chart.dispose();
|
|
17520
18959
|
```
|
|
17521
18960
|
|
|
17522
|
-
`tickFormat` formats axis labels only. Tooltip content and accessibility announcements use the underlying keys and values.
|
|
18961
|
+
`tickFormat` formats axis labels only. Tooltip content and accessibility announcements use the underlying keys and values. To render an exact set of ticks instead of scale-generated ones, pass `tickValues`; gridlines follow the same list. Values must match the axis's scale kind, and an off-scale value warns in development:
|
|
18962
|
+
|
|
18963
|
+
```ts
|
|
18964
|
+
// Force a tick on the last month, which nice-stepped ticks can skip.
|
|
18965
|
+
const chart = createLineChart(container, {
|
|
18966
|
+
series: [{ data: [{ key: 0, value: 90 }, { key: 11, value: 128 }], name: 'Costs' }],
|
|
18967
|
+
xAxis: { tickValues: [0, 6, 11] },
|
|
18968
|
+
});
|
|
18969
|
+
```
|
|
18970
|
+
|
|
18971
|
+
Numeric tick labels at a magnitude of `1e5` or above default to compact notation (`123K`, `1.23M`) so long numbers fit the default value-axis margin; pass `tickFormat: String` for raw labels. Supplying a partial value-axis config merges over its default, so `yAxis: { tickFormat }` alone keeps the default grid lines.
|
|
17523
18972
|
|
|
17524
18973
|
## Bar Charts
|
|
17525
18974
|
|
|
@@ -17577,7 +19026,7 @@ chart.dispose();
|
|
|
17577
19026
|
|
|
17578
19027
|
## Scatter Charts
|
|
17579
19028
|
|
|
17580
|
-
Scatter charts treat every datum as an independent point: `key` is the numeric x-value and `value` is the y-value. The scales fit the observed values rather than forcing the y-domain to include zero. Set `pointRadius` on a series to change its marker size.
|
|
19029
|
+
Scatter charts treat every datum as an independent point: `key` is the numeric or `Date` x-value and `value` is the y-value. The scales fit the observed values rather than forcing the y-domain to include zero. Set `pointRadius` on a series to change its marker size (default `3`).
|
|
17581
19030
|
|
|
17582
19031
|
```ts
|
|
17583
19032
|
import { createScatterChart } from '@vielzeug/prism';
|
|
@@ -17599,7 +19048,7 @@ const chart = createScatterChart(container, {
|
|
|
17599
19048
|
chart.dispose();
|
|
17600
19049
|
```
|
|
17601
19050
|
|
|
17602
|
-
Scatter callbacks identify
|
|
19051
|
+
Scatter callbacks identify the nearest point in two dimensions and do not provide cross-series `values`, because points do not share a category key. Keyboard navigation visits every point across series in x order. With a tooltip, `titleFormat` formats the x-value and `valueFormat` the y-value, in both the visible row and the spoken summary.
|
|
17603
19052
|
|
|
17604
19053
|
## Forecast and Emphasis Styling
|
|
17605
19054
|
|
|
@@ -17716,7 +19165,7 @@ For a stacked sparkline, each segment can set `value`, `color`, and `label`. Spa
|
|
|
17716
19165
|
|
|
17717
19166
|
## Interaction
|
|
17718
19167
|
|
|
17719
|
-
Set `tooltip: true` to show Prism's default tooltip, or pass a `TooltipConfig` to format its content. A `render` callback receives the active `Datum` and `Series
|
|
19168
|
+
Set `tooltip: true` to show Prism's default tooltip, or pass a `TooltipConfig` to format its content. `titleFormat` and `valueFormat` shape the default comparison tooltip on line, area, and bar charts—the title from the focused key and each row's value—without rebuilding its markup, and the same formatting is applied to the tooltip's spoken summary. A `render` callback receives the active `Datum` and `Series` and replaces the whole body, taking precedence over the formatters. Returned strings are inserted as text; return a DOM `Node` for structured content.
|
|
17720
19169
|
|
|
17721
19170
|
```ts
|
|
17722
19171
|
import { createLineChart } from '@vielzeug/prism';
|
|
@@ -17725,17 +19174,21 @@ const container = document.createElement('div');
|
|
|
17725
19174
|
container.style.cssText = 'width:640px;height:320px';
|
|
17726
19175
|
document.body.append(container);
|
|
17727
19176
|
|
|
19177
|
+
const compact = new Intl.NumberFormat(undefined, { notation: 'compact' });
|
|
19178
|
+
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
19179
|
+
|
|
17728
19180
|
const chart = createLineChart(container, {
|
|
17729
|
-
series: [{ data: [{ key:
|
|
19181
|
+
series: [{ data: [{ key: 11, value: 128000 }], name: 'EC2' }],
|
|
17730
19182
|
tooltip: {
|
|
17731
|
-
|
|
19183
|
+
titleFormat: (key) => months[Number(key)] ?? String(key),
|
|
19184
|
+
valueFormat: (value) => compact.format(value),
|
|
17732
19185
|
},
|
|
17733
19186
|
});
|
|
17734
19187
|
|
|
17735
19188
|
chart.dispose();
|
|
17736
19189
|
```
|
|
17737
19190
|
|
|
17738
|
-
`onHover` receives an event while a point, category, slice, or radar axis is active, then `null` when the interaction clears. `onClick` receives the selected event. For line, area, and bar charts, `ChartEvent.values` contains each series' datum at that shared key; a missing datum is `undefined`. Scatter
|
|
19191
|
+
`onHover` receives an event while a point, category, slice, or radar axis is active, then `null` when the interaction clears. `onClick` receives the selected event. For line, area, and bar charts, `ChartEvent.values` contains each series' datum at that shared key; a missing datum is `undefined`. Scatter events are `ChartEvent` objects without `values`; pie, radar, and sparkline use their chart-specific event types.
|
|
17739
19192
|
|
|
17740
19193
|
`crosshair` is available on line, area, and scatter charts. By default it shows a vertical guide and snaps the line to the nearest datum. Set `horizontal: true` to add a horizontal guide or `vertical: false` to hide the vertical one. Set `snap: false` to make the guide follow the pointer; tooltip and callback data still come from the nearest datum.
|
|
17741
19194
|
|
|
@@ -17766,11 +19219,11 @@ chart.dispose();
|
|
|
17766
19219
|
|
|
17767
19220
|
Columns grow together from their baseline by default over 300 ms. Lines trace their final curve over 420 ms, uncovering point markers along the way without fading or shifting the series. Line data updates retain the default 300 ms geometry transition; an explicit `duration` overrides both timings.
|
|
17768
19221
|
|
|
17769
|
-
`preference: 'system'` (the default) disables JavaScript motion when the user prefers reduced motion. Use `'always'` to ignore that preference or `'never'` to disable motion. `stagger` sets an optional delay between bars or radar series; bar charts cap the effective delay so
|
|
19222
|
+
`preference: 'system'` (the default) disables JavaScript motion when the user prefers reduced motion. Use `'always'` to ignore that preference or `'never'` to disable motion. `stagger` sets an optional delay between bars, entering scatter points (in x order), or radar series; bar and scatter charts cap the effective delay so many marks do not add unbounded time. Named easing values are `ease-in`, `ease-in-out`, `ease-out`, `back-out`, `expo-out`, and `linear`; you can also provide an easing function.
|
|
17770
19223
|
|
|
17771
19224
|
## Responsive Layout and Lifecycle
|
|
17772
19225
|
|
|
17773
|
-
Size the host with CSS. Prism observes its content box and updates the SVG dimensions and chart layout when it changes. Bar and
|
|
19226
|
+
Size the host with CSS. Prism observes its content box and updates the SVG dimensions and chart layout when it changes. Bar, line, and scatter resize redraws apply immediately rather than animating between layout sizes; entrance animations and explicit data-update transitions remain enabled. The legend is rendered as container chrome outside the SVG and included in resize calculations.
|
|
17774
19227
|
|
|
17775
19228
|
Call `dispose()` when the view no longer owns the chart. Disposal is idempotent: it removes the SVG, tooltip, legend, and resize observation, stops in-flight chart motion, and aborts `disposalSignal`. `chart[Symbol.dispose]()` calls the same cleanup method.
|
|
17776
19229
|
|
|
@@ -18939,7 +20392,7 @@ Component registration happens through side-effect imports such as `@vielzeug/re
|
|
|
18939
20392
|
|
|
18940
20393
|
**Feedback:** `ore-alert`, `ore-async`, `ore-badge`, `ore-chip`, `ore-cookie-banner`, `ore-password-strength`, `ore-progress`, `ore-skeleton`, `ore-toast`, `ore-typing-indicator`
|
|
18941
20394
|
|
|
18942
|
-
**Inputs:** `ore-button`, `ore-button-group`, `ore-calendar`, `ore-checkbox`, `ore-checkbox-group`, `ore-column`, `ore-combobox`, `ore-counter`, `ore-datagrid`, `ore-date-picker`, `ore-file-input`, `ore-input`, `ore-message-composer`, `ore-number-input`, `ore-otp-input`, `ore-qr-scanner`, `ore-radio`, `ore-radio-group`, `ore-rating`, `ore-select`, `ore-slider`, `ore-switch`, `ore-textarea`, `ore-time-picker`
|
|
20395
|
+
**Inputs:** `ore-button`, `ore-button-group`, `ore-calendar`, `ore-checkbox`, `ore-checkbox-group`, `ore-column`, `ore-combobox`, `ore-counter`, `ore-datagrid`, `ore-date-picker`, `ore-file-input`, `ore-input`, `ore-message-composer`, `ore-number-input`, `ore-otp-input`, `ore-qr-scanner`, `ore-query-bar`, `ore-radio`, `ore-radio-group`, `ore-rating`, `ore-select`, `ore-slider`, `ore-switch`, `ore-textarea`, `ore-time-picker`
|
|
18943
20396
|
|
|
18944
20397
|
**Layout:** `ore-box`, `ore-grid`, `ore-grid-item`, `ore-navbar`, `ore-sidebar`
|
|
18945
20398
|
|
|
@@ -19045,7 +20498,7 @@ import type { OreButtonProps } from '@vielzeug/refine/button';
|
|
|
19045
20498
|
| Content | `avatar`, `avatar-group`, `breadcrumb`, `card`, `carousel`, `chat-message`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `list-item`, `marquee`, `pagination`, `separator`, `speech-player`, `stats`, `step`, `stepper`, `table`, `text` |
|
|
19046
20499
|
| Disclosure | `accordion`, `accordion-item`, `tabs`, `tab-item`, `tab-panel` |
|
|
19047
20500
|
| Feedback | `alert`, `async`, `badge`, `chip`, `cookie-banner`, `password-strength`, `progress`, `skeleton`, `toast`, `typing-indicator` |
|
|
19048
|
-
| Inputs | `button`, `button-group`, `calendar`, `checkbox`, `checkbox-group`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `radio`, `radio-group`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |
|
|
20501
|
+
| Inputs | `button`, `button-group`, `calendar`, `checkbox`, `checkbox-group`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `query-bar`, `radio`, `radio-group`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |
|
|
19049
20502
|
| Layout | `box`, `grid`, `grid-item`, `navbar`, `sidebar` |
|
|
19050
20503
|
| Overlays | `command-palette`, `dialog`, `drawer`, `menu`, `navigation-menu`, `popover`, `tooltip` |
|
|
19051
20504
|
|
|
@@ -28979,6 +30432,7 @@ useEffect(() => {
|
|
|
28979
30432
|
## Examples
|
|
28980
30433
|
|
|
28981
30434
|
- [Sync a Vault Store](./examples/sync-a-vault-store.md)
|
|
30435
|
+
- [Make Store Commands Undoable](./examples/make-store-commands-undoable.md)
|
|
28982
30436
|
- [Keep Deletions from Resurrecting](./examples/keep-deletions-from-resurrecting.md)
|
|
28983
30437
|
- [Switch Accounts Safely](./examples/switch-accounts-safely.md)
|
|
28984
30438
|
|