Open History to see the last commit
1export interface KvEnv {
2 SCHEMA_CACHE: KVNamespace
3}
4
5/**
6 * Deterministic JSON stringify: object keys are sorted recursively so the
7 * same logical value always produces the same string (and content hash).
8 */
9export function stableStringify(value: unknown): string {
10 return JSON.stringify(sortValue(value))
11}
12
13function sortValue(value: unknown): unknown {
14 if (Array.isArray(value)) {
15 return value.map(sortValue)
16 }
17 if (value !== null && typeof value === 'object') {
18 const sorted: Record<string, unknown> = {}
19 for (const key of Object.keys(value).sort()) {
20 sorted[key] = sortValue((value as Record<string, unknown>)[key])
21 }
22 return sorted
23 }
24 return value
25}
26
27/** SHA-256 hex digest of a stable-stringified value. */
28export async function contentHash(value: unknown): Promise<string> {
29 const bytes = new TextEncoder().encode(stableStringify(value))
30 const digest = await crypto.subtle.digest('SHA-256', bytes)
31 return [...new Uint8Array(digest)]
32 .map((b) => b.toString(16).padStart(2, '0'))
33 .join('')
34}
35
36/** Key for an immutable schema blob, addressed by its content hash. */
37export function schemaKey(hash: string): string {
38 return `schema:${hash}`
39}
40
41export async function getJson<T>(
42 kv: KVNamespace,
43 key: string,
44): Promise<T | null> {
45 const raw = await kv.get(key, 'text')
46 if (raw === null) return null
47 return JSON.parse(raw) as T
48}
49
50export async function putJson(
51 kv: KVNamespace,
52 key: string,
53 value: unknown,
54 options?: { expirationTtl?: number },
55): Promise<void> {
56 await kv.put(key, stableStringify(value), options)
57}
58
59/**
60 * Store a JSON value under its content-hash key. Returns the hash so callers
61 * can persist it (e.g. in a D1 `schema_versions` row) for later lookup.
62 */
63export async function putByHash(
64 kv: KVNamespace,
65 value: unknown,
66): Promise<string> {
67 const hash = await contentHash(value)
68 await putJson(kv, schemaKey(hash), value)
69 return hash
70}
71
72export async function getByHash<T>(
73 kv: KVNamespace,
74 hash: string,
75): Promise<T | null> {
76 return getJson<T>(kv, schemaKey(hash))
77}