@umituz/web-hono 1.14.1 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -2
- package/src/auth.ts +2 -0
- package/src/cookies.ts +41 -0
- package/src/docstore.ts +237 -96
- package/src/http.ts +63 -0
- package/src/index.ts +6 -2
- package/src/lib.ts +23 -0
- package/src/r2.ts +110 -0
- package/src/resource.ts +129 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), and db lifecycle scripts (reset / snapshot / seed)",
|
|
3
|
+
"version": "1.16.0",
|
|
4
|
+
"description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), cookie channels + request scope/ETag/R2-stream server helpers, TTL resource cache, and db lifecycle scripts (reset / snapshot / seed)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
7
7
|
"types": "./src/index.ts",
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
"./auth": "./src/auth.ts",
|
|
19
19
|
"./mail": "./src/mail.ts",
|
|
20
20
|
"./etag": "./src/etag.ts",
|
|
21
|
+
"./cookies": "./src/cookies.ts",
|
|
22
|
+
"./http": "./src/http.ts",
|
|
23
|
+
"./r2": "./src/r2.ts",
|
|
24
|
+
"./resource": "./src/resource.ts",
|
|
21
25
|
"./package.json": "./package.json"
|
|
22
26
|
},
|
|
23
27
|
"scripts": {
|
package/src/auth.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { betterAuth } from 'better-auth';
|
|
2
|
+
import { bearer } from 'better-auth/plugins';
|
|
2
3
|
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
|
|
3
4
|
import { eq } from 'drizzle-orm';
|
|
4
5
|
import { Hono } from 'hono';
|
|
@@ -123,6 +124,7 @@ function initAuth(env: AuthEnv, opts: AuthOptions<AuthEnv>) {
|
|
|
123
124
|
},
|
|
124
125
|
session: { expiresIn: SESSION_SECONDS, updateAge: UPDATE_AGE_SECONDS },
|
|
125
126
|
trustedOrigins: opts.trustedOrigins ?? [],
|
|
127
|
+
plugins: [bearer()],
|
|
126
128
|
});
|
|
127
129
|
}
|
|
128
130
|
|
package/src/cookies.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export type CookieSameSite = 'lax' | 'strict' | 'none';
|
|
2
|
+
|
|
3
|
+
export interface CookieChannelConfig {
|
|
4
|
+
/** Wire name of the cookie (`prefs_theme`…). */
|
|
5
|
+
key: string;
|
|
6
|
+
/** max-age in seconds — long-lived preferences pass a year. */
|
|
7
|
+
maxAgeSeconds: number;
|
|
8
|
+
sameSite: CookieSameSite;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface CookieChannel {
|
|
12
|
+
/** Current value, or null when the cookie is absent/empty. */
|
|
13
|
+
read(): string | null;
|
|
14
|
+
write(value: string): void;
|
|
15
|
+
clear(): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One named browser cookie, read/write/clear — the only cookie surface apps
|
|
20
|
+
* should hand-roll. Serializes exactly `key=value; path=/; max-age=N;
|
|
21
|
+
* samesite=X` and parses back defensively (values never contain `;`).
|
|
22
|
+
*/
|
|
23
|
+
export function createCookieChannel(config: CookieChannelConfig): CookieChannel {
|
|
24
|
+
const prefix = `${config.key}=`;
|
|
25
|
+
return {
|
|
26
|
+
read() {
|
|
27
|
+
const entry = document.cookie
|
|
28
|
+
.split('; ')
|
|
29
|
+
.find((part) => part.startsWith(prefix));
|
|
30
|
+
const value = entry === undefined ? null : entry.slice(prefix.length);
|
|
31
|
+
if (value === null || value.length === 0) return null;
|
|
32
|
+
return value;
|
|
33
|
+
},
|
|
34
|
+
write(value) {
|
|
35
|
+
document.cookie = `${config.key}=${value}; path=/; max-age=${config.maxAgeSeconds}; samesite=${config.sameSite}`;
|
|
36
|
+
},
|
|
37
|
+
clear() {
|
|
38
|
+
document.cookie = `${config.key}=; path=/; max-age=0; samesite=${config.sameSite}`;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
package/src/docstore.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { and, eq, getTableColumns, isNull, sql } from 'drizzle-orm';
|
|
2
|
+
import { and, eq, getTableColumns, inArray, isNull, sql } from 'drizzle-orm';
|
|
3
3
|
import { drizzle } from 'drizzle-orm/neon-http';
|
|
4
4
|
import { neon } from '@neondatabase/serverless';
|
|
5
5
|
import { validator } from 'hono/validator';
|
|
@@ -22,10 +22,16 @@ import type { ApiEnv } from './env';
|
|
|
22
22
|
* listDocs/getDoc) that seed scripts and server-side workflows call
|
|
23
23
|
* directly. Status machines ride along as declarative `transitions` maps and
|
|
24
24
|
* write guards as `validate` hooks; violations surface as WorkflowError → 400.
|
|
25
|
+
*
|
|
26
|
+
* Router config scales it from open admin surfaces to authenticated user
|
|
27
|
+
* sync APIs: `scopeOf` derives the scope per request from the session (401
|
|
28
|
+
* when it resolves null, replacing the `?scope=` query), `routeKeys`
|
|
29
|
+
* allowlists which collections the router serves (others 404 as unknown,
|
|
30
|
+
* staying motor-only), `onPut`/`onPatch` shape writes (server-owned fields,
|
|
31
|
+
* deep merges), and `bulkBatch` runs the batch as grouped bulk writes that
|
|
32
|
+
* keep large syncs inside the Workers subrequest budget.
|
|
25
33
|
*/
|
|
26
34
|
|
|
27
|
-
type RequestContext = Context<{ Bindings: ApiEnv }>;
|
|
28
|
-
|
|
29
35
|
export type Doc = Record<string, unknown> & { id: string };
|
|
30
36
|
export type DocInput = Record<string, unknown>;
|
|
31
37
|
|
|
@@ -57,7 +63,7 @@ export interface DocCollectionSpec {
|
|
|
57
63
|
/** Collections that must always write the one fixed id. */
|
|
58
64
|
singletonId?: string;
|
|
59
65
|
/** Status state machine: allowed targets per current status. */
|
|
60
|
-
transitions?: Record<string, string[]
|
|
66
|
+
transitions?: Readonly<Record<string, readonly string[]>>;
|
|
61
67
|
/** Doc field the transitions guard reads. Default 'status'. */
|
|
62
68
|
statusKey?: string;
|
|
63
69
|
/** Write guard — see DocValidateFn. */
|
|
@@ -67,19 +73,54 @@ export interface DocCollectionSpec {
|
|
|
67
73
|
afterWrite?: DocAfterWriteFn;
|
|
68
74
|
}
|
|
69
75
|
|
|
70
|
-
export interface
|
|
76
|
+
export interface DocWriteHookArgs {
|
|
77
|
+
key: string;
|
|
78
|
+
/** Incoming document — hooks may rewrite server-owned fields in place. */
|
|
79
|
+
doc: Record<string, unknown>;
|
|
80
|
+
/** Current stored doc, or null when the write creates. */
|
|
81
|
+
existing: Record<string, unknown> | null;
|
|
82
|
+
/** Session scope when `scopeOf` resolved one (else undefined). */
|
|
83
|
+
scope: string | undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface DocPatchHookArgs {
|
|
87
|
+
key: string;
|
|
88
|
+
/** Incoming patch — hooks may rewrite it in place. */
|
|
89
|
+
patch: Record<string, unknown>;
|
|
90
|
+
existing: Doc | null;
|
|
91
|
+
scope: string | undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface DocStoreSpec<E extends ApiEnv = ApiEnv> {
|
|
71
95
|
collections: readonly DocCollectionSpec[];
|
|
72
96
|
/** Injectable db factory (tests, Hyperdrive). Default: per-request neon-http. */
|
|
73
|
-
db?: (c:
|
|
97
|
+
db?: (c: Context<{ Bindings: E }>) => CrudDb;
|
|
74
98
|
/** POST /batch op cap. Default 2000. */
|
|
75
99
|
maxBatch?: number;
|
|
100
|
+
/** Restrict the generated ROUTER to these keys (authz allowlist — admin
|
|
101
|
+
* collections stay motor-only). Others answer 404 as if unknown.
|
|
102
|
+
* Default: every collection is routed. */
|
|
103
|
+
routeKeys?: readonly string[];
|
|
104
|
+
/** Session-derived scope for the router: resolves per request (better-auth
|
|
105
|
+
* user id, tenant id…). Null answers 401. When set it replaces the
|
|
106
|
+
* `?scope=` query: scoped collections are filtered by it and puts get it
|
|
107
|
+
* stamped, so clients cannot read or write another scope's rows. */
|
|
108
|
+
scopeOf?: (c: Context<{ Bindings: E }>) => Promise<string | null>;
|
|
109
|
+
/** Router-level put shaping (server-owned fields) before the write. */
|
|
110
|
+
onPut?: (args: DocWriteHookArgs) => void | Promise<void>;
|
|
111
|
+
/** Router-level patch shaping (deep merges, server-owned fields). */
|
|
112
|
+
onPatch?: (args: DocPatchHookArgs) => void | Promise<void>;
|
|
113
|
+
/** Batch runs as grouped bulk writes — one guard read + chunked upserts
|
|
114
|
+
* per collection instead of per-op putDoc — keeping large sync batches
|
|
115
|
+
* inside the Workers subrequest budget. Default: per-op. */
|
|
116
|
+
bulkBatch?: boolean;
|
|
76
117
|
}
|
|
77
118
|
|
|
78
119
|
export class WorkflowError extends Error {}
|
|
79
120
|
export class UnknownCollectionError extends Error {}
|
|
80
121
|
|
|
81
122
|
/** Status machine check: staying put is always allowed. */
|
|
82
|
-
export function canTransition(map: Record<string, string[]
|
|
123
|
+
export function canTransition(map: Readonly<Record<string, readonly string[]>>, from: string, to: string): boolean {
|
|
83
124
|
return from === to || (map[from] ?? []).includes(to);
|
|
84
125
|
}
|
|
85
126
|
|
|
@@ -92,14 +133,15 @@ export function epoch(iso: unknown): number {
|
|
|
92
133
|
return Number.isNaN(ms) ? Date.now() : ms;
|
|
93
134
|
}
|
|
94
135
|
|
|
95
|
-
function defaultDb(c:
|
|
136
|
+
function defaultDb<E extends ApiEnv>(c: Context<{ Bindings: E }>): CrudDb {
|
|
96
137
|
return drizzle(neon(c.env.DATABASE_URL));
|
|
97
138
|
}
|
|
98
139
|
|
|
99
|
-
export function docStore(spec: DocStoreSpec) {
|
|
140
|
+
export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
|
|
100
141
|
const byKey = new Map(spec.collections.map((col) => [col.key, col]));
|
|
101
|
-
const getDb = spec.db ?? defaultDb
|
|
142
|
+
const getDb = spec.db ?? defaultDb<E>;
|
|
102
143
|
const maxBatch = spec.maxBatch ?? 2000;
|
|
144
|
+
const routeSet = spec.routeKeys === undefined ? null : new Set(spec.routeKeys);
|
|
103
145
|
|
|
104
146
|
function collectionOf(key: string): DocCollectionSpec | undefined {
|
|
105
147
|
return byKey.get(key);
|
|
@@ -111,6 +153,14 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
111
153
|
return col;
|
|
112
154
|
}
|
|
113
155
|
|
|
156
|
+
function requireRoute(key: string): DocCollectionSpec {
|
|
157
|
+
const col = requireSpec(key);
|
|
158
|
+
if (routeSet !== null && !routeSet.has(key)) {
|
|
159
|
+
throw new UnknownCollectionError(`Unknown collection '${key}'`);
|
|
160
|
+
}
|
|
161
|
+
return col;
|
|
162
|
+
}
|
|
163
|
+
|
|
114
164
|
function idFieldOf(col: DocCollectionSpec): string {
|
|
115
165
|
return col.idField ?? 'id';
|
|
116
166
|
}
|
|
@@ -295,138 +345,229 @@ export function docStore(spec: DocStoreSpec) {
|
|
|
295
345
|
.max(maxBatch),
|
|
296
346
|
}).strict();
|
|
297
347
|
|
|
298
|
-
function requireScopeQuery(c:
|
|
348
|
+
function requireScopeQuery(c: Context, col: DocCollectionSpec): string | undefined {
|
|
299
349
|
if (!col.scope) return undefined;
|
|
300
350
|
const q = c.req.query('scope');
|
|
301
351
|
if (!q) throw new WorkflowError(`Scoped collection '${col.key}' requires a scope query`);
|
|
302
352
|
return q;
|
|
303
353
|
}
|
|
304
354
|
|
|
305
|
-
|
|
355
|
+
function routeErrorResponse(c: Context, err: unknown): Response {
|
|
356
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
|
|
357
|
+
if (err instanceof UnknownCollectionError) return c.json({ error: err.message }, 404);
|
|
358
|
+
throw err;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function resolveScope(c: Context): Promise<string | null | undefined> {
|
|
362
|
+
if (spec.scopeOf === undefined) return undefined;
|
|
363
|
+
return spec.scopeOf(c as unknown as Context<{ Bindings: E }>);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function dbOf(c: Context): CrudDb {
|
|
367
|
+
return getDb(c as unknown as Context<{ Bindings: E }>);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const router = new Hono<{ Bindings: E }>();
|
|
306
371
|
|
|
307
372
|
router.get('/:collection', async (c) => {
|
|
308
373
|
try {
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
return c.json({ error: '
|
|
374
|
+
const col = requireRoute(c.req.param('collection'));
|
|
375
|
+
const scope = spec.scopeOf === undefined ? c.req.query('scope') : await resolveScope(c);
|
|
376
|
+
if (scope === null) return c.json({ error: 'Authentication required' }, 401);
|
|
377
|
+
return c.json(await listDocs(dbOf(c), col.key, scope));
|
|
378
|
+
} catch (err) {
|
|
379
|
+
return routeErrorResponse(c, err);
|
|
312
380
|
}
|
|
313
|
-
return c.json(await listDocs(getDb(c), c.req.param('collection'), c.req.query('scope')));
|
|
314
381
|
});
|
|
315
382
|
|
|
316
383
|
router.get('/:collection/:id', async (c) => {
|
|
317
|
-
let col: DocCollectionSpec;
|
|
318
384
|
try {
|
|
319
|
-
col =
|
|
320
|
-
|
|
321
|
-
return c.json({ error: '
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
try {
|
|
325
|
-
scope = requireScopeQuery(c, col);
|
|
385
|
+
const col = requireRoute(c.req.param('collection'));
|
|
386
|
+
const scope = spec.scopeOf === undefined ? requireScopeQuery(c, col) : await resolveScope(c);
|
|
387
|
+
if (scope === null) return c.json({ error: 'Authentication required' }, 401);
|
|
388
|
+
const doc = await getDoc(dbOf(c), col.key, c.req.param('id'), scope);
|
|
389
|
+
return doc ? c.json(doc) : c.json({ error: 'Document not found' }, 404);
|
|
326
390
|
} catch (err) {
|
|
327
|
-
|
|
328
|
-
throw err;
|
|
391
|
+
return routeErrorResponse(c, err);
|
|
329
392
|
}
|
|
330
|
-
const doc = await getDoc(getDb(c), col.key, c.req.param('id'), scope);
|
|
331
|
-
return doc ? c.json(doc) : c.json({ error: 'Document not found' }, 404);
|
|
332
393
|
});
|
|
333
394
|
|
|
334
395
|
router.put('/:collection/:id', validator('json', validateJson(docSchema, 'Invalid document payload')), async (c) => {
|
|
335
|
-
const key = c.req.param('collection');
|
|
336
|
-
let col: DocCollectionSpec;
|
|
337
396
|
try {
|
|
338
|
-
col =
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
397
|
+
const col = requireRoute(c.req.param('collection'));
|
|
398
|
+
const doc = c.req.valid('json') as unknown as DocInput;
|
|
399
|
+
const fld = idFieldOf(col);
|
|
400
|
+
if (typeof doc[fld] !== 'string' || (doc[fld] as string).length === 0) {
|
|
401
|
+
return c.json({ error: 'Invalid document payload', details: { [fld]: ['Required'] } }, 400);
|
|
402
|
+
}
|
|
403
|
+
if (doc[fld] !== c.req.param('id')) {
|
|
404
|
+
return c.json({ error: 'Body id does not match the URL' }, 400);
|
|
405
|
+
}
|
|
406
|
+
const queryMode = spec.scopeOf === undefined;
|
|
407
|
+
if (queryMode && col.scope && typeof doc[col.scope.field] !== 'string') {
|
|
408
|
+
const q = c.req.query('scope');
|
|
409
|
+
if (!q) return c.json({ error: `Scoped collection '${col.key}' requires a scope query` }, 400);
|
|
410
|
+
doc[col.scope.field] = q;
|
|
411
|
+
}
|
|
412
|
+
const scope = queryMode ? undefined : await resolveScope(c);
|
|
413
|
+
if (scope === null) return c.json({ error: 'Authentication required' }, 401);
|
|
414
|
+
if (col.scope && scope !== undefined) doc[col.scope.field] = scope;
|
|
415
|
+
const existing =
|
|
416
|
+
spec.onPut === undefined
|
|
417
|
+
? undefined
|
|
418
|
+
: await getDoc(dbOf(c), col.key, doc[fld] as string, col.scope ? scope : undefined);
|
|
419
|
+
if (spec.onPut !== undefined) {
|
|
420
|
+
await spec.onPut({ key: col.key, doc, existing: existing ?? null, scope: scope ?? undefined });
|
|
421
|
+
}
|
|
422
|
+
await putDoc(dbOf(c), col.key, doc);
|
|
423
|
+
return c.json(doc as Doc, existing ? 200 : 201);
|
|
357
424
|
} catch (err) {
|
|
358
|
-
|
|
359
|
-
throw err;
|
|
425
|
+
return routeErrorResponse(c, err);
|
|
360
426
|
}
|
|
361
|
-
return c.json(doc, 201);
|
|
362
427
|
});
|
|
363
428
|
|
|
364
429
|
router.patch('/:collection/:id', validator('json', validateJson(patchSchema, 'Invalid patch payload')), async (c) => {
|
|
365
|
-
const key = c.req.param('collection');
|
|
366
|
-
let col: DocCollectionSpec;
|
|
367
430
|
try {
|
|
368
|
-
col =
|
|
369
|
-
|
|
370
|
-
return c.json({ error: '
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
throw err;
|
|
378
|
-
}
|
|
379
|
-
try {
|
|
380
|
-
const merged = await patchDoc(getDb(c), key, c.req.param('id'), c.req.valid('json') as unknown as DocInput, scope);
|
|
431
|
+
const col = requireRoute(c.req.param('collection'));
|
|
432
|
+
const scope = spec.scopeOf === undefined ? requireScopeQuery(c, col) : await resolveScope(c);
|
|
433
|
+
if (scope === null) return c.json({ error: 'Authentication required' }, 401);
|
|
434
|
+
const patch = c.req.valid('json') as unknown as DocInput;
|
|
435
|
+
if (spec.onPatch !== undefined) {
|
|
436
|
+
const existing = await getDoc(dbOf(c), col.key, c.req.param('id'), col.scope ? scope : undefined);
|
|
437
|
+
await spec.onPatch({ key: col.key, patch, existing: existing ?? null, scope: scope ?? undefined });
|
|
438
|
+
}
|
|
439
|
+
const merged = await patchDoc(dbOf(c), col.key, c.req.param('id'), patch, col.scope ? scope : undefined);
|
|
381
440
|
return c.json(merged ?? {});
|
|
382
441
|
} catch (err) {
|
|
383
|
-
|
|
384
|
-
throw err;
|
|
442
|
+
return routeErrorResponse(c, err);
|
|
385
443
|
}
|
|
386
444
|
});
|
|
387
445
|
|
|
388
446
|
router.delete('/:collection/:id', async (c) => {
|
|
389
|
-
let col: DocCollectionSpec;
|
|
390
|
-
try {
|
|
391
|
-
col = requireSpec(c.req.param('collection'));
|
|
392
|
-
} catch {
|
|
393
|
-
return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
|
|
394
|
-
}
|
|
395
|
-
let scope: string | undefined;
|
|
396
447
|
try {
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
if (
|
|
400
|
-
|
|
401
|
-
}
|
|
402
|
-
try {
|
|
403
|
-
const gone = await softDeleteDoc(getDb(c), col.key, c.req.param('id'), scope);
|
|
448
|
+
const col = requireRoute(c.req.param('collection'));
|
|
449
|
+
const scope = spec.scopeOf === undefined ? requireScopeQuery(c, col) : await resolveScope(c);
|
|
450
|
+
if (scope === null) return c.json({ error: 'Authentication required' }, 401);
|
|
451
|
+
const gone = await softDeleteDoc(dbOf(c), col.key, c.req.param('id'), col.scope ? scope : undefined);
|
|
404
452
|
return gone ? c.json({ ok: true }) : c.json({ error: 'Document not found' }, 404);
|
|
405
453
|
} catch (err) {
|
|
406
|
-
|
|
407
|
-
throw err;
|
|
454
|
+
return routeErrorResponse(c, err);
|
|
408
455
|
}
|
|
409
456
|
});
|
|
410
457
|
|
|
411
458
|
router.post('/batch', validator('json', validateJson(batchSchema, 'Invalid batch payload')), async (c) => {
|
|
412
|
-
const
|
|
459
|
+
const batchError = (err: unknown, extra: Record<string, unknown> = {}): Response | null => {
|
|
460
|
+
if (err instanceof WorkflowError) return c.json({ error: err.message, ...extra }, 400);
|
|
461
|
+
if (err instanceof UnknownCollectionError) return c.json({ error: err.message, ...extra }, 404);
|
|
462
|
+
return null;
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
const scope = await resolveScope(c);
|
|
466
|
+
if (scope === null) return c.json({ error: 'Authentication required' }, 401);
|
|
467
|
+
|
|
468
|
+
if (!spec.bulkBatch) {
|
|
469
|
+
const applied: { collection: string; id: string }[] = [];
|
|
470
|
+
try {
|
|
471
|
+
for (const op of c.req.valid('json').ops) {
|
|
472
|
+
const col = requireRoute(op.collection);
|
|
473
|
+
if (op.op === 'put') {
|
|
474
|
+
const doc = op.doc as DocInput;
|
|
475
|
+
if (col.scope && scope !== undefined) doc[col.scope.field] = scope;
|
|
476
|
+
await putDoc(dbOf(c), op.collection, doc);
|
|
477
|
+
applied.push({ collection: op.collection, id: docIdOf(col, doc) });
|
|
478
|
+
} else {
|
|
479
|
+
const delScope = col.scope && scope === undefined ? op.scope : col.scope ? scope : op.scope;
|
|
480
|
+
await softDeleteDoc(dbOf(c), op.collection, op.id, delScope);
|
|
481
|
+
applied.push({ collection: op.collection, id: op.id });
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
} catch (err) {
|
|
485
|
+
const mapped = batchError(err, { applied: applied.length });
|
|
486
|
+
if (mapped !== null) return mapped;
|
|
487
|
+
throw err;
|
|
488
|
+
}
|
|
489
|
+
return c.json({ ok: true, applied: applied.length });
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const db = dbOf(c);
|
|
493
|
+
const putsByCollection = new Map<string, Map<string, DocInput>>();
|
|
494
|
+
const delsByCollection = new Map<string, Set<string>>();
|
|
413
495
|
try {
|
|
414
496
|
for (const op of c.req.valid('json').ops) {
|
|
415
|
-
|
|
416
|
-
if (op.op === '
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
497
|
+
const col = requireRoute(op.collection);
|
|
498
|
+
if (op.op === 'del') {
|
|
499
|
+
const dels = delsByCollection.get(op.collection) ?? new Set<string>();
|
|
500
|
+
dels.add(op.id);
|
|
501
|
+
delsByCollection.set(op.collection, dels);
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const doc = op.doc as DocInput;
|
|
505
|
+
const id = docIdOf(col, doc);
|
|
506
|
+
if (col.singletonId && id !== col.singletonId) {
|
|
507
|
+
throw new WorkflowError(`Collection '${op.collection}' only accepts document id '${col.singletonId}'`);
|
|
422
508
|
}
|
|
509
|
+
if (col.scope && scope !== undefined) doc[col.scope.field] = scope;
|
|
510
|
+
const puts = putsByCollection.get(op.collection) ?? new Map<string, DocInput>();
|
|
511
|
+
puts.set(id, doc);
|
|
512
|
+
putsByCollection.set(op.collection, puts);
|
|
513
|
+
}
|
|
514
|
+
} catch (err) {
|
|
515
|
+
const mapped = batchError(err);
|
|
516
|
+
if (mapped !== null) return mapped;
|
|
517
|
+
throw err;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
try {
|
|
521
|
+
let applied = 0;
|
|
522
|
+
for (const [key, docs] of putsByCollection) {
|
|
523
|
+
const col = requireSpec(key);
|
|
524
|
+
const existingById = new Map<string, DocInput>();
|
|
525
|
+
if (col.scope !== undefined && col.scope !== null) {
|
|
526
|
+
const needsExisting = col.transitions !== undefined || spec.onPut !== undefined;
|
|
527
|
+
if (needsExisting && scope !== undefined) {
|
|
528
|
+
const rows = await db
|
|
529
|
+
.select({ id: col.table.id, data: col.table.data })
|
|
530
|
+
.from(col.table)
|
|
531
|
+
.where(and(eq(col.scope.column, scope), inArray(col.table.id, [...docs.keys()])));
|
|
532
|
+
for (const row of rows) existingById.set(String(row.id), (row.data ?? {}) as DocInput);
|
|
533
|
+
}
|
|
534
|
+
} else if (spec.onPut !== undefined) {
|
|
535
|
+
for (const id of docs.keys()) {
|
|
536
|
+
const doc = await getDoc(db, key, id);
|
|
537
|
+
if (doc !== undefined) existingById.set(id, doc);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
for (const doc of docs.values()) {
|
|
541
|
+
const id = String(doc[idFieldOf(col)]);
|
|
542
|
+
const existing = existingById.get(id) ?? null;
|
|
543
|
+
if (spec.onPut !== undefined) await spec.onPut({ key, doc, existing, scope });
|
|
544
|
+
if (col.transitions !== undefined && existing !== null) {
|
|
545
|
+
const statusKey = col.statusKey ?? 'status';
|
|
546
|
+
const from = existing[statusKey];
|
|
547
|
+
const to = doc[statusKey];
|
|
548
|
+
if (typeof from === 'string' && typeof to === 'string' && !canTransition(col.transitions, from, to)) {
|
|
549
|
+
throw new WorkflowError(`Invalid ${key} transition ${from} → ${to}`);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
applied += await putDocs(db, key, [...docs.values()]);
|
|
554
|
+
}
|
|
555
|
+
for (const [key, ids] of delsByCollection) {
|
|
556
|
+
const col = requireSpec(key);
|
|
557
|
+
const conds = [inArray(col.table.id, [...ids])];
|
|
558
|
+
if (col.scope && scope !== undefined) conds.unshift(eq(col.scope.column, scope));
|
|
559
|
+
await db
|
|
560
|
+
.update(col.table)
|
|
561
|
+
.set({ deletedAt: Date.now() } as never)
|
|
562
|
+
.where(and(...conds));
|
|
563
|
+
applied += ids.size;
|
|
423
564
|
}
|
|
565
|
+
return c.json({ ok: true, applied });
|
|
424
566
|
} catch (err) {
|
|
425
|
-
|
|
426
|
-
if (
|
|
567
|
+
const mapped = batchError(err);
|
|
568
|
+
if (mapped !== null) return mapped;
|
|
427
569
|
throw err;
|
|
428
570
|
}
|
|
429
|
-
return c.json({ ok: true, applied: applied.length });
|
|
430
571
|
});
|
|
431
572
|
|
|
432
573
|
return {
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { getCookie } from 'hono/cookie';
|
|
3
|
+
import { matchesEtag } from './etag';
|
|
4
|
+
|
|
5
|
+
/** Cache-Control catalog for auth-private responses. */
|
|
6
|
+
export const CACHE_CONTROLS = {
|
|
7
|
+
/** Revalidate every time (audio/video streams, mutable payloads). */
|
|
8
|
+
privateRevalidate: 'private, max-age=0, must-revalidate',
|
|
9
|
+
/** Browser-fresh for a day (cover art and other immutable-ish assets). */
|
|
10
|
+
privateDay: 'private, max-age=86400',
|
|
11
|
+
/** ETag-carried payloads: cache allowed, revalidate on every use. */
|
|
12
|
+
etagRevalidate: 'no-cache',
|
|
13
|
+
} as const;
|
|
14
|
+
|
|
15
|
+
export interface RequestScopeConfig {
|
|
16
|
+
/** Query parameter that carries the scope explicitly (`?lang=ko`). */
|
|
17
|
+
queryParam: string;
|
|
18
|
+
/** Cookie consulted when the query parameter is absent. */
|
|
19
|
+
cookieKey: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Resolve a request-scoped value — a language, a tenant, a workspace —
|
|
24
|
+
* from the explicit query parameter first, then the ambient cookie, or
|
|
25
|
+
* null when the request carries neither. Routes answer a 400 on null
|
|
26
|
+
* instead of guessing a default.
|
|
27
|
+
*/
|
|
28
|
+
export function requestScopeOf(c: Context, config: RequestScopeConfig): string | null {
|
|
29
|
+
const fromQuery = c.req.query(config.queryParam);
|
|
30
|
+
if (fromQuery !== undefined && fromQuery.length > 0) return fromQuery;
|
|
31
|
+
const fromCookie = getCookie(c, config.cookieKey);
|
|
32
|
+
if (fromCookie !== undefined && fromCookie.length > 0) return fromCookie;
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The If-None-Match dance in one call: weak-compares the request's
|
|
38
|
+
* If-None-Match against `etag` and answers 304 (ETag + no-cache headers,
|
|
39
|
+
* empty body) or 200 (same headers plus the JSON payload). Payload types
|
|
40
|
+
* stay the caller's — only the transport is shared.
|
|
41
|
+
*/
|
|
42
|
+
export function respondWithEtag(c: Context, etag: string, payload: unknown) {
|
|
43
|
+
if (matchesEtag(c.req.header('If-None-Match'), etag)) {
|
|
44
|
+
return c.body(null, 304, { ETag: etag, 'Cache-Control': CACHE_CONTROLS.etagRevalidate });
|
|
45
|
+
}
|
|
46
|
+
c.header('ETag', etag);
|
|
47
|
+
c.header('Cache-Control', CACHE_CONTROLS.etagRevalidate);
|
|
48
|
+
return c.json(payload);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* `500 { error, details }` for caught errors in hand-rolled routes —
|
|
53
|
+
* the envelope's last resort outside the global onError.
|
|
54
|
+
*/
|
|
55
|
+
export function internalError(c: Context, message: string, err?: unknown) {
|
|
56
|
+
return c.json(
|
|
57
|
+
{
|
|
58
|
+
error: message,
|
|
59
|
+
details: err instanceof Error ? err.name : 'error',
|
|
60
|
+
},
|
|
61
|
+
500,
|
|
62
|
+
);
|
|
63
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
* `/store` createStore — the fetch-backed reactive store
|
|
20
20
|
* `/store/react` makeStoreHooks — useQuery/useDbValue/useCollection/useHydration
|
|
21
21
|
* `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
|
|
22
|
+
* `/cookies` createCookieChannel — one named browser cookie, read/write/clear
|
|
23
|
+
* `/http` requestScopeOf / respondWithEtag / internalError / CACHE_CONTROLS
|
|
24
|
+
* `/r2` streamFromBucket / parseRange — ranged R2 streaming
|
|
25
|
+
* `/resource` createResource — TTL-cached async value with subscribe
|
|
22
26
|
*/
|
|
23
27
|
export { createApi } from './api';
|
|
24
28
|
export type { ApiConfig } from './api';
|
|
@@ -27,9 +31,9 @@ export { ApiError, apiOnError, isUniqueViolation } from './errors';
|
|
|
27
31
|
export { crudRoutes, listRoutes } from './crud';
|
|
28
32
|
export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
|
|
29
33
|
export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
|
|
30
|
-
export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec } from './docstore';
|
|
34
|
+
export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec, DocWriteHookArgs, DocPatchHookArgs } from './docstore';
|
|
31
35
|
export { getDb } from './db';
|
|
32
|
-
export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor } from './lib';
|
|
36
|
+
export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor, mapLimit, withRetry } from './lib';
|
|
33
37
|
export { isoNow, isoAt, todayISO, addDaysISO } from './dates';
|
|
34
38
|
export type { IsoPrecision } from './dates';
|
|
35
39
|
export { resolveOrg, orgHasMode, nextNumber } from './org';
|
package/src/lib.ts
CHANGED
|
@@ -139,3 +139,26 @@ export function normalizeRow(table: PgTable, input: Record<string, unknown>): Re
|
|
|
139
139
|
}
|
|
140
140
|
return out;
|
|
141
141
|
}
|
|
142
|
+
|
|
143
|
+
/** Run `fn` over items in `limit`-sized waves — bounded DB subrequest fan-out. */
|
|
144
|
+
export async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
|
145
|
+
const out: R[] = [];
|
|
146
|
+
for (let i = 0; i < items.length; i += limit) {
|
|
147
|
+
out.push(...(await Promise.all(items.slice(i, i + limit).map(fn))));
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Retry transient Neon/HTTP blips: up to `attempts` tries, backoff 250ms·n. */
|
|
153
|
+
export async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
|
|
154
|
+
let lastErr: unknown;
|
|
155
|
+
for (let i = 0; i < attempts; i++) {
|
|
156
|
+
try {
|
|
157
|
+
return await fn();
|
|
158
|
+
} catch (err) {
|
|
159
|
+
lastErr = err;
|
|
160
|
+
await new Promise((r) => setTimeout(r, 250 * (i + 1)));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
throw lastErr;
|
|
164
|
+
}
|
package/src/r2.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
|
|
3
|
+
/** The R2 surface streamFromBucket needs — Cloudflare's binding satisfies
|
|
4
|
+
* it structurally, tests satisfy it with an in-memory fake. */
|
|
5
|
+
export interface R2StreamBucket {
|
|
6
|
+
head(key: string): Promise<{
|
|
7
|
+
size: number;
|
|
8
|
+
httpEtag: string;
|
|
9
|
+
httpMetadata?: { contentType?: string } | undefined;
|
|
10
|
+
} | null>;
|
|
11
|
+
get(key: string, options?: { range?: { offset: number; length: number } }): Promise<{ body: ReadableStream } | null>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface RangedRequest {
|
|
15
|
+
offset: number;
|
|
16
|
+
length: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Parse a single-range `bytes=` header against a known size: a valid window,
|
|
21
|
+
* 'invalid' (answer 416), or null (no Range header → full body).
|
|
22
|
+
*/
|
|
23
|
+
export function parseRange(header: string | undefined, size: number): RangedRequest | 'invalid' | null {
|
|
24
|
+
if (!header) return null;
|
|
25
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
26
|
+
if (!match) return 'invalid';
|
|
27
|
+
const [, startRaw, endRaw] = match;
|
|
28
|
+
if (startRaw === '' && endRaw === '') return 'invalid';
|
|
29
|
+
if (startRaw === '') {
|
|
30
|
+
const suffix = Number(endRaw);
|
|
31
|
+
if (!Number.isFinite(suffix) || suffix <= 0) return 'invalid';
|
|
32
|
+
const length = Math.min(suffix, size);
|
|
33
|
+
return { offset: size - length, length };
|
|
34
|
+
}
|
|
35
|
+
const start = Number(startRaw);
|
|
36
|
+
if (!Number.isFinite(start) || start < 0) return 'invalid';
|
|
37
|
+
if (start >= size) return 'invalid';
|
|
38
|
+
let end = size - 1;
|
|
39
|
+
if (endRaw !== '') {
|
|
40
|
+
const parsed = Number(endRaw);
|
|
41
|
+
if (!Number.isFinite(parsed) || parsed < start) return 'invalid';
|
|
42
|
+
end = Math.min(parsed, size - 1);
|
|
43
|
+
}
|
|
44
|
+
return { offset: start, length: end - start + 1 };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface StreamOptions {
|
|
48
|
+
/** Cache-Control value — CACHE_CONTROLS.privateRevalidate / privateDay. */
|
|
49
|
+
cacheControl: string;
|
|
50
|
+
/** e.g. `attachment; filename="report.pdf"`. */
|
|
51
|
+
contentDisposition?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Serve an R2 object as a Workers response: HEAD support, single-range
|
|
56
|
+
* requests (206 + Content-Range), malformed ranges (416), R2's own ETag
|
|
57
|
+
* and content type. Missing key or empty key answers 404 — callers pass
|
|
58
|
+
* `''` for docs without media.
|
|
59
|
+
*/
|
|
60
|
+
export async function streamFromBucket(
|
|
61
|
+
c: Context,
|
|
62
|
+
bucket: R2StreamBucket,
|
|
63
|
+
key: string,
|
|
64
|
+
options: StreamOptions,
|
|
65
|
+
) {
|
|
66
|
+
if (!key) return c.json({ error: 'not found' }, 404);
|
|
67
|
+
const head = await bucket.head(key);
|
|
68
|
+
if (!head) return c.json({ error: 'not found' }, 404);
|
|
69
|
+
const size = head.size;
|
|
70
|
+
const contentType = head.httpMetadata?.contentType ?? 'application/octet-stream';
|
|
71
|
+
const range = parseRange(c.req.header('Range'), size);
|
|
72
|
+
|
|
73
|
+
if (range === 'invalid') {
|
|
74
|
+
return c.body(null, 416, {
|
|
75
|
+
'Content-Range': `bytes */${size}`,
|
|
76
|
+
'Accept-Ranges': 'bytes',
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const headers: Record<string, string> = {
|
|
81
|
+
'Content-Type': contentType,
|
|
82
|
+
'Accept-Ranges': 'bytes',
|
|
83
|
+
'Cache-Control': options.cacheControl,
|
|
84
|
+
ETag: head.httpEtag,
|
|
85
|
+
};
|
|
86
|
+
if (options.contentDisposition !== undefined) headers['Content-Disposition'] = options.contentDisposition;
|
|
87
|
+
|
|
88
|
+
if (c.req.method === 'HEAD') {
|
|
89
|
+
if (range) {
|
|
90
|
+
headers['Content-Length'] = String(range.length);
|
|
91
|
+
headers['Content-Range'] = `bytes ${range.offset}-${range.offset + range.length - 1}/${size}`;
|
|
92
|
+
} else {
|
|
93
|
+
headers['Content-Length'] = String(size);
|
|
94
|
+
}
|
|
95
|
+
return c.body(null, 200, headers);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (range) {
|
|
99
|
+
const obj = await bucket.get(key, { range: { offset: range.offset, length: range.length } });
|
|
100
|
+
if (!obj) return c.json({ error: 'not found' }, 404);
|
|
101
|
+
headers['Content-Length'] = String(range.length);
|
|
102
|
+
headers['Content-Range'] = `bytes ${range.offset}-${range.offset + range.length - 1}/${size}`;
|
|
103
|
+
return c.body(obj.body, 206, headers);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const obj = await bucket.get(key);
|
|
107
|
+
if (!obj) return c.json({ error: 'not found' }, 404);
|
|
108
|
+
headers['Content-Length'] = String(size);
|
|
109
|
+
return c.body(obj.body, 200, headers);
|
|
110
|
+
}
|
package/src/resource.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/** Default TTL for cached resources — one minute of warm navigations. */
|
|
2
|
+
export const RESOURCE_TTL_MS = 60_000;
|
|
3
|
+
|
|
4
|
+
export interface Resource<T> {
|
|
5
|
+
/** Cached value without loading; null when nothing valid was loaded. */
|
|
6
|
+
read(): T | null;
|
|
7
|
+
write(value: T): void;
|
|
8
|
+
subscribe(listener: () => void): () => void;
|
|
9
|
+
ensure(): Promise<T | null>;
|
|
10
|
+
refresh(): Promise<T | null>;
|
|
11
|
+
clear(): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ResourceConfig<T> {
|
|
15
|
+
/** Network (or other async) source of truth. */
|
|
16
|
+
load: () => Promise<T>;
|
|
17
|
+
/** localStorage persistence key, or null for memory-only. */
|
|
18
|
+
storageKey: string | null;
|
|
19
|
+
/** Validates stored JSON; a null return ignores the persisted value. */
|
|
20
|
+
decode?: (stored: unknown) => T | null;
|
|
21
|
+
ttlMs: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const memoryStore = new Map<string, string>();
|
|
25
|
+
|
|
26
|
+
function readStored(key: string): unknown {
|
|
27
|
+
let raw: string | null = null;
|
|
28
|
+
try {
|
|
29
|
+
raw = localStorage.getItem(key);
|
|
30
|
+
} catch {
|
|
31
|
+
raw = memoryStore.get(key) ?? null;
|
|
32
|
+
}
|
|
33
|
+
if (raw === null || raw.length === 0) return null;
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(raw);
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function writeStored(key: string, value: unknown): void {
|
|
42
|
+
const raw = JSON.stringify(value);
|
|
43
|
+
try {
|
|
44
|
+
localStorage.setItem(key, raw);
|
|
45
|
+
} catch {
|
|
46
|
+
memoryStore.set(key, raw);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function dropStored(key: string): void {
|
|
51
|
+
try {
|
|
52
|
+
localStorage.removeItem(key);
|
|
53
|
+
} catch {}
|
|
54
|
+
memoryStore.delete(key);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A TTL-cached async value: read() synchronously, ensure() (deduped,
|
|
59
|
+
* in-flight shared) or refresh() from the network, subscribe() for
|
|
60
|
+
* React re-renders, optional localStorage persistence behind decode().
|
|
61
|
+
* Loads swallow errors and keep the last good value — a failed refresh
|
|
62
|
+
* never blanks a warm cache.
|
|
63
|
+
*/
|
|
64
|
+
export function createResource<T>(config: ResourceConfig<T>): Resource<T> {
|
|
65
|
+
const stored = config.storageKey === null ? null : readStored(config.storageKey);
|
|
66
|
+
let value: T | null = stored === null || config.decode === undefined ? null : config.decode(stored);
|
|
67
|
+
let expiresAt = 0;
|
|
68
|
+
let inflight: Promise<T | null> | null = null;
|
|
69
|
+
const listeners = new Set<() => void>();
|
|
70
|
+
|
|
71
|
+
function notify(): void {
|
|
72
|
+
for (const listener of listeners) {
|
|
73
|
+
try {
|
|
74
|
+
listener();
|
|
75
|
+
} catch {}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function fetch(): Promise<T | null> {
|
|
80
|
+
const run = (async () => {
|
|
81
|
+
try {
|
|
82
|
+
const next = await config.load();
|
|
83
|
+
value = next;
|
|
84
|
+
expiresAt = Date.now() + config.ttlMs;
|
|
85
|
+
if (config.storageKey !== null) writeStored(config.storageKey, next);
|
|
86
|
+
notify();
|
|
87
|
+
return next;
|
|
88
|
+
} catch {
|
|
89
|
+
return value;
|
|
90
|
+
} finally {
|
|
91
|
+
inflight = null;
|
|
92
|
+
}
|
|
93
|
+
})();
|
|
94
|
+
inflight = run;
|
|
95
|
+
return run;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
read: () => value,
|
|
100
|
+
write: (next: T) => {
|
|
101
|
+
value = next;
|
|
102
|
+
expiresAt = Date.now() + config.ttlMs;
|
|
103
|
+
if (config.storageKey !== null) writeStored(config.storageKey, next);
|
|
104
|
+
notify();
|
|
105
|
+
},
|
|
106
|
+
subscribe: (listener: () => void) => {
|
|
107
|
+
listeners.add(listener);
|
|
108
|
+
return () => {
|
|
109
|
+
listeners.delete(listener);
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
ensure: () => {
|
|
113
|
+
if (inflight !== null) return inflight;
|
|
114
|
+
if (value !== null && Date.now() < expiresAt) return Promise.resolve(value);
|
|
115
|
+
return fetch();
|
|
116
|
+
},
|
|
117
|
+
refresh: () => {
|
|
118
|
+
if (inflight !== null) return inflight;
|
|
119
|
+
return fetch();
|
|
120
|
+
},
|
|
121
|
+
clear: () => {
|
|
122
|
+
value = null;
|
|
123
|
+
expiresAt = 0;
|
|
124
|
+
inflight = null;
|
|
125
|
+
if (config.storageKey !== null) dropStored(config.storageKey);
|
|
126
|
+
notify();
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|