sanity-plugin-visual-editor 1.1.0 → 1.2.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/README.md +128 -2
- package/dist/cloudflare.d.ts +15 -4
- package/dist/cloudflare.js +97 -34
- package/dist/cloudflare.js.map +1 -1
- package/dist/{host-DreYJEmR.js → host-x2eXr-LJ.js} +9 -5
- package/dist/host-x2eXr-LJ.js.map +1 -0
- package/dist/host.d.ts +2 -0
- package/dist/host.js +1 -1
- package/dist/{index-4Zm_NjhC.d.ts → index-hDzatlg7.d.ts} +56 -1
- package/dist/next-client.d.ts +8 -1
- package/dist/next-client.js +41 -7
- package/dist/next-client.js.map +1 -1
- package/dist/next.d.ts +98 -1
- package/dist/next.js +63 -4
- package/dist/next.js.map +1 -1
- package/dist/server-B8MqMyaN.js +748 -0
- package/dist/server-B8MqMyaN.js.map +1 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.js +3 -495
- package/dist/sveltekit.d.ts +2 -2
- package/dist/sveltekit.js +2 -3
- package/dist/sveltekit.js.map +1 -1
- package/package.json +1 -1
- package/dist/host-DreYJEmR.js.map +0 -1
- package/dist/link-session-Dr4YkKFy.js +0 -52
- package/dist/link-session-Dr4YkKFy.js.map +0 -1
- package/dist/server.js.map +0 -1
package/dist/cloudflare.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare.js","names":["rewrite","isNode"],"sources":["../src/cloudflare/indexes.ts","../src/cloudflare/sanity-compat.ts","../src/cloudflare/mirror.ts","../src/cloudflare/sse.ts","../src/cloudflare/index.ts"],"sourcesContent":["import type {ExprNode} from 'groq-js'\n\ntype Node = {type: string; [field: string]: unknown}\n\n/** A precomputed document list that replaces `*` in one filter. */\nexport interface IndexSpec {\n /** Name of the hidden parameter holding the list. */\n param: string\n kind: 'type' | 'id'\n values: string[]\n}\n\n/**\n * Index emulation for `groq-js`, which scans every document for each `*[…]`. A filter over `*`\n * whose condition has a top-level conjunct `_id == \"…\"`, `_type == \"…\"` or `_type in [...]`\n * (params are already inlined at parse time) gets its `*` replaced by a hidden parameter that\n * holds just those documents. The full condition still runs on that list, so the result is the\n * same; only documents that could never match are skipped. Lists keep the dataset's order.\n */\nexport function useIndexes(tree: ExprNode): {tree: ExprNode; indexes: IndexSpec[]} {\n const indexes = new Map<string, IndexSpec>()\n const rewritten = rewrite(tree as unknown as Node, indexes)\n return {tree: rewritten as unknown as ExprNode, indexes: [...indexes.values()]}\n}\n\nfunction rewrite(node: Node, indexes: Map<string, IndexSpec>): Node {\n const copy: Node = {...node}\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value)) {\n copy[key] = value.map((item) => (isNode(item) ? rewrite(item, indexes) : item))\n } else if (isNode(value)) {\n copy[key] = rewrite(value, indexes)\n }\n }\n if (copy.type !== 'Filter' || (copy.base as Node).type !== 'Everything') return copy\n\n const spec = indexFor(conjuncts(copy.expr as Node))\n if (!spec) return copy\n const param = `__index_${spec.kind}_${spec.values.join('|')}`\n indexes.set(param, {param, ...spec})\n return {...copy, base: {type: 'Parameter', name: param}}\n}\n\n/** Top-level `&&` operands, through groups. */\nfunction conjuncts(node: Node): Node[] {\n if (node.type === 'And')\n return [...conjuncts(node.left as Node), ...conjuncts(node.right as Node)]\n if (node.type === 'Group') return conjuncts(node.base as Node)\n return [node]\n}\n\nfunction indexFor(nodes: Node[]): Omit<IndexSpec, 'param'> | null {\n let byType: Omit<IndexSpec, 'param'> | null = null\n for (const node of nodes) {\n if (node.type !== 'OpCall') continue\n const field = attributeName(node.left as Node)\n if (node.op === '==' && field === '_id') {\n const value = stringValue(node.right as Node)\n if (value !== null) return {kind: 'id', values: [value]}\n }\n if (field !== '_type' || byType) continue\n if (node.op === '==') {\n const value = stringValue(node.right as Node)\n if (value !== null) byType = {kind: 'type', values: [value]}\n } else if (node.op === 'in') {\n const values = stringArray(node.right as Node)\n if (values) byType = {kind: 'type', values}\n }\n }\n return byType\n}\n\n/** The name of an implicit attribute access (`_type`, not `foo._type`). */\nfunction attributeName(node: Node): string | null {\n return node.type === 'AccessAttribute' && node.base === undefined ? (node.name as string) : null\n}\n\nfunction stringValue(node: Node): string | null {\n return node.type === 'Value' && typeof node.value === 'string' ? node.value : null\n}\n\nfunction stringArray(node: Node): string[] | null {\n if (node.type !== 'Array') return null\n const values: string[] = []\n for (const element of node.elements as Node[]) {\n if (element.isSplat) return null\n const value = stringValue(element.value as Node)\n if (value === null) return null\n values.push(value)\n }\n return values\n}\n\nfunction isNode(value: unknown): value is Node {\n return !!value && typeof value === 'object' && typeof (value as Node).type === 'string'\n}\n","import type {ExprNode} from 'groq-js'\n\ntype Node = {type: string; [field: string]: unknown}\n\n/** Node fields that open a new `@` scope: implicit attribute access inside them is not ours. */\nconst SCOPED = new Set(['Projection', 'Filter', 'Map', 'FlatMap'])\n\n/**\n * Make `groq-js` match a Sanity query-engine behaviour (observed 2026-11-23): Sanity fetches\n * only the sub-fields a projection names, so when none of them exist the parent object counts as\n * missing and `seo{title, description, image}` returns `null`, even though `seo` is an object\n * (here `{url: …}`). `groq-js` returns `{title: null, …}`.\n *\n * Each projection over a non-document base becomes\n * `select(count(base) != null || defined(base._id) || defined(base.f1) || … => base, null){…}`,\n * where `f1…` are the fields the projection reads from `@`. Arrays and documents pass through\n * unchanged; projections over document sets (`*[…]`) are left alone. The hub's verification gate\n * still compares every query with Sanity before trusting it.\n */\nexport function emulateSanityPruning(tree: ExprNode): ExprNode {\n return rewrite(tree as unknown as Node) as unknown as ExprNode\n}\n\nfunction rewrite(node: Node): Node {\n const copy: Node = {...node}\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value)) copy[key] = value.map((item) => (isNode(item) ? rewrite(item) : item))\n else if (isNode(value)) copy[key] = rewrite(value)\n }\n if (copy.type !== 'Projection') return copy\n\n const base = copy.base as Node\n const expr = copy.expr as Node\n if (expr.type !== 'Object' || containsEverything(base)) return copy\n const attributes = expr.attributes as Node[]\n if (attributes.some((attribute) => attribute.type !== 'ObjectAttributeValue')) return copy\n\n const fields = new Set<string>()\n let usesThis = false\n for (const attribute of attributes) {\n usesThis = collectFields(attribute.value as Node, fields) || usesThis\n }\n // A projection that reads `@` itself (`@->title`, `defined(@->)`) makes Sanity fetch the\n // whole object, so nothing is pruned.\n if (usesThis || !fields.size) return copy\n\n const conditions: Node[] = [\n {\n type: 'OpCall',\n op: '!=',\n left: {type: 'FuncCall', namespace: 'global', name: 'count', args: [base]},\n right: {type: 'Value', value: null},\n },\n ...['_id', ...fields].map((name) => ({\n type: 'FuncCall',\n namespace: 'global',\n name: 'defined',\n args: [{type: 'AccessAttribute', base, name}],\n })),\n ]\n const condition = conditions.reduce((left, right) => ({type: 'Or', left, right}))\n\n return {\n ...copy,\n base: {\n type: 'Select',\n alternatives: [{type: 'SelectAlternative', condition, value: base}],\n fallback: {type: 'Value', value: null},\n },\n }\n}\n\n/**\n * Root fields read from `@` (implicit attribute access), not descending into new scopes.\n * Returns whether `@` itself is read.\n */\nfunction collectFields(node: Node, fields: Set<string>): boolean {\n if (node.type === 'AccessAttribute' && node.base === undefined) {\n fields.add(node.name as string)\n return false\n }\n if (node.type === 'This') return true\n let usesThis = false\n for (const [key, value] of Object.entries(node)) {\n // The scoped part of a projection/filter/map is evaluated against a different `@`.\n if (SCOPED.has(node.type) && key === 'expr') continue\n if (Array.isArray(value)) {\n for (const item of value) if (isNode(item)) usesThis = collectFields(item, fields) || usesThis\n } else if (isNode(value)) {\n usesThis = collectFields(value, fields) || usesThis\n }\n }\n return usesThis\n}\n\nfunction containsEverything(node: Node): boolean {\n if (node.type === 'Everything') return true\n return Object.values(node).some((value) =>\n Array.isArray(value)\n ? value.some((item) => isNode(item) && containsEverything(item))\n : isNode(value) && containsEverything(value),\n )\n}\n\nfunction isNode(value: unknown): value is Node {\n return !!value && typeof value === 'object' && typeof (value as Node).type === 'string'\n}\n","import {evaluate, parse, type ExprNode} from 'groq-js'\nimport {useIndexes, type IndexSpec} from './indexes'\nimport {emulateSanityPruning} from './sanity-compat'\n\ntype Doc = {_id: string; _type?: string; [field: string]: unknown}\ntype QueryParams = Record<string, unknown>\n\n/** A perspective's documents, kept current one document at a time. */\ninterface View {\n stack: {releases: string[]; withDrafts: boolean}\n /** Base ID → the document the perspective sees, with `_id` set to the base ID. */\n byId: Map<string, Doc>\n /** Rebuilt from `byId` on demand after a change (references only, no copies). */\n docs: Doc[] | null\n byType: Map<string, Doc[]> | null\n}\n\n/**\n * Shopify-synced types make up ~21 of the dataset's ~22 MB (2026-11-23: 17,235 variants, 2,701\n * products). The mirror holds every other document, and only the products that held results\n * reference.\n */\nconst ON_DEMAND_TYPES = ['product', 'productVariant']\nconst BASE_QUERY = `*[!(_type in ${JSON.stringify(ON_DEMAND_TYPES)}) && !(_id in path(\"_.**\"))]`\n/** `/listen` filter: everything the mirror can hold. Variants never feed preview queries. */\nexport const LISTEN_QUERY = '*[_type != \"productVariant\" && !(_id in path(\"_.**\"))]'\n\n/** Strip the `drafts.` or `versions.<release>.` prefix so every variant maps to one ID. */\nexport function baseId(id: string): string {\n return id.replace(/^drafts\\./, '').replace(/^versions\\.[^.]+\\./, '')\n}\n\n/**\n * A local copy of the documents preview queries read (raw: published, `drafts.` and\n * `versions.` IDs), kept current from `/listen` mutation results. It evaluates GROQ with\n * `groq-js` against a perspective view built here, since `groq-js` has no perspectives.\n *\n * Production CPU is much slower than a laptop (2026-11-23: rebuilding the view took 0.2–0.55 s and\n * a page query with a product scan ~3 s), so views update one document at a time, and scans\n * filtered by `_type` or `_id` read precomputed lists instead of every document (`indexes.ts`).\n */\nexport class Mirror {\n #docs = new Map<string, Doc>()\n /** Base ID → release name → version document. */\n #versions = new Map<string, Map<string, Doc>>()\n /** Base IDs of on-demand (product) documents the mirror tracks. */\n #tracked = new Set<string>()\n /** Base IDs known not to exist, so they are not fetched again for every evaluation. */\n #missing = new Set<string>()\n /**\n * Unsaved Studio edits (LF-INIT-21), keyed by draft or version ID. They sit above the saved\n * document until the saved content catches up, or until they go stale.\n */\n #overlays = new Map<string, {doc: Doc; seq: number; at: number}>()\n #trees = new Map<string, {tree: ExprNode; indexes: IndexSpec[]}>()\n #views = new Map<string, View>()\n #ready: Promise<void> | null = null\n #fetchRaw: (query: string, params?: QueryParams) => Promise<unknown>\n #loaded = false\n\n constructor(fetchRaw: (query: string, params?: QueryParams) => Promise<unknown>) {\n this.#fetchRaw = fetchRaw\n }\n\n get loaded(): boolean {\n return this.#loaded\n }\n\n /** Load every non-product document once. Concurrent callers share one load. */\n ready(): Promise<void> {\n this.#ready ??= (async () => {\n const docs = (await this.#fetchRaw(BASE_QUERY)) as Doc[]\n for (const doc of docs) this.#put(doc)\n this.#views.clear()\n this.#loaded = true\n })().catch((error) => {\n this.#ready = null\n throw error\n })\n return this.#ready\n }\n\n clear() {\n this.#overlays.clear()\n this.#docs.clear()\n this.#versions.clear()\n this.#tracked.clear()\n this.#missing.clear()\n this.#views.clear()\n this.#ready = null\n this.#loaded = false\n }\n\n /** Fetch the published and draft variants of any base IDs the mirror lacks. */\n async ensure(ids: string[]): Promise<void> {\n const wanted = ids.filter((id) => !this.#knows(id))\n if (!wanted.length) return\n const docs = (await this.#fetchRaw('*[_id in $ids]', {\n ids: wanted.flatMap((id) => [id, `drafts.${id}`]),\n })) as Doc[]\n const found = new Set<string>()\n for (const doc of docs) {\n const base = baseId(doc._id)\n found.add(base)\n this.#put(doc)\n if (doc._type && ON_DEMAND_TYPES.includes(doc._type)) this.#tracked.add(base)\n }\n for (const id of wanted) if (!found.has(id)) this.#missing.add(id)\n for (const base of found) this.#refresh(base)\n }\n\n /**\n * Apply one `/listen` mutation (`includeResult=true`). Returns whether the mirror changed.\n * Products the mirror does not track are ignored.\n */\n apply(documentId: string, result: Doc | undefined, transition: string): boolean {\n const base = baseId(documentId)\n if (transition === 'disappear' || !result) {\n if (!this.#remove(documentId)) return false\n } else {\n const onDemand = result._type && ON_DEMAND_TYPES.includes(result._type)\n if (onDemand && !this.#tracked.has(base)) return false\n this.#put(result)\n this.#missing.delete(base)\n }\n // The saved document has caught up with (or replaced) the unsaved edits.\n const overlay = this.#overlays.get(documentId)\n if (overlay && (!result || transition === 'disappear' || sameContent(overlay.doc, result))) {\n this.#overlays.delete(documentId)\n }\n this.#refresh(base)\n return true\n }\n\n /**\n * Show an unsaved Studio edit in place of the saved draft or version. `seq` orders updates\n * from one editor; an older one is ignored. Returns whether the mirror changed.\n */\n overlay(doc: Doc, seq: number, now = Date.now()): boolean {\n if (!/^(drafts|versions)\\./.test(doc._id)) return false\n const base = baseId(doc._id)\n const onDemand = doc._type && ON_DEMAND_TYPES.includes(doc._type)\n if (onDemand && !this.#tracked.has(base)) return false\n const current = this.#overlays.get(doc._id)\n if (current && current.seq >= seq) return false\n this.#overlays.set(doc._id, {doc, seq, at: now})\n this.#refresh(base)\n return true\n }\n\n /** Drop overlays with no update for `ttl` ms. Returns the base IDs that changed. */\n expireOverlays(ttl: number, now = Date.now()): string[] {\n const expired: string[] = []\n for (const [id, overlay] of this.#overlays) {\n if (now - overlay.at < ttl) continue\n this.#overlays.delete(id)\n const base = baseId(id)\n this.#refresh(base)\n expired.push(base)\n }\n return expired\n }\n\n get overlayCount(): number {\n return this.#overlays.size\n }\n\n /** Whether any of these base IDs currently show unsaved edits. */\n overlaid(ids: string[]): boolean {\n if (!this.#overlays.size) return false\n const bases = new Set([...this.#overlays.keys()].map(baseId))\n return ids.some((id) => bases.has(id))\n }\n\n /** Base IDs referenced (`_ref`) by any variant of the given documents. */\n referencesOf(ids: string[]): string[] {\n const found = new Set<string>()\n const walk = (value: unknown) => {\n if (Array.isArray(value)) value.forEach(walk)\n else if (value && typeof value === 'object') {\n for (const [field, child] of Object.entries(value)) {\n if (field === '_ref' && typeof child === 'string') found.add(baseId(child))\n else walk(child)\n }\n }\n }\n for (const id of ids) {\n for (const doc of this.#variants(id)) walk(doc)\n }\n return [...found]\n }\n\n /** Debug: rebuild one perspective view from scratch. */\n benchView(perspective: string) {\n this.#views.delete(perspective)\n this.#lists(this.#view(perspective))\n }\n\n /** Whether every ID is in the mirror (or known not to exist). */\n covers(ids: string[]): boolean {\n return ids.every((id) => this.#knows(id))\n }\n\n /**\n * Evaluate a GROQ query against the given perspective. `->` looks documents up by ID and\n * fetches any the mirror does not hold yet (products), so references resolve as on Sanity.\n */\n async evaluate(query: string, params: QueryParams, perspective: string): Promise<unknown> {\n const {tree, indexes} = this.#parse(query, params)\n const view = this.#view(perspective)\n const lists = this.#lists(view)\n const indexParams: QueryParams = {}\n for (const index of indexes) {\n if (index.kind === 'id') {\n const doc = view.byId.get(index.values[0])\n indexParams[index.param] = doc ? [doc] : []\n } else if (index.values.length === 1) {\n indexParams[index.param] = lists.byType.get(index.values[0]) ?? []\n } else {\n // Several types: keep the dataset's order, as a full scan would.\n const types = new Set(index.values)\n indexParams[index.param] = lists.docs.filter((doc) => types.has(doc._type ?? ''))\n }\n }\n const value = await evaluate(tree, {\n dataset: lists.docs,\n params: {...params, ...indexParams},\n dereference: async ({_ref}) => {\n const id = baseId(_ref)\n const known = view.byId.get(id)\n if (known || this.#missing.has(id)) return known ?? null\n await this.ensure([id])\n return view.byId.get(id) ?? null\n },\n })\n return value.get()\n }\n\n #parse(query: string, params: QueryParams) {\n const key = JSON.stringify([query, params])\n let parsed = this.#trees.get(key)\n if (!parsed) {\n parsed = useIndexes(emulateSanityPruning(parse(query, {params})))\n if (this.#trees.size > 1_000) this.#trees.clear()\n this.#trees.set(key, parsed)\n }\n return parsed\n }\n\n #knows(id: string): boolean {\n return this.#missing.has(id) || this.#docs.has(id) || this.#docs.has(`drafts.${id}`)\n }\n\n #put(doc: Doc) {\n this.#docs.set(doc._id, doc)\n if (doc._id.startsWith('versions.')) {\n const base = baseId(doc._id)\n let versions = this.#versions.get(base)\n if (!versions) this.#versions.set(base, (versions = new Map()))\n versions.set(doc._id.split('.')[1], doc)\n }\n }\n\n #remove(id: string): boolean {\n if (!this.#docs.delete(id)) return false\n if (id.startsWith('versions.')) this.#versions.get(baseId(id))?.delete(id.split('.')[1])\n return true\n }\n\n #variants(base: string): Doc[] {\n const docs: Doc[] = []\n const published = this.#docs.get(base)\n const draft = this.#overlays.get(`drafts.${base}`)?.doc ?? this.#docs.get(`drafts.${base}`)\n if (published) docs.push(published)\n if (draft) docs.push(draft)\n for (const version of this.#versions.get(base)?.values() ?? []) docs.push(version)\n for (const [id, overlay] of this.#overlays) {\n if (id.startsWith('versions.') && baseId(id) === base) docs.push(overlay.doc)\n }\n return docs\n }\n\n /** The document a perspective sees for one base ID, or `undefined`. */\n #choose(base: string, stack: View['stack']): Doc | undefined {\n let chosen: Doc | undefined\n const versions = this.#versions.get(base)\n for (const release of stack.releases) {\n chosen ??= this.#overlays.get(`versions.${release}.${base}`)?.doc ?? versions?.get(release)\n }\n if (stack.withDrafts) {\n chosen ??= this.#overlays.get(`drafts.${base}`)?.doc ?? this.#docs.get(`drafts.${base}`)\n }\n chosen ??= this.#docs.get(base)\n return chosen && {...chosen, _id: base, _originalId: chosen._id}\n }\n\n /** Re-choose one base ID in every built view. */\n #refresh(base: string) {\n for (const view of this.#views.values()) {\n const doc = this.#choose(base, view.stack)\n if (doc) view.byId.set(base, doc)\n else view.byId.delete(base)\n view.docs = null\n view.byType = null\n }\n }\n\n /**\n * The documents as a perspective sees them: per base ID, the first of the release versions\n * (in stack order), the draft (if `drafts` is in the stack) and the published document, with\n * `_id` set to the base ID and `_originalId` to the document chosen.\n */\n #view(perspective: string): View {\n const cached = this.#views.get(perspective)\n if (cached) return cached\n\n const names = perspective.split(',')\n const stack = {\n releases: names.filter((name) => name !== 'drafts' && name !== 'published'),\n withDrafts: names.includes('drafts'),\n }\n const view: View = {stack, byId: new Map(), docs: null, byType: null}\n const seen = new Set<string>()\n for (const id of this.#docs.keys()) {\n const base = baseId(id)\n if (seen.has(base)) continue\n seen.add(base)\n const doc = this.#choose(base, stack)\n if (doc) view.byId.set(base, doc)\n }\n this.#views.set(perspective, view)\n return view\n }\n\n #lists(view: View): {docs: Doc[]; byType: Map<string, Doc[]>} {\n if (!view.docs || !view.byType) {\n view.docs = [...view.byId.values()]\n view.byType = new Map()\n for (const doc of view.docs) {\n const type = doc._type ?? ''\n let list = view.byType.get(type)\n if (!list) view.byType.set(type, (list = []))\n list.push(doc)\n }\n }\n return {docs: view.docs, byType: view.byType}\n }\n}\n\n/** System fields that differ between the Studio's form value and the saved document. */\nconst SYSTEM_FIELDS = new Set(['_rev', '_updatedAt', '_createdAt', '_system', '_originalId'])\n\n/** Whether two documents hold the same content, ignoring system fields and key order. */\nfunction sameContent(a: Doc, b: Doc): boolean {\n const canonical = (doc: Doc) =>\n JSON.stringify(\n Object.fromEntries(Object.entries(doc).filter(([key]) => !SYSTEM_FIELDS.has(key))),\n (_key, value: unknown) =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? Object.fromEntries(\n Object.entries(value).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0)),\n )\n : value,\n )\n return canonical(a) === canonical(b)\n}\n","export interface SseEvent {\n id?: string\n event: string\n data: string\n}\n\n/** Parse a `text/event-stream` body into events. Comments and `retry:` lines are skipped. */\nexport async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> {\n const reader = body\n .pipeThrough(new TextDecoderStream() as unknown as ReadableWritablePair<string, Uint8Array>)\n .getReader()\n let buffer = ''\n\n try {\n while (true) {\n const {done, value} = await reader.read()\n if (done) return\n buffer += value.replace(/\\r\\n?/g, '\\n')\n\n let boundary: number\n while ((boundary = buffer.indexOf('\\n\\n')) !== -1) {\n const block = buffer.slice(0, boundary)\n buffer = buffer.slice(boundary + 2)\n const event = parseBlock(block)\n if (event) yield event\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\nfunction parseBlock(block: string): SseEvent | null {\n let id: string | undefined\n let event = 'message'\n const data: string[] = []\n\n for (const line of block.split('\\n')) {\n if (!line || line.startsWith(':')) continue\n const colon = line.indexOf(':')\n const field = colon === -1 ? line : line.slice(0, colon)\n const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '')\n if (field === 'id') id = value\n else if (field === 'event') event = value\n else if (field === 'data') data.push(value)\n }\n\n if (!data.length && !id && event === 'message') return null\n return {id, event, data: data.join('\\n')}\n}\n","import {DurableObject} from 'cloudflare:workers'\nimport {LISTEN_QUERY, Mirror, baseId} from './mirror'\nimport {parseSse, type SseEvent} from './sse'\n\n/**\n * Realtime preview hub (LF-INIT-20). One instance per preview perspective, addressed by name\n * (`drafts`, or a release stack such as `rABC,drafts`).\n *\n * - Reads: the storefront calls `POST /query` instead of Sanity. Results are held in memory with\n * their sync tags, so editors on the same page share one Sanity fetch.\n * - Fast path: a local mirror of the documents (`mirror.ts`) follows `/listen` with\n * `includeResult`, ~50 ms after each write, and re-evaluates held queries with `groq-js`.\n * A query uses this path only after its local result matched Sanity's exactly.\n * Refetching instead would not help: Sanity's query API returns a change only ~1 s after the\n * write, whatever the request (tested 2026-11-23).\n * - Authority: one Live Content API stream (`includeDrafts`) reports changed sync tags ~1 s after\n * each write. Matching results are refetched from Sanity, which corrects any local result.\n * (The `invalidate-tags` Sanity Function never fires for draft edits, tested 2026-11-23.)\n * - Downstream: when a result's hash changes, its key is appended to an in-memory log and sent at\n * once to every tab's WebSocket (`/socket`); tabs that cannot open one long-poll (`/events`).\n * A tab resumes from its cursor. Nothing here touches Durable Object storage: on Workers, the\n * output gate holds a Durable Object's outgoing messages until its storage writes are\n * confirmed, and with a durable log (`agents/streams`) every update reached the tab ~3 s late\n * (2026-11-23).\n */\n\ntype QueryParams = Record<string, unknown>\n\n/** Set by the storefront on a WebSocket from an editor with a live-edit session. */\nconst LIVE_EDIT_HEADER = 'x-live-edit'\n\n/** Whether a query's local evaluation is trusted: `ok` after it reproduced Sanity's result. */\ntype LocalState = 'unknown' | 'ok' | 'off'\n\ninterface Entry {\n query: string\n params: QueryParams\n result: unknown\n hash: string\n tags: string[]\n /** Base IDs of every `_id`/`_ref` in the result and every string in the params. */\n docs: string[]\n local: LocalState\n usedAt: number\n}\n\ninterface QueryResponse {\n result: unknown\n syncTags?: string[]\n}\n\n/** What a tab receives: events after its cursor, and the new cursor. */\ninterface EventsMessage {\n cursor: string\n events: PreviewInvalidation[]\n /** The tab's cursor is unknown here: refresh everything. */\n reset?: boolean\n}\n\n/** Payload of each invalidation event sent to tabs. */\nexport interface PreviewInvalidation {\n keys: string[]\n at: number\n /** Which path found the change: local evaluation, the delayed re-evaluation or a refetch. */\n source: 'local' | 'rest' | 'sweep'\n /**\n * The changed results, by key, so a tab can show them without asking again. Only on WebSocket\n * messages (the log keeps keys alone), and only for results under {@link MAX_PUSH_BYTES}.\n */\n results?: Record<string, unknown>\n /** The storefront remote queries that read each changed key (WebSocket messages only). */\n labels?: Record<string, string[]>\n}\n\nconst MAX_ENTRIES = 500\n/** Stop the upstream streams and drop the caches after this long with no reads and no tabs. */\n// Long enough that an editor who pauses comes back to a warm hub; an idle instance costs little.\nconst IDLE_MS = 30 * 60_000\n/**\n * An unsaved edit with no update for this long is dropped. The Studio saves within ~1 s of the\n * last keystroke, so by then the saved draft has normally replaced it.\n */\nconst OVERLAY_TTL_MS = 5_000\n/** Verification waits for reads to pause this long, so it never competes with a page load. */\nconst VERIFY_DELAY_MS = 750\nconst IDLE_CHECK_MS = 60_000\n/** Events kept in memory for tabs whose next poll comes after a burst of changes. */\nconst LOG_SIZE = 200\n/** A poll with nothing to report answers after this long; the tab polls again at once. */\nconst POLL_TIMEOUT_MS = 25_000\n/** Coalesce events that arrive together (a Studio save often touches several documents). */\nconst FLUSH_DELAY_MS = 25\nconst LOCAL_DELAY_MS = 10\n/** Quiet period after the last edit before re-evaluating queries that do not name it. */\nconst REST_DELAY_MS = 400\nconst RECENT_EVENTS = 50\n/** Larger results are announced by key alone; the tab refetches them. */\nconst MAX_PUSH_BYTES = 256_000\n/** Remote query labels kept per held query, and the longest accepted. */\nconst MAX_LABELS_PER_QUERY = 32\nconst MAX_LABEL_LENGTH = 2_000\n/** An unsaved document larger than this is ignored; the saved draft still reaches the hub. */\nconst MAX_OVERLAY_BYTES = 1_000_000\n\n/** Required Cloudflare Worker bindings for the preview hub worker. */\nexport interface PreviewHubEnv {\n CF_VERSION_METADATA: {id: string}\n SANITY_PROJECT_ID: string\n SANITY_DATASET: string\n SANITY_API_VERSION: string\n SANITY_API_READ_TOKEN: string\n PREVIEW_HUB: {\n getByName(name: string): {fetch(request: Request): Promise<Response>}\n }\n}\n\nexport class PreviewHub extends DurableObject<PreviewHubEnv> {\n #entries = new Map<string, Entry>()\n #byTag = new Map<string, Set<string>>()\n #inflight = new Map<string, Promise<unknown>>()\n #recentEvents: {at: number; tags: string[]}[] = []\n #mirror = new Mirror((query, params) => this.#fetchRaw(query, params))\n #lastMutationAt = 0\n #lastVerifyNote = ''\n /** Upstream stream health, for diagnostics. */\n #streamStatus: Record<string, {connects: number; events: number; error: string}> = {}\n /** Base IDs mutated since the last local flush. */\n #editedDocs = new Set<string>()\n\n #upstream: AbortController | null = null\n #lastEventId: string | null = null\n #idleTimer: ReturnType<typeof setInterval> | null = null\n #lastActive = Date.now()\n\n #pendingTags = new Set<string>()\n #flushTimer: ReturnType<typeof setTimeout> | null = null\n #localTimer: ReturnType<typeof setTimeout> | null = null\n /** Independent task chains, so local updates never wait behind Sanity fetches. */\n #chains: Record<'local' | 'sweep' | 'verify', Promise<void>> = {\n local: Promise.resolve(),\n sweep: Promise.resolve(),\n verify: Promise.resolve(),\n }\n\n /** Long polls waiting right now. */\n #polling = 0\n /** Wakes the waiting long polls when the log grows. */\n #waiters = new Set<() => void>()\n /** Tabs following this hub over a WebSocket. */\n #sockets = new Set<WebSocket>()\n /** The storefront remote queries (labels) that read each held query, by key. */\n #labels = new Map<string, Set<string>>()\n\n #label(key: string, label: string) {\n let labels = this.#labels.get(key)\n if (!labels) this.#labels.set(key, (labels = new Set()))\n if (labels.size < MAX_LABELS_PER_QUERY) labels.add(label)\n }\n /** Changes on every instance start, so a `Last-Event-ID` from before a restart is recognised. */\n #epoch = crypto.randomUUID().slice(0, 8)\n #seq = 0\n #log: {seq: number; chunk: PreviewInvalidation}[] = []\n\n /** The instance name is `<perspective>|<deployed version id>`; see the default export. */\n get #perspective(): string {\n return (this.ctx.id.name ?? 'drafts').split('|')[0]\n }\n\n /** Run a GROQ query in this hub's perspective, from memory when the hub already holds it. */\n async query<T = unknown>(query: string, params: QueryParams = {}, label?: string): Promise<T> {\n this.#touch()\n this.#ensureUpstream()\n // Start loading the mirror on the first read, overlapping the network wait with the page.\n if (!this.#mirror.loaded) void this.#mirror.ready().catch(() => {})\n // Reads push verification back until the page load is over.\n if (this.#verifyPending.size) this.#scheduleVerify()\n\n const key = await fingerprint(query, params)\n if (label) this.#label(key, label)\n const entry = this.#entries.get(key)\n if (entry) {\n entry.usedAt = Date.now()\n return entry.result as T\n }\n\n let pending = this.#inflight.get(key)\n if (!pending) {\n pending = this.#load(key, query, params).finally(() => this.#inflight.delete(key))\n this.#inflight.set(key, pending)\n }\n return (await pending) as T\n }\n\n /**\n * - `POST /query` `{ query, params, label? }` → `{ result }`. `label` names the storefront's\n * remote query reading it; events for the query carry it back. The storefront uses this rather than the\n * `query()` RPC method because Vite dev's platform proxy cannot carry Durable Object RPC.\n * - `GET /socket` (WebSocket upgrade) → invalidation events, pushed as they happen.\n * - `GET /events` → the same events by long poll, for tabs without a WebSocket.\n * - `GET /stats` → entry counts by local state and timings, for debugging.\n */\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url)\n if (url.pathname === '/query' && request.method === 'POST') {\n const {query, params, label} = (await request.json()) as {\n query: string\n params?: QueryParams\n label?: unknown\n }\n const name = typeof label === 'string' && label.length <= MAX_LABEL_LENGTH ? label : undefined\n return Response.json({result: await this.query(query, params ?? {}, name)})\n }\n if (url.pathname === '/stats') {\n const local: Record<LocalState, number> = {unknown: 0, ok: 0, off: 0}\n for (const entry of this.#entries.values()) local[entry.local]++\n return Response.json({\n entries: this.#entries.size,\n local,\n polling: this.#polling,\n sockets: this.#sockets.size,\n mirror: this.#mirror.loaded,\n lastLocalFlush: this.#lastLocalFlush,\n upstream: this.#streamStatus,\n lastVerifyNote: this.#lastVerifyNote,\n })\n }\n if (url.pathname === '/socket') return this.#socket(request)\n if (url.pathname === '/events') return this.#poll(request)\n if (url.pathname === '/overlay' && request.method === 'POST') {\n const {document, seq} = (await request.json()) as {\n document: {_id: string; _type?: string}\n seq: number\n }\n return Response.json({applied: await this.#applyOverlay(document, seq)})\n }\n if (url.pathname === '/bench') {\n // Debug: evaluate one held query locally (or rebuild the perspective view) and answer.\n // The caller times the request; Workers freezes the clock during computation.\n const key = url.searchParams.get('key')\n if (url.searchParams.has('view')) {\n await this.#mirror.ready()\n this.#mirror.benchView(this.#perspective)\n return Response.json({view: true})\n }\n const entry = key ? this.#entries.get(key) : undefined\n if (!entry) {\n return Response.json({\n keys: [...this.#entries].map(([k, e]) => ({\n key: k,\n local: e.local,\n query: e.query.length,\n })),\n })\n }\n const result = await this.#evaluateLocal(entry)\n return Response.json({key, bytes: JSON.stringify(result)?.length ?? 0})\n }\n return new Response('Not found', {status: 404})\n }\n\n /**\n * What a tab at cursor `after` has missed: `{ cursor, events }`, `reset` when the cursor is from\n * another instance (the hub restarted or was redeployed) or older than the log (refresh\n * everything), or `null` when it is up to date. Without a cursor, the current one, so a new tab\n * starts from now.\n */\n #since(after: string | null): EventsMessage | null {\n const current = `${this.#epoch}:${this.#seq}`\n if (!after) return {cursor: current, events: []}\n const [epoch, raw] = after.split(':')\n const seq = Number(raw)\n const oldest = this.#log[0]?.seq ?? this.#seq + 1\n if (epoch !== this.#epoch || !Number.isInteger(seq) || (seq < this.#seq && seq + 1 < oldest)) {\n return {cursor: current, events: [], reset: true}\n }\n const events = this.#log.filter((event) => event.seq > seq)\n if (!events.length) return null\n return {\n cursor: `${this.#epoch}:${events[events.length - 1].seq}`,\n events: events.map((e) => e.chunk),\n }\n }\n\n /**\n * WebSocket: `GET /socket?after=<cursor>` sends what the tab missed (or its starting cursor),\n * then each event as {@link #publish} logs it, with no request to wait for. The tab sends\n * `ping` every 20 s to keep the connection open through proxies; the hub answers `pong`.\n *\n * Plain `accept()` rather than hibernation: a hub with open sockets stays in memory with its\n * caches and upstream streams, as it does for waiting long polls.\n */\n #socket(request: Request): Response {\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected a WebSocket', {status: 426})\n }\n this.#touch()\n const {0: client, 1: server} = new WebSocketPair()\n ;(server as WebSocket & {accept(): void}).accept()\n // The storefront sets this only after checking the editor's live-edit session; this Worker\n // has no public URL, so a browser cannot send it.\n const edits = request.headers.get(LIVE_EDIT_HEADER) === '1'\n if (!edits) this.#sockets.add(server)\n const close = () => {\n this.#sockets.delete(server)\n this.#touch()\n }\n server.addEventListener('close', close)\n server.addEventListener('error', close)\n server.addEventListener('message', (event) => {\n if (event.data === 'ping') {\n server.send('pong')\n return\n }\n if (edits && typeof event.data === 'string') void this.#receiveEdit(event.data)\n })\n if (!edits) {\n const missed = this.#since(new URL(request.url).searchParams.get('after'))\n server.send(JSON.stringify(missed ?? {cursor: `${this.#epoch}:${this.#seq}`, events: []}))\n }\n return new Response(null, {status: 101, webSocket: client} as ResponseInit)\n }\n\n /** An unsaved Studio edit sent over a live-edit socket: `{ document, seq }`, a draft. */\n async #receiveEdit(data: string) {\n if (data.length > MAX_OVERLAY_BYTES || this.#perspective !== 'drafts') return\n try {\n const {document, seq} = JSON.parse(data) as {\n document?: {_id?: unknown; _type?: string}\n seq?: unknown\n }\n if (\n typeof document?._id !== 'string' ||\n !document._id.startsWith('drafts.') ||\n typeof seq !== 'number'\n ) {\n return\n }\n await this.#applyOverlay(document as {_id: string; _type?: string}, seq)\n } catch (error) {\n console.warn('[preview-hub] live edit failed', error)\n }\n }\n\n /**\n * Long poll: `GET /events?after=<cursor>` answers as soon as the log has events after the\n * cursor (see {@link #since}), or with none after {@link POLL_TIMEOUT_MS}.\n *\n * The request stays inside this handler until {@link #publish} wakes it. A streaming response\n * does not work here: once a handler has returned its `Response`, Workers did not run its\n * timers or flush its writes promptly, and SSE events reached tabs 0.7–4 s late (2026-11-23).\n */\n async #poll(request: Request): Promise<Response> {\n this.#touch()\n const after = new URL(request.url).searchParams.get('after')\n const json = (body: unknown) =>\n Response.json(body, {headers: {'cache-control': 'no-store, no-transform'}})\n\n this.#polling++\n try {\n const deadline = Date.now() + POLL_TIMEOUT_MS\n while (!request.signal?.aborted) {\n const message = this.#since(after)\n if (message) return json(message)\n const left = deadline - Date.now()\n if (left <= 0) break\n await new Promise<void>((resolve) => {\n const wake = () => {\n clearTimeout(timer)\n this.#waiters.delete(wake)\n resolve()\n }\n const timer = setTimeout(wake, left)\n this.#waiters.add(wake)\n request.signal?.addEventListener('abort', wake, {once: true})\n })\n }\n return json({cursor: after, events: []})\n } finally {\n this.#polling--\n this.#touch()\n }\n }\n\n async #load(key: string, query: string, params: QueryParams): Promise<unknown> {\n const startedAt = Date.now()\n let response = await this.#fetchSanity(query, params)\n\n // A Live event that arrived while this fetch was in flight may postdate its result.\n const missed = this.#recentEvents.some(\n (event) =>\n event.at >= startedAt && event.tags.some((tag) => response.syncTags?.includes(tag)),\n )\n if (missed) response = await this.#fetchSanity(query, params)\n\n await this.#store(key, query, params, response.result, response.syncTags)\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n return response.result\n }\n\n /** Store a result. Returns whether its hash changed. `tags` defaults to the previous ones. */\n async #store(\n key: string,\n query: string,\n params: QueryParams,\n result: unknown,\n syncTags?: string[],\n ): Promise<boolean> {\n const previous = this.#entries.get(key)\n if (previous) this.#unindex(key, previous.tags)\n\n const entry: Entry = {\n query,\n params,\n result,\n hash: await hashJson(result),\n tags: syncTags ?? previous?.tags ?? [],\n docs: documentIds(result, params),\n local: previous?.local ?? 'unknown',\n usedAt: Date.now(),\n }\n this.#entries.set(key, entry)\n for (const tag of entry.tags) {\n let keys = this.#byTag.get(tag)\n if (!keys) this.#byTag.set(tag, (keys = new Set()))\n keys.add(key)\n }\n this.#evict()\n return previous?.hash !== entry.hash\n }\n\n #unindex(key: string, tags: string[]) {\n for (const tag of tags) {\n const keys = this.#byTag.get(tag)\n keys?.delete(key)\n if (keys && !keys.size) this.#byTag.delete(tag)\n }\n }\n\n #evict() {\n if (this.#entries.size <= MAX_ENTRIES) return\n const oldest = [...this.#entries].sort((a, b) => a[1].usedAt - b[1].usedAt)\n for (const [key, entry] of oldest.slice(0, this.#entries.size - MAX_ENTRIES)) {\n this.#unindex(key, entry.tags)\n this.#entries.delete(key)\n }\n }\n\n /** Run hub work one task at a time per chain; the chains run independently. */\n #queue(chain: 'local' | 'sweep' | 'verify', task: () => Promise<void>) {\n this.#chains[chain] = this.#chains[chain].then(task).catch((error) => {\n console.warn(`[preview-hub] ${chain} task failed`, error)\n })\n }\n\n /** Evaluate a query locally; `null` when the mirror cannot answer it. */\n async #evaluateLocal(entry: Entry): Promise<unknown | null> {\n await this.#mirror.ready()\n await this.#mirror.ensure(entry.docs)\n // Products a page references only through a `*[_type == 'product' && _id in …]` scan.\n await this.#mirror.ensure(this.#mirror.referencesOf(entry.docs))\n let result = await this.#mirror.evaluate(entry.query, entry.params, this.#perspective)\n // The result may now name documents (products) the mirror does not hold yet.\n const ids = documentIds(result, entry.params)\n if (!this.#mirror.covers(ids)) {\n await this.#mirror.ensure(ids)\n result = await this.#mirror.evaluate(entry.query, entry.params, this.#perspective)\n }\n return result\n }\n\n /** Trust a query's local evaluation only if it reproduces Sanity's result exactly. */\n async #verify(key: string) {\n // Sanity's result lacks unsaved edits, so verifying an overlaid query would always fail.\n const overlaid = this.#entries.get(key)\n if (overlaid && this.#mirror.overlaid(overlaid.docs)) {\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n return\n }\n // Experiment switch: `LOCAL_EVAL = \"off\"` keeps every query on the Live API refetch path.\n if ((this.env as {LOCAL_EVAL?: string}).LOCAL_EVAL === 'off') return\n const entry = this.#entries.get(key)\n if (!entry || entry.local === 'ok') return\n try {\n const local = await this.#evaluateLocal(entry)\n const matches = (await hashJson(local)) === entry.hash\n entry.local = matches ? 'ok' : 'off'\n if (!matches) {\n this.#lastVerifyNote = `${key} ${firstDifference(entry.result, local)}`.slice(0, 300)\n console.log(\n '[preview-hub] local result differs; refetch only',\n key,\n firstDifference(entry.result, local),\n )\n }\n } catch (error) {\n entry.local = 'off'\n this.#lastVerifyNote = `${key} error ${String(error)}`.slice(0, 300)\n console.log('[preview-hub] local evaluation unsupported; refetch only', key, String(error))\n }\n }\n\n /**\n * After mirror mutations: re-evaluate the trusted queries whose results name an edited\n * document, and publish the ones that changed. Every other trusted query is re-evaluated\n * {@link REST_DELAY_MS} after edits stop: some are slow (the Makers list takes ~600 ms of CPU),\n * and running them now would make the tab's refresh requests, ~100 ms later, wait behind them.\n * The Live API sweep checks them against Sanity too.\n */\n async #flushLocal() {\n const started = Date.now()\n const edited = this.#editedDocs\n this.#editedDocs = new Set()\n\n const evaluated: string[] = []\n for (const [key, entry] of this.#entries) {\n if (entry.local !== 'ok') continue\n if (!entry.docs.some((id) => edited.has(id))) {\n this.#restPending.add(key)\n continue\n }\n evaluated.push(key)\n this.#restPending.delete(key)\n // Each result goes out as soon as it is ready, not after the slowest query.\n if (await this.#reevaluate(key, entry)) await this.#publish([key], 'local')\n }\n this.#lastLocalFlush = {\n queuedMs: started - this.#lastMutationAt,\n firstMs: Date.now() - started,\n evaluated,\n }\n\n if (this.#restTimer) clearTimeout(this.#restTimer)\n this.#restTimer = setTimeout(() => {\n this.#restTimer = null\n this.#queue('local', () => this.#flushRest())\n }, REST_DELAY_MS)\n }\n\n /** Re-evaluate the trusted queries the last edits did not name directly. */\n async #flushRest() {\n const keys = [...this.#restPending]\n this.#restPending.clear()\n const changed: string[] = []\n for (const key of keys) {\n const entry = this.#entries.get(key)\n if (!entry || entry.local !== 'ok') continue\n // `groq-js` runs as one long chain of microtasks; yield between queries so requests and\n // stream writes are not held until every evaluation is done.\n await yieldToEventLoop()\n if (await this.#reevaluate(key, entry)) changed.push(key)\n }\n await this.#publish(changed, 'rest')\n }\n\n /** Evaluate one trusted query locally and store it. Returns whether its result changed. */\n async #reevaluate(key: string, entry: Entry): Promise<boolean> {\n try {\n const result = await this.#evaluateLocal(entry)\n return await this.#store(key, entry.query, entry.params, result)\n } catch (error) {\n entry.local = 'off'\n console.warn('[preview-hub] local evaluation failed', key, error)\n return false\n }\n }\n\n #restPending = new Set<string>()\n #restTimer: ReturnType<typeof setTimeout> | null = null\n #lastLocalFlush: unknown = null\n\n async #fetchSanity(query: string, params: QueryParams): Promise<QueryResponse> {\n const url = this.#sanityUrl('query')\n url.searchParams.set('perspective', this.#perspective)\n url.searchParams.set('returnQuery', 'false')\n // Ask for results at least as new as the last Live event this hub has seen.\n if (this.#lastEventId) url.searchParams.set('lastLiveEventId', this.#lastEventId)\n return this.#post(url, query, params)\n }\n\n /** Raw perspective (published, drafts and versions as stored), for the mirror. */\n async #fetchRaw(query: string, params: QueryParams = {}): Promise<unknown> {\n const url = this.#sanityUrl('query')\n url.searchParams.set('perspective', 'raw')\n url.searchParams.set('returnQuery', 'false')\n return (await this.#post(url, query, params)).result\n }\n\n async #post(url: URL, query: string, params: QueryParams): Promise<QueryResponse> {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${this.env.SANITY_API_READ_TOKEN}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({query, params}),\n })\n if (!response.ok) {\n throw new Error(`Sanity query failed: HTTP ${response.status} ${await response.text()}`)\n }\n return response.json()\n }\n\n #sanityUrl(path: string): URL {\n const {SANITY_PROJECT_ID, SANITY_DATASET, SANITY_API_VERSION} = this.env\n return new URL(\n `https://${SANITY_PROJECT_ID}.api.sanity.io/v${SANITY_API_VERSION}/data/${path}/${SANITY_DATASET}`,\n )\n }\n\n #ensureUpstream() {\n if (this.#upstream) return\n const controller = new AbortController()\n this.#upstream = controller\n void this.#followListener(controller.signal)\n void this.#followLive(controller.signal)\n\n this.#idleTimer ??= setInterval(() => this.#checkIdle(), IDLE_CHECK_MS)\n }\n\n /**\n * Keep one Server-Sent Events stream from Sanity open until `signal` aborts, reconnecting with\n * exponential backoff. `onEvent` returns `false` to drop the connection and reconnect.\n */\n async #follow(\n name: string,\n signal: AbortSignal,\n connect: () => {url: URL; headers?: Record<string, string>},\n onEvent: (event: SseEvent) => boolean | void,\n ) {\n let backoff = 1_000\n const status = (this.#streamStatus[name] = {connects: 0, events: 0, error: ''})\n while (!signal.aborted) {\n try {\n status.connects++\n const {url, headers} = connect()\n const response = await fetch(url, {\n headers: {\n authorization: `Bearer ${this.env.SANITY_API_READ_TOKEN}`,\n accept: 'text/event-stream',\n // Uncompressed: a compressed event stream can be held in the decompressor\n // until more bytes arrive, delaying each event until the next one.\n 'accept-encoding': 'identity',\n ...headers,\n },\n signal,\n })\n if (!response.ok || !response.body) {\n throw new Error(`HTTP ${response.status} ${(await response.text()).slice(0, 200)}`)\n }\n backoff = 1_000\n for await (const event of parseSse(response.body)) {\n status.events++\n if (event.event === 'channelError') status.error = event.data.slice(0, 200)\n if (onEvent(event) === false) break\n }\n } catch (error) {\n if (signal.aborted) return\n status.error = String(error).slice(0, 200)\n console.warn(`[preview-hub] ${name} stream failed`, error)\n }\n if (signal.aborted) return\n await new Promise((resolve) => setTimeout(resolve, backoff))\n backoff = Math.min(backoff * 2, 30_000)\n }\n }\n\n /** Fast path: `/listen` mutation results, applied to the mirror as soon as they commit. */\n #followListener(signal: AbortSignal) {\n let connected = false\n return this.#follow(\n 'Listener',\n signal,\n () => {\n const url = this.#sanityUrl('listen')\n url.searchParams.set('query', LISTEN_QUERY)\n url.searchParams.set('includeResult', 'true')\n url.searchParams.set('visibility', 'transaction')\n url.searchParams.set('includeAllVersions', 'true')\n url.searchParams.set('tag', 'preview-hub')\n return {url}\n },\n (event) => {\n if (event.event === 'welcome') {\n // The listener cannot replay what it missed while disconnected: start the mirror\n // over and re-verify every query against Sanity.\n if (connected) this.#resetLocal()\n connected = true\n } else if (event.event === 'mutation') {\n const {documentId, transition, result} = JSON.parse(event.data) as {\n documentId: string\n transition: string\n result?: {_id: string; _type?: string}\n }\n if (this.#mirror.loaded && this.#mirror.apply(documentId, result, transition)) {\n this.#lastMutationAt = Date.now()\n this.#editedDocs.add(baseId(documentId))\n this.#scheduleLocal()\n }\n } else if (['reconnect', 'disconnect', 'channelError'].includes(event.event)) {\n if (event.event === 'channelError') {\n console.warn('[preview-hub] Listener channel error', event.data)\n }\n return false\n }\n },\n )\n }\n\n /** Authority: Live Content API sync tags, ~1 s after each write; replays from its event ID. */\n #followLive(signal: AbortSignal) {\n return this.#follow(\n 'Live Content API',\n signal,\n () => {\n const url = this.#sanityUrl('live/events')\n url.searchParams.set('includeDrafts', 'true')\n return {\n url,\n headers: this.#lastEventId ? {'last-event-id': this.#lastEventId} : undefined,\n }\n },\n (event) => {\n if (event.id) this.#lastEventId = event.id\n if (event.event === 'message') {\n const {tags} = JSON.parse(event.data) as {tags?: string[]}\n if (tags?.length) this.#onTags(tags)\n } else if (event.event === 'restart') {\n // The API lost track of what changed: refetch everything held.\n this.#onTags([...this.#byTag.keys()])\n } else if (event.event === 'reconnect') {\n return false\n }\n },\n )\n }\n\n /**\n * Unsaved Studio edits (LF-INIT-21): the `live-edit` Studio plugin posts the open document's\n * form value through the storefront. It shows in the mirror until the saved document catches\n * up or it goes stale, and trusted queries re-evaluate at once.\n */\n async #applyOverlay(doc: {_id: string; _type?: string}, seq: number): Promise<boolean> {\n this.#touch()\n this.#ensureUpstream()\n await this.#mirror.ready()\n if (!this.#mirror.overlay(doc, seq)) return false\n this.#lastMutationAt = Date.now()\n this.#editedDocs.add(baseId(doc._id))\n this.#flushLocalNow()\n this.#overlayTimer ??= setInterval(() => {\n for (const base of this.#mirror.expireOverlays(OVERLAY_TTL_MS)) this.#editedDocs.add(base)\n if (this.#editedDocs.size) this.#scheduleLocal()\n if (!this.#mirror.overlayCount && this.#overlayTimer) {\n clearInterval(this.#overlayTimer)\n this.#overlayTimer = null\n }\n }, 1_000)\n return true\n }\n\n #overlayTimer: ReturnType<typeof setInterval> | null = null\n\n #verifyPending = new Set<string>()\n #verifyTimer: ReturnType<typeof setTimeout> | null = null\n\n /** Verify pending queries once reads have paused for VERIFY_DELAY_MS, yielding between them. */\n #scheduleVerify() {\n if (this.#verifyTimer) clearTimeout(this.#verifyTimer)\n this.#verifyTimer = setTimeout(() => {\n this.#verifyTimer = null\n const keys = [...this.#verifyPending]\n this.#verifyPending.clear()\n this.#queue('verify', async () => {\n for (const key of keys) {\n await yieldToEventLoop()\n await this.#verify(key)\n }\n })\n }, VERIFY_DELAY_MS)\n }\n\n #resetLocal() {\n this.#mirror.clear()\n for (const [key, entry] of this.#entries) {\n entry.local = 'unknown'\n this.#verifyPending.add(key)\n }\n this.#scheduleVerify()\n }\n\n #localQueued = false\n\n /**\n * Re-evaluate on the local chain's next turn, with no timer: an editor is typing, and on Workers\n * a Durable Object's timers can fire late. Listener mutations keep {@link #scheduleLocal},\n * which coalesces a save's burst of documents.\n */\n #flushLocalNow() {\n if (this.#localQueued) return\n this.#localQueued = true\n this.#queue('local', async () => {\n this.#localQueued = false\n await this.#flushLocal()\n })\n }\n\n #scheduleLocal() {\n if (this.#localTimer) return\n this.#localTimer = setTimeout(() => {\n this.#localTimer = null\n this.#queue('local', () => this.#flushLocal())\n }, LOCAL_DELAY_MS)\n }\n\n #onTags(tags: string[]) {\n this.#recentEvents.push({at: Date.now(), tags})\n if (this.#recentEvents.length > RECENT_EVENTS) this.#recentEvents.shift()\n\n for (const tag of tags) this.#pendingTags.add(tag)\n if (this.#flushTimer) return\n this.#flushTimer = setTimeout(() => {\n this.#flushTimer = null\n this.#queue('sweep', () => this.#flush())\n }, FLUSH_DELAY_MS)\n }\n\n /** Refetch the results a Live event's sync tags name, from Sanity. */\n async #flush() {\n const tags = [...this.#pendingTags]\n this.#pendingTags.clear()\n\n const keys = new Set<string>()\n for (const tag of tags) for (const key of this.#byTag.get(tag) ?? []) keys.add(key)\n if (!keys.size) return\n\n // Every matching result is refetched, locally evaluated or not. In production `/listen`\n // events sometimes reach the hub late (2026-11-23), so this refetch is what bounds an\n // update at ~1.4 s when the fast path is held up.\n const changed: string[] = []\n await Promise.all(\n [...keys].map(async (key) => {\n const entry = this.#entries.get(key)\n if (!entry) return\n // The refetch lacks unsaved edits; applying it would flicker the page back mid-typing.\n if (entry.local === 'ok' && this.#mirror.overlaid(entry.docs)) return\n try {\n const response = await this.#fetchSanity(entry.query, entry.params)\n const didChange = await this.#store(\n key,\n entry.query,\n entry.params,\n response.result,\n response.syncTags,\n )\n if (didChange) changed.push(key)\n } catch (error) {\n // Drop the entry so the next read refetches instead of serving stale data.\n console.warn('[preview-hub] refetch failed', key, error)\n this.#unindex(key, entry.tags)\n this.#entries.delete(key)\n changed.push(key)\n }\n }),\n )\n await this.#publish(changed, 'sweep')\n }\n\n async #publish(changed: string[], source: 'local' | 'rest' | 'sweep') {\n if (!changed.length) return\n const chunk: PreviewInvalidation = {keys: changed.sort(), at: Date.now(), source}\n const seq = ++this.#seq\n this.#log.push({seq, chunk})\n if (this.#log.length > LOG_SIZE) this.#log.shift()\n\n // Push to WebSockets at once, with the new results, then wake the waiting long polls.\n if (!this.#sockets.size) {\n for (const wake of [...this.#waiters]) wake()\n return\n }\n const results: Record<string, unknown> = {}\n const labels: Record<string, string[]> = {}\n for (const key of changed) {\n const names = this.#labels.get(key)\n if (names?.size) labels[key] = [...names]\n const entry = this.#entries.get(key)\n if (!entry) continue\n const json = JSON.stringify(entry.result ?? null)\n if (json.length <= MAX_PUSH_BYTES) results[key] = entry.result ?? null\n }\n const message = JSON.stringify({\n cursor: `${this.#epoch}:${seq}`,\n events: [{...chunk, results, labels}],\n })\n for (const socket of this.#sockets) {\n try {\n socket.send(message)\n } catch {\n this.#sockets.delete(socket)\n }\n }\n for (const wake of [...this.#waiters]) wake()\n }\n\n #touch() {\n this.#lastActive = Date.now()\n }\n\n #checkIdle() {\n if (this.#polling > 0 || this.#sockets.size > 0 || Date.now() - this.#lastActive < IDLE_MS) {\n return\n }\n\n this.#upstream?.abort()\n this.#upstream = null\n if (this.#idleTimer) clearInterval(this.#idleTimer)\n this.#idleTimer = null\n this.#entries.clear()\n this.#byTag.clear()\n this.#labels.clear()\n this.#mirror.clear()\n }\n}\n\n/**\n * Base IDs of every `_id` and `_ref` anywhere in a result, plus every string in the params\n * (`getSections({ id })` returns no `_id` of its own). A param that is not a document ID only\n * adds a name the mirror marks as missing.\n */\nfunction documentIds(result: unknown, params: QueryParams): string[] {\n const found = new Set<string>()\n const walk = (value: unknown) => {\n if (Array.isArray(value)) {\n for (const item of value) walk(item)\n } else if (value && typeof value === 'object') {\n for (const [field, child] of Object.entries(value)) {\n if ((field === '_id' || field === '_ref') && typeof child === 'string') {\n found.add(baseId(child))\n } else {\n walk(child)\n }\n }\n }\n }\n walk(result)\n\n const walkParams = (value: unknown) => {\n if (typeof value === 'string') found.add(baseId(value))\n else if (Array.isArray(value)) value.forEach(walkParams)\n else if (value && typeof value === 'object') Object.values(value).forEach(walkParams)\n }\n walkParams(params)\n return [...found]\n}\n\n/** The first path where two JSON values differ, for logging why a local result was rejected. */\nfunction firstDifference(a: unknown, b: unknown, path = '$'): string | null {\n if (canonicalJson(a) === canonicalJson(b)) return null\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of keys) {\n const diff = firstDifference(\n (a as Record<string, unknown>)[key],\n (b as Record<string, unknown>)[key],\n `${path}.${key}`,\n )\n if (diff) return diff\n }\n }\n const show = (value: unknown) => JSON.stringify(value)?.slice(0, 80)\n return `${path}: sanity=${show(a)} local=${show(b)}`\n}\n\nfunction yieldToEventLoop(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0))\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const digest = new Uint8Array(\n await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input)),\n )\n return Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Stable key for a query and its params. */\nfunction fingerprint(query: string, params: QueryParams): Promise<string> {\n return sha256Hex(JSON.stringify([query, sortKeys(params)]))\n}\n\n/**\n * Hash of a result with object keys sorted. Sanity returns keys sorted and `groq-js` in projection\n * order, so a raw `JSON.stringify` would make every local result look different.\n */\nfunction hashJson(value: unknown): Promise<string> {\n return sha256Hex(canonicalJson(value))\n}\n\nfunction canonicalJson(value: unknown): string {\n return (\n JSON.stringify(value, (_key, child: unknown) =>\n child && typeof child === 'object' && !Array.isArray(child)\n ? Object.fromEntries(Object.entries(child).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : child,\n ) ?? 'undefined'\n )\n}\n\nfunction sortKeys(params: QueryParams): QueryParams {\n return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b)))\n}\n\n/** Header carrying the preview perspective, e.g. `drafts` or `rABC,drafts`. */\nconst PERSPECTIVE_HEADER = 'x-preview-perspective'\n\n/**\n * Entry point for the storefront's service binding (this Worker has no public URL). It picks the\n * hub for the request's perspective with `getByName()` here, inside this Worker, so the instance\n * can read its perspective from `ctx.id.name`. Through Vite dev's platform proxy, a Durable\n * Object stub reached directly from the storefront arrives without its name.\n */\nexport default {\n fetch(request: Request, env: PreviewHubEnv) {\n const perspective = request.headers.get(PERSPECTIVE_HEADER) ?? 'drafts'\n if (!/^[\\w.,-]{1,256}$/.test(perspective) || ['raw', 'published'].includes(perspective)) {\n return new Response('Invalid perspective', {status: 400})\n }\n // One instance per deployed version: an instance with open upstream streams is not\n // restarted on deploy and would keep running the old code. The old instance shuts down\n // once it has had no tabs and no reads for IDLE_MS.\n return env.PREVIEW_HUB.getByName(`${perspective}|${env.CF_VERSION_METADATA.id}`).fetch(request)\n },\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,WAAW,MAAwD;CACjF,IAAM,0BAAU,IAAI,IAAuB;CAE3C,OAAO;EAAC,MADUA,UAAQ,MAAyB,OAC7B;EAA0B,SAAS,CAAC,GAAG,QAAQ,OAAO,CAAC;CAAC;AAChF;AAEA,SAASA,UAAQ,MAAY,SA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AAO,WAAW,CAAC,CAAC,SAAS,WAAW,IAC7E,IAAI,SAAS,uBAAuB,EAAC,QAAQ,IAAG,CAAC,IAKnD,IAAI,YAAY,UAAU,GAAG,YAAY,GAAG,IAAI,oBAAoB,IAAI,CAAC,CAAC,MAAM,OAAO;AAChG,EACF"}
|
|
1
|
+
{"version":3,"file":"cloudflare.js","names":["rewrite","isNode"],"sources":["../src/cloudflare/indexes.ts","../src/cloudflare/sanity-compat.ts","../src/cloudflare/mirror.ts","../src/cloudflare/sse.ts","../src/cloudflare/index.ts"],"sourcesContent":["import type {ExprNode} from 'groq-js'\n\ntype Node = {type: string; [field: string]: unknown}\n\n/** A precomputed document list that replaces `*` in one filter. */\nexport interface IndexSpec {\n /** Name of the hidden parameter holding the list. */\n param: string\n kind: 'type' | 'id'\n values: string[]\n}\n\n/**\n * Index emulation for `groq-js`, which scans every document for each `*[…]`. A filter over `*`\n * whose condition has a top-level conjunct `_id == \"…\"`, `_type == \"…\"` or `_type in [...]`\n * (params are already inlined at parse time) gets its `*` replaced by a hidden parameter that\n * holds just those documents. The full condition still runs on that list, so the result is the\n * same; only documents that could never match are skipped. Lists keep the dataset's order.\n */\nexport function useIndexes(tree: ExprNode): {tree: ExprNode; indexes: IndexSpec[]} {\n const indexes = new Map<string, IndexSpec>()\n const rewritten = rewrite(tree as unknown as Node, indexes)\n return {tree: rewritten as unknown as ExprNode, indexes: [...indexes.values()]}\n}\n\nfunction rewrite(node: Node, indexes: Map<string, IndexSpec>): Node {\n const copy: Node = {...node}\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value)) {\n copy[key] = value.map((item) => (isNode(item) ? rewrite(item, indexes) : item))\n } else if (isNode(value)) {\n copy[key] = rewrite(value, indexes)\n }\n }\n if (copy.type !== 'Filter' || (copy.base as Node).type !== 'Everything') return copy\n\n const spec = indexFor(conjuncts(copy.expr as Node))\n if (!spec) return copy\n const param = `__index_${spec.kind}_${spec.values.join('|')}`\n indexes.set(param, {param, ...spec})\n return {...copy, base: {type: 'Parameter', name: param}}\n}\n\n/** Top-level `&&` operands, through groups. */\nfunction conjuncts(node: Node): Node[] {\n if (node.type === 'And')\n return [...conjuncts(node.left as Node), ...conjuncts(node.right as Node)]\n if (node.type === 'Group') return conjuncts(node.base as Node)\n return [node]\n}\n\nfunction indexFor(nodes: Node[]): Omit<IndexSpec, 'param'> | null {\n let byType: Omit<IndexSpec, 'param'> | null = null\n for (const node of nodes) {\n if (node.type !== 'OpCall') continue\n const field = attributeName(node.left as Node)\n if (node.op === '==' && field === '_id') {\n const value = stringValue(node.right as Node)\n if (value !== null) return {kind: 'id', values: [value]}\n }\n if (field !== '_type' || byType) continue\n if (node.op === '==') {\n const value = stringValue(node.right as Node)\n if (value !== null) byType = {kind: 'type', values: [value]}\n } else if (node.op === 'in') {\n const values = stringArray(node.right as Node)\n if (values) byType = {kind: 'type', values}\n }\n }\n return byType\n}\n\n/** The name of an implicit attribute access (`_type`, not `foo._type`). */\nfunction attributeName(node: Node): string | null {\n return node.type === 'AccessAttribute' && node.base === undefined ? (node.name as string) : null\n}\n\nfunction stringValue(node: Node): string | null {\n return node.type === 'Value' && typeof node.value === 'string' ? node.value : null\n}\n\nfunction stringArray(node: Node): string[] | null {\n if (node.type !== 'Array') return null\n const values: string[] = []\n for (const element of node.elements as Node[]) {\n if (element.isSplat) return null\n const value = stringValue(element.value as Node)\n if (value === null) return null\n values.push(value)\n }\n return values\n}\n\nfunction isNode(value: unknown): value is Node {\n return !!value && typeof value === 'object' && typeof (value as Node).type === 'string'\n}\n","import type {ExprNode} from 'groq-js'\n\ntype Node = {type: string; [field: string]: unknown}\n\n/** Node fields that open a new `@` scope: implicit attribute access inside them is not ours. */\nconst SCOPED = new Set(['Projection', 'Filter', 'Map', 'FlatMap'])\n\n/**\n * Make `groq-js` match a Sanity query-engine behaviour (observed 2026-11-23): Sanity fetches\n * only the sub-fields a projection names, so when none of them exist the parent object counts as\n * missing and `seo{title, description, image}` returns `null`, even though `seo` is an object\n * (here `{url: …}`). `groq-js` returns `{title: null, …}`.\n *\n * Each projection over a non-document base becomes\n * `select(count(base) != null || defined(base._id) || defined(base.f1) || … => base, null){…}`,\n * where `f1…` are the fields the projection reads from `@`. Arrays and documents pass through\n * unchanged; projections over document sets (`*[…]`) are left alone. The hub's verification gate\n * still compares every query with Sanity before trusting it.\n */\nexport function emulateSanityPruning(tree: ExprNode): ExprNode {\n return rewrite(tree as unknown as Node) as unknown as ExprNode\n}\n\nfunction rewrite(node: Node): Node {\n const copy: Node = {...node}\n for (const [key, value] of Object.entries(node)) {\n if (Array.isArray(value)) copy[key] = value.map((item) => (isNode(item) ? rewrite(item) : item))\n else if (isNode(value)) copy[key] = rewrite(value)\n }\n if (copy.type !== 'Projection') return copy\n\n const base = copy.base as Node\n const expr = copy.expr as Node\n if (expr.type !== 'Object' || containsEverything(base)) return copy\n const attributes = expr.attributes as Node[]\n if (attributes.some((attribute) => attribute.type !== 'ObjectAttributeValue')) return copy\n\n const fields = new Set<string>()\n let usesThis = false\n for (const attribute of attributes) {\n usesThis = collectFields(attribute.value as Node, fields) || usesThis\n }\n // A projection that reads `@` itself (`@->title`, `defined(@->)`) makes Sanity fetch the\n // whole object, so nothing is pruned.\n if (usesThis || !fields.size) return copy\n\n const conditions: Node[] = [\n {\n type: 'OpCall',\n op: '!=',\n left: {type: 'FuncCall', namespace: 'global', name: 'count', args: [base]},\n right: {type: 'Value', value: null},\n },\n ...['_id', ...fields].map((name) => ({\n type: 'FuncCall',\n namespace: 'global',\n name: 'defined',\n args: [{type: 'AccessAttribute', base, name}],\n })),\n ]\n const condition = conditions.reduce((left, right) => ({type: 'Or', left, right}))\n\n return {\n ...copy,\n base: {\n type: 'Select',\n alternatives: [{type: 'SelectAlternative', condition, value: base}],\n fallback: {type: 'Value', value: null},\n },\n }\n}\n\n/**\n * Root fields read from `@` (implicit attribute access), not descending into new scopes.\n * Returns whether `@` itself is read.\n */\nfunction collectFields(node: Node, fields: Set<string>): boolean {\n if (node.type === 'AccessAttribute' && node.base === undefined) {\n fields.add(node.name as string)\n return false\n }\n if (node.type === 'This') return true\n let usesThis = false\n for (const [key, value] of Object.entries(node)) {\n // The scoped part of a projection/filter/map is evaluated against a different `@`.\n if (SCOPED.has(node.type) && key === 'expr') continue\n if (Array.isArray(value)) {\n for (const item of value) if (isNode(item)) usesThis = collectFields(item, fields) || usesThis\n } else if (isNode(value)) {\n usesThis = collectFields(value, fields) || usesThis\n }\n }\n return usesThis\n}\n\nfunction containsEverything(node: Node): boolean {\n if (node.type === 'Everything') return true\n return Object.values(node).some((value) =>\n Array.isArray(value)\n ? value.some((item) => isNode(item) && containsEverything(item))\n : isNode(value) && containsEverything(value),\n )\n}\n\nfunction isNode(value: unknown): value is Node {\n return !!value && typeof value === 'object' && typeof (value as Node).type === 'string'\n}\n","import {evaluate, parse, type ExprNode} from 'groq-js'\nimport {useIndexes, type IndexSpec} from './indexes'\nimport {emulateSanityPruning} from './sanity-compat'\n\ntype Doc = {_id: string; _type?: string; [field: string]: unknown}\ntype QueryParams = Record<string, unknown>\n\n/** A perspective's documents, kept current one document at a time. */\ninterface View {\n stack: {releases: string[]; withDrafts: boolean}\n /** Base ID → the document the perspective sees, with `_id` set to the base ID. */\n byId: Map<string, Doc>\n /** Rebuilt from `byId` on demand after a change (references only, no copies). */\n docs: Doc[] | null\n byType: Map<string, Doc[]> | null\n}\n\n/**\n * Default on-demand types: Shopify-synced types made up ~21 of one dataset's ~22 MB (2026-11-23:\n * 17,235 variants, 2,701 products). The mirror holds every other document, and only the products\n * that held results reference.\n */\nexport const DEFAULT_ON_DEMAND_TYPES = ['product', 'productVariant']\n/** Default types left out of `/listen`. Variants never feed preview queries. */\nexport const DEFAULT_LISTEN_EXCLUDED_TYPES = ['productVariant']\n\nexport interface MirrorOptions {\n /**\n * Types not bulk-loaded: a document of these types is fetched only when a held result\n * references it, then kept current. Defaults to {@link DEFAULT_ON_DEMAND_TYPES}.\n */\n onDemandTypes?: string[]\n /**\n * Types left out of `/listen` (see {@link Mirror.listenQuery}). They are on-demand too, since\n * the mirror could not keep them current. Defaults to {@link DEFAULT_LISTEN_EXCLUDED_TYPES}.\n */\n listenExcludedTypes?: string[]\n}\n\n/** Parse a comma-separated type list (a Worker var). Unset → `undefined`, so defaults apply. */\nexport function parseTypeList(value: string | undefined): string[] | undefined {\n if (value === undefined) return undefined\n return value\n .split(',')\n .map((type) => type.trim())\n .filter(Boolean)\n}\n\n/** `*[...]` over documents not of these types, leaving out system documents (`_.`). */\nfunction filterQuery(excluded: string[]): string {\n const system = '!(_id in path(\"_.**\"))'\n return excluded.length\n ? `*[!(_type in ${JSON.stringify(excluded)}) && ${system}]`\n : `*[${system}]`\n}\n\n/** Strip the `drafts.` or `versions.<release>.` prefix so every variant maps to one ID. */\nexport function baseId(id: string): string {\n return id.replace(/^drafts\\./, '').replace(/^versions\\.[^.]+\\./, '')\n}\n\n/**\n * A local copy of the documents preview queries read (raw: published, `drafts.` and\n * `versions.` IDs), kept current from `/listen` mutation results. It evaluates GROQ with\n * `groq-js` against a perspective view built here, since `groq-js` has no perspectives.\n *\n * Production CPU is much slower than a laptop (2026-11-23: rebuilding the view took 0.2–0.55 s and\n * a page query with a product scan ~3 s), so views update one document at a time, and scans\n * filtered by `_type` or `_id` read precomputed lists instead of every document (`indexes.ts`).\n */\nexport class Mirror {\n #docs = new Map<string, Doc>()\n /** Base ID → release name → version document. */\n #versions = new Map<string, Map<string, Doc>>()\n /** Base IDs of on-demand documents the mirror tracks. */\n #tracked = new Set<string>()\n /** Base IDs known not to exist, so they are not fetched again for every evaluation. */\n #missing = new Set<string>()\n /**\n * Unsaved Studio edits (LF-INIT-21), keyed by draft or version ID. They sit above the saved\n * document until the saved content catches up, or until they go stale.\n */\n #overlays = new Map<string, {doc: Doc; seq: number; at: number}>()\n #trees = new Map<string, {tree: ExprNode; indexes: IndexSpec[]}>()\n #views = new Map<string, View>()\n #ready: Promise<void> | null = null\n #fetchRaw: (query: string, params?: QueryParams) => Promise<unknown>\n #loaded = false\n #onDemandTypes: Set<string>\n #baseQuery: string\n /** `/listen` filter: everything the mirror can hold. */\n readonly listenQuery: string\n\n constructor(\n fetchRaw: (query: string, params?: QueryParams) => Promise<unknown>,\n options: MirrorOptions = {},\n ) {\n this.#fetchRaw = fetchRaw\n const excluded = options.listenExcludedTypes ?? DEFAULT_LISTEN_EXCLUDED_TYPES\n this.#onDemandTypes = new Set([\n ...(options.onDemandTypes ?? DEFAULT_ON_DEMAND_TYPES),\n ...excluded,\n ])\n this.#baseQuery = filterQuery([...this.#onDemandTypes])\n this.listenQuery = filterQuery(excluded)\n }\n\n #onDemand(type: string | undefined): boolean {\n return type !== undefined && this.#onDemandTypes.has(type)\n }\n\n get loaded(): boolean {\n return this.#loaded\n }\n\n /** Load every document not of an on-demand type once. Concurrent callers share one load. */\n ready(): Promise<void> {\n this.#ready ??= (async () => {\n const docs = (await this.#fetchRaw(this.#baseQuery)) as Doc[]\n for (const doc of docs) this.#put(doc)\n this.#views.clear()\n this.#loaded = true\n })().catch((error) => {\n this.#ready = null\n throw error\n })\n return this.#ready\n }\n\n clear() {\n this.#overlays.clear()\n this.#docs.clear()\n this.#versions.clear()\n this.#tracked.clear()\n this.#missing.clear()\n this.#views.clear()\n this.#ready = null\n this.#loaded = false\n }\n\n /** Fetch the published and draft variants of any base IDs the mirror lacks. */\n async ensure(ids: string[]): Promise<void> {\n const wanted = ids.filter((id) => !this.#knows(id))\n if (!wanted.length) return\n const docs = (await this.#fetchRaw('*[_id in $ids]', {\n ids: wanted.flatMap((id) => [id, `drafts.${id}`]),\n })) as Doc[]\n const found = new Set<string>()\n for (const doc of docs) {\n const base = baseId(doc._id)\n found.add(base)\n this.#put(doc)\n if (this.#onDemand(doc._type)) this.#tracked.add(base)\n }\n for (const id of wanted) if (!found.has(id)) this.#missing.add(id)\n for (const base of found) this.#refresh(base)\n }\n\n /**\n * Apply one `/listen` mutation (`includeResult=true`). Returns whether the mirror changed.\n * On-demand documents the mirror does not track are ignored.\n */\n apply(documentId: string, result: Doc | undefined, transition: string): boolean {\n const base = baseId(documentId)\n if (transition === 'disappear' || !result) {\n if (!this.#remove(documentId)) return false\n } else {\n if (this.#onDemand(result._type) && !this.#tracked.has(base)) return false\n this.#put(result)\n this.#missing.delete(base)\n }\n // The saved document has caught up with (or replaced) the unsaved edits.\n const overlay = this.#overlays.get(documentId)\n if (overlay && (!result || transition === 'disappear' || sameContent(overlay.doc, result))) {\n this.#overlays.delete(documentId)\n }\n this.#refresh(base)\n return true\n }\n\n /**\n * Show an unsaved Studio edit in place of the saved draft or version. `seq` orders updates\n * from one editor; an older one is ignored. Returns whether the mirror changed.\n */\n overlay(doc: Doc, seq: number, now = Date.now()): boolean {\n if (!/^(drafts|versions)\\./.test(doc._id)) return false\n const base = baseId(doc._id)\n if (this.#onDemand(doc._type) && !this.#tracked.has(base)) return false\n const current = this.#overlays.get(doc._id)\n if (current && current.seq >= seq) return false\n this.#overlays.set(doc._id, {doc, seq, at: now})\n this.#refresh(base)\n return true\n }\n\n /** Drop overlays with no update for `ttl` ms. Returns the base IDs that changed. */\n expireOverlays(ttl: number, now = Date.now()): string[] {\n const expired: string[] = []\n for (const [id, overlay] of this.#overlays) {\n if (now - overlay.at < ttl) continue\n this.#overlays.delete(id)\n const base = baseId(id)\n this.#refresh(base)\n expired.push(base)\n }\n return expired\n }\n\n get overlayCount(): number {\n return this.#overlays.size\n }\n\n /** Whether any of these base IDs currently show unsaved edits. */\n overlaid(ids: string[]): boolean {\n if (!this.#overlays.size) return false\n const bases = new Set([...this.#overlays.keys()].map(baseId))\n return ids.some((id) => bases.has(id))\n }\n\n /** Base IDs referenced (`_ref`) by any variant of the given documents. */\n referencesOf(ids: string[]): string[] {\n const found = new Set<string>()\n const walk = (value: unknown) => {\n if (Array.isArray(value)) value.forEach(walk)\n else if (value && typeof value === 'object') {\n for (const [field, child] of Object.entries(value)) {\n if (field === '_ref' && typeof child === 'string') found.add(baseId(child))\n else walk(child)\n }\n }\n }\n for (const id of ids) {\n for (const doc of this.#variants(id)) walk(doc)\n }\n return [...found]\n }\n\n /** Debug: rebuild one perspective view from scratch. */\n benchView(perspective: string) {\n this.#views.delete(perspective)\n this.#lists(this.#view(perspective))\n }\n\n /** Whether every ID is in the mirror (or known not to exist). */\n covers(ids: string[]): boolean {\n return ids.every((id) => this.#knows(id))\n }\n\n /**\n * Evaluate a GROQ query against the given perspective. `->` looks documents up by ID and\n * fetches any the mirror does not hold yet (on-demand types), so references resolve as on Sanity.\n */\n async evaluate(query: string, params: QueryParams, perspective: string): Promise<unknown> {\n const {tree, indexes} = this.#parse(query, params)\n const view = this.#view(perspective)\n const lists = this.#lists(view)\n const indexParams: QueryParams = {}\n for (const index of indexes) {\n if (index.kind === 'id') {\n const doc = view.byId.get(index.values[0])\n indexParams[index.param] = doc ? [doc] : []\n } else if (index.values.length === 1) {\n indexParams[index.param] = lists.byType.get(index.values[0]) ?? []\n } else {\n // Several types: keep the dataset's order, as a full scan would.\n const types = new Set(index.values)\n indexParams[index.param] = lists.docs.filter((doc) => types.has(doc._type ?? ''))\n }\n }\n const value = await evaluate(tree, {\n dataset: lists.docs,\n params: {...params, ...indexParams},\n dereference: async ({_ref}) => {\n const id = baseId(_ref)\n const known = view.byId.get(id)\n if (known || this.#missing.has(id)) return known ?? null\n await this.ensure([id])\n return view.byId.get(id) ?? null\n },\n })\n return value.get()\n }\n\n #parse(query: string, params: QueryParams) {\n const key = JSON.stringify([query, params])\n let parsed = this.#trees.get(key)\n if (!parsed) {\n parsed = useIndexes(emulateSanityPruning(parse(query, {params})))\n if (this.#trees.size > 1_000) this.#trees.clear()\n this.#trees.set(key, parsed)\n }\n return parsed\n }\n\n #knows(id: string): boolean {\n return this.#missing.has(id) || this.#docs.has(id) || this.#docs.has(`drafts.${id}`)\n }\n\n #put(doc: Doc) {\n this.#docs.set(doc._id, doc)\n if (doc._id.startsWith('versions.')) {\n const base = baseId(doc._id)\n let versions = this.#versions.get(base)\n if (!versions) this.#versions.set(base, (versions = new Map()))\n versions.set(doc._id.split('.')[1], doc)\n }\n }\n\n #remove(id: string): boolean {\n if (!this.#docs.delete(id)) return false\n if (id.startsWith('versions.')) this.#versions.get(baseId(id))?.delete(id.split('.')[1])\n return true\n }\n\n #variants(base: string): Doc[] {\n const docs: Doc[] = []\n const published = this.#docs.get(base)\n const draft = this.#overlays.get(`drafts.${base}`)?.doc ?? this.#docs.get(`drafts.${base}`)\n if (published) docs.push(published)\n if (draft) docs.push(draft)\n for (const version of this.#versions.get(base)?.values() ?? []) docs.push(version)\n for (const [id, overlay] of this.#overlays) {\n if (id.startsWith('versions.') && baseId(id) === base) docs.push(overlay.doc)\n }\n return docs\n }\n\n /** The document a perspective sees for one base ID, or `undefined`. */\n #choose(base: string, stack: View['stack']): Doc | undefined {\n let chosen: Doc | undefined\n const versions = this.#versions.get(base)\n for (const release of stack.releases) {\n chosen ??= this.#overlays.get(`versions.${release}.${base}`)?.doc ?? versions?.get(release)\n }\n if (stack.withDrafts) {\n chosen ??= this.#overlays.get(`drafts.${base}`)?.doc ?? this.#docs.get(`drafts.${base}`)\n }\n chosen ??= this.#docs.get(base)\n return chosen && {...chosen, _id: base, _originalId: chosen._id}\n }\n\n /** Re-choose one base ID in every built view. */\n #refresh(base: string) {\n for (const view of this.#views.values()) {\n const doc = this.#choose(base, view.stack)\n if (doc) view.byId.set(base, doc)\n else view.byId.delete(base)\n view.docs = null\n view.byType = null\n }\n }\n\n /**\n * The documents as a perspective sees them: per base ID, the first of the release versions\n * (in stack order), the draft (if `drafts` is in the stack) and the published document, with\n * `_id` set to the base ID and `_originalId` to the document chosen.\n */\n #view(perspective: string): View {\n const cached = this.#views.get(perspective)\n if (cached) return cached\n\n const names = perspective.split(',')\n const stack = {\n releases: names.filter((name) => name !== 'drafts' && name !== 'published'),\n withDrafts: names.includes('drafts'),\n }\n const view: View = {stack, byId: new Map(), docs: null, byType: null}\n const seen = new Set<string>()\n for (const id of this.#docs.keys()) {\n const base = baseId(id)\n if (seen.has(base)) continue\n seen.add(base)\n const doc = this.#choose(base, stack)\n if (doc) view.byId.set(base, doc)\n }\n this.#views.set(perspective, view)\n return view\n }\n\n #lists(view: View): {docs: Doc[]; byType: Map<string, Doc[]>} {\n if (!view.docs || !view.byType) {\n view.docs = [...view.byId.values()]\n view.byType = new Map()\n for (const doc of view.docs) {\n const type = doc._type ?? ''\n let list = view.byType.get(type)\n if (!list) view.byType.set(type, (list = []))\n list.push(doc)\n }\n }\n return {docs: view.docs, byType: view.byType}\n }\n}\n\n/** System fields that differ between the Studio's form value and the saved document. */\nconst SYSTEM_FIELDS = new Set(['_rev', '_updatedAt', '_createdAt', '_system', '_originalId'])\n\n/** Whether two documents hold the same content, ignoring system fields and key order. */\nfunction sameContent(a: Doc, b: Doc): boolean {\n const canonical = (doc: Doc) =>\n JSON.stringify(\n Object.fromEntries(Object.entries(doc).filter(([key]) => !SYSTEM_FIELDS.has(key))),\n (_key, value: unknown) =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? Object.fromEntries(\n Object.entries(value).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0)),\n )\n : value,\n )\n return canonical(a) === canonical(b)\n}\n","export interface SseEvent {\n id?: string\n event: string\n data: string\n}\n\n/** Parse a `text/event-stream` body into events. Comments and `retry:` lines are skipped. */\nexport async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> {\n const reader = body\n .pipeThrough(new TextDecoderStream() as unknown as ReadableWritablePair<string, Uint8Array>)\n .getReader()\n let buffer = ''\n\n try {\n while (true) {\n const {done, value} = await reader.read()\n if (done) return\n buffer += value.replace(/\\r\\n?/g, '\\n')\n\n let boundary: number\n while ((boundary = buffer.indexOf('\\n\\n')) !== -1) {\n const block = buffer.slice(0, boundary)\n buffer = buffer.slice(boundary + 2)\n const event = parseBlock(block)\n if (event) yield event\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\nfunction parseBlock(block: string): SseEvent | null {\n let id: string | undefined\n let event = 'message'\n const data: string[] = []\n\n for (const line of block.split('\\n')) {\n if (!line || line.startsWith(':')) continue\n const colon = line.indexOf(':')\n const field = colon === -1 ? line : line.slice(0, colon)\n const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '')\n if (field === 'id') id = value\n else if (field === 'event') event = value\n else if (field === 'data') data.push(value)\n }\n\n if (!data.length && !id && event === 'message') return null\n return {id, event, data: data.join('\\n')}\n}\n","import {DurableObject} from 'cloudflare:workers'\nimport {Mirror, baseId, parseTypeList} from './mirror'\nimport {parseSse, type SseEvent} from './sse'\n\n/**\n * Realtime preview hub (LF-INIT-20). One instance per preview perspective, addressed by name\n * (`drafts`, or a release stack such as `rABC,drafts`).\n *\n * - Reads: the storefront calls `POST /query` instead of Sanity. Results are held in memory with\n * their sync tags, so editors on the same page share one Sanity fetch.\n * - Fast path: a local mirror of the documents (`mirror.ts`) follows `/listen` with\n * `includeResult`, ~50 ms after each write, and re-evaluates held queries with `groq-js`.\n * A query uses this path only after its local result matched Sanity's exactly.\n * Refetching instead would not help: Sanity's query API returns a change only ~1 s after the\n * write, whatever the request (tested 2026-11-23).\n * - Authority: one Live Content API stream (`includeDrafts`) reports changed sync tags ~1 s after\n * each write. Matching results are refetched from Sanity, which corrects any local result.\n * (The `invalidate-tags` Sanity Function never fires for draft edits, tested 2026-11-23.)\n * - Downstream: when a result's hash changes, its key is appended to an in-memory log and sent at\n * once to every tab's WebSocket (`/socket`); tabs that cannot open one long-poll (`/events`).\n * A tab resumes from its cursor. Nothing here touches Durable Object storage: on Workers, the\n * output gate holds a Durable Object's outgoing messages until its storage writes are\n * confirmed, and with a durable log (`agents/streams`) every update reached the tab ~3 s late\n * (2026-11-23).\n */\n\ntype QueryParams = Record<string, unknown>\n\n/** Set by the storefront on a WebSocket from an editor with a live-edit session. */\nconst LIVE_EDIT_HEADER = 'x-live-edit'\n\n/** Whether a query's local evaluation is trusted: `ok` after it reproduced Sanity's result. */\ntype LocalState = 'unknown' | 'ok' | 'off'\n\ninterface Entry {\n query: string\n params: QueryParams\n result: unknown\n hash: string\n tags: string[]\n /** Base IDs of every `_id`/`_ref` in the result and every string in the params. */\n docs: string[]\n local: LocalState\n /**\n * Consecutive verifications where the local result differed from Sanity's (or evaluation\n * failed), and when a new Sanity result may be checked again (see {@link RETRY_BASE_MS}).\n */\n mismatches: number\n retryAt: number\n usedAt: number\n}\n\ninterface QueryResponse {\n result: unknown\n syncTags?: string[]\n}\n\n/** What a tab receives: events after its cursor, and the new cursor. */\ninterface EventsMessage {\n cursor: string\n events: PreviewInvalidation[]\n /** The tab's cursor is unknown here: refresh everything. */\n reset?: boolean\n}\n\n/** Payload of each invalidation event sent to tabs. */\nexport interface PreviewInvalidation {\n keys: string[]\n at: number\n /** Which path found the change: local evaluation, the delayed re-evaluation or a refetch. */\n source: 'local' | 'rest' | 'sweep'\n /**\n * The changed results, by key, so a tab can show them without asking again. Only for results\n * under {@link MAX_PUSH_BYTES}. Events a tab catches up on (a long poll, or a reconnecting\n * WebSocket) carry each key's current result, on the last event that names the key.\n */\n results?: Record<string, unknown>\n /** The storefront remote queries that read each changed key. */\n labels?: Record<string, string[]>\n}\n\nconst MAX_ENTRIES = 500\n/** Stop the upstream streams and drop the caches after this long with no reads and no tabs. */\n// Long enough that an editor who pauses comes back to a warm hub; an idle instance costs little.\nconst IDLE_MS = 30 * 60_000\n/**\n * An unsaved edit with no update for this long is dropped. The Studio saves within ~1 s of the\n * last keystroke, so by then the saved draft has normally replaced it.\n */\nconst OVERLAY_TTL_MS = 5_000\n/** Verification waits for reads to pause this long, so it never competes with a page load. */\nconst VERIFY_DELAY_MS = 750\n/**\n * A query whose local result once differed from Sanity's is checked again when it is read or a\n * refetch changes its result, this long after the first miss, doubling with each further miss up\n * to {@link RETRY_MAX_MS}. A one-off miss (the mirror a mutation behind Sanity, a draft created or\n * discarded mid-check) would otherwise keep a query on the slower refetch path until the upstream\n * reconnects; a real difference costs a check now and then.\n */\nconst RETRY_BASE_MS = 5_000\nconst RETRY_MAX_MS = 5 * 60_000\nconst IDLE_CHECK_MS = 60_000\n/** Events kept in memory for tabs whose next poll comes after a burst of changes. */\nconst LOG_SIZE = 200\n/** A poll with nothing to report answers after this long; the tab polls again at once. */\nconst POLL_TIMEOUT_MS = 25_000\n/** Coalesce events that arrive together (a Studio save often touches several documents). */\nconst FLUSH_DELAY_MS = 25\nconst LOCAL_DELAY_MS = 10\n/** Quiet period after the last edit before re-evaluating queries that do not name it. */\nconst REST_DELAY_MS = 400\nconst RECENT_EVENTS = 50\n/** Larger results are announced by key alone; the tab refetches them. */\nconst MAX_PUSH_BYTES = 256_000\n/** Remote query labels kept per held query, and the longest accepted. */\nconst MAX_LABELS_PER_QUERY = 32\nconst MAX_LABEL_LENGTH = 2_000\n/** An unsaved document larger than this is ignored; the saved draft still reaches the hub. */\nconst MAX_OVERLAY_BYTES = 1_000_000\n\n/** Cloudflare Worker bindings and vars for the preview hub worker. */\nexport interface PreviewHubEnv {\n CF_VERSION_METADATA: {id: string}\n SANITY_PROJECT_ID: string\n SANITY_DATASET: string\n SANITY_API_VERSION: string\n SANITY_API_READ_TOKEN: string\n /**\n * Comma-separated document types the mirror does not bulk-load; one is fetched only when a held\n * result references it. Default `product,productVariant`; set to `\"\"` to bulk-load every type.\n */\n PREVIEW_HUB_ON_DEMAND_TYPES?: string\n /**\n * Comma-separated document types left out of the `/listen` stream (and so also on-demand).\n * Default `productVariant`; set to `\"\"` to listen to every type.\n */\n PREVIEW_HUB_LISTEN_EXCLUDED_TYPES?: string\n PREVIEW_HUB: {\n getByName(name: string): {fetch(request: Request): Promise<Response>}\n }\n}\n\nexport class PreviewHub extends DurableObject<PreviewHubEnv> {\n #entries = new Map<string, Entry>()\n #byTag = new Map<string, Set<string>>()\n #inflight = new Map<string, Promise<unknown>>()\n #recentEvents: {at: number; tags: string[]}[] = []\n #mirror = new Mirror((query, params) => this.#fetchRaw(query, params), {\n onDemandTypes: parseTypeList(this.env.PREVIEW_HUB_ON_DEMAND_TYPES),\n listenExcludedTypes: parseTypeList(this.env.PREVIEW_HUB_LISTEN_EXCLUDED_TYPES),\n })\n #lastMutationAt = 0\n #lastVerifyNote = ''\n /** Upstream stream health, for diagnostics. */\n #streamStatus: Record<string, {connects: number; events: number; error: string}> = {}\n /** Base IDs mutated since the last local flush. */\n #editedDocs = new Set<string>()\n\n #upstream: AbortController | null = null\n #lastEventId: string | null = null\n #idleTimer: ReturnType<typeof setInterval> | null = null\n #lastActive = Date.now()\n\n #pendingTags = new Set<string>()\n #flushTimer: ReturnType<typeof setTimeout> | null = null\n #localTimer: ReturnType<typeof setTimeout> | null = null\n /** Independent task chains, so local updates never wait behind Sanity fetches. */\n #chains: Record<'local' | 'sweep' | 'verify', Promise<void>> = {\n local: Promise.resolve(),\n sweep: Promise.resolve(),\n verify: Promise.resolve(),\n }\n\n /** Long polls waiting right now. */\n #polling = 0\n /** Wakes the waiting long polls when the log grows. */\n #waiters = new Set<() => void>()\n /** Tabs following this hub over a WebSocket. */\n #sockets = new Set<WebSocket>()\n /** The storefront remote queries (labels) that read each held query, by key. */\n #labels = new Map<string, Set<string>>()\n\n #label(key: string, label: string) {\n let labels = this.#labels.get(key)\n if (!labels) this.#labels.set(key, (labels = new Set()))\n if (labels.size < MAX_LABELS_PER_QUERY) labels.add(label)\n }\n /** Changes on every instance start, so a `Last-Event-ID` from before a restart is recognised. */\n #epoch = crypto.randomUUID().slice(0, 8)\n #seq = 0\n #log: {seq: number; chunk: PreviewInvalidation}[] = []\n\n /** The instance name is `<perspective>|<deployed version id>`; see the default export. */\n get #perspective(): string {\n return (this.ctx.id.name ?? 'drafts').split('|')[0]\n }\n\n /** Run a GROQ query in this hub's perspective, from memory when the hub already holds it. */\n async query<T = unknown>(query: string, params: QueryParams = {}, label?: string): Promise<T> {\n this.#touch()\n this.#ensureUpstream()\n // Start loading the mirror on the first read, overlapping the network wait with the page.\n if (!this.#mirror.loaded) void this.#mirror.ready().catch(() => {})\n // Reads push verification back until the page load is over.\n if (this.#verifyPending.size) this.#scheduleVerify()\n\n const key = await fingerprint(query, params)\n if (label) this.#label(key, label)\n const entry = this.#entries.get(key)\n if (entry) {\n entry.usedAt = Date.now()\n // A page opening is a good time to give a distrusted query another chance (after the\n // page load, as verification waits for reads to pause).\n if (entry.local === 'off' && entry.usedAt >= entry.retryAt) {\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n }\n return entry.result as T\n }\n\n let pending = this.#inflight.get(key)\n if (!pending) {\n pending = this.#load(key, query, params).finally(() => this.#inflight.delete(key))\n this.#inflight.set(key, pending)\n }\n return (await pending) as T\n }\n\n /**\n * - `POST /query` `{ query, params, label? }` → `{ result }`. `label` names the storefront's\n * remote query reading it; events for the query carry it back. The storefront uses this rather than the\n * `query()` RPC method because Vite dev's platform proxy cannot carry Durable Object RPC.\n * - `GET /socket` (WebSocket upgrade) → invalidation events, pushed as they happen.\n * - `GET /events` → the same events by long poll, for tabs without a WebSocket.\n * - `GET /stats` → entry counts by local state and timings, for debugging.\n */\n async fetch(request: Request): Promise<Response> {\n const url = new URL(request.url)\n if (url.pathname === '/query' && request.method === 'POST') {\n const {query, params, label} = (await request.json()) as {\n query: string\n params?: QueryParams\n label?: unknown\n }\n const name = typeof label === 'string' && label.length <= MAX_LABEL_LENGTH ? label : undefined\n return Response.json({result: await this.query(query, params ?? {}, name)})\n }\n if (url.pathname === '/stats') {\n const local: Record<LocalState, number> = {unknown: 0, ok: 0, off: 0}\n for (const entry of this.#entries.values()) local[entry.local]++\n return Response.json({\n entries: this.#entries.size,\n local,\n polling: this.#polling,\n sockets: this.#sockets.size,\n mirror: this.#mirror.loaded,\n lastLocalFlush: this.#lastLocalFlush,\n upstream: this.#streamStatus,\n lastVerifyNote: this.#lastVerifyNote,\n })\n }\n if (url.pathname === '/socket') return this.#socket(request)\n if (url.pathname === '/events') return this.#poll(request)\n if (url.pathname === '/overlay' && request.method === 'POST') {\n const {document, seq} = (await request.json()) as {\n document: {_id: string; _type?: string}\n seq: number\n }\n return Response.json({applied: await this.#applyOverlay(document, seq)})\n }\n if (url.pathname === '/bench') {\n // Debug: evaluate one held query locally (or rebuild the perspective view) and answer.\n // The caller times the request; Workers freezes the clock during computation.\n const key = url.searchParams.get('key')\n if (url.searchParams.has('view')) {\n await this.#mirror.ready()\n this.#mirror.benchView(this.#perspective)\n return Response.json({view: true})\n }\n const entry = key ? this.#entries.get(key) : undefined\n if (!entry) {\n return Response.json({\n keys: [...this.#entries].map(([k, e]) => ({\n key: k,\n local: e.local,\n query: e.query.length,\n mismatches: e.mismatches,\n })),\n })\n }\n const result = await this.#evaluateLocal(entry)\n return Response.json({key, bytes: JSON.stringify(result)?.length ?? 0})\n }\n return new Response('Not found', {status: 404})\n }\n\n /**\n * What a tab at cursor `after` has missed: `{ cursor, events }`, `reset` when the cursor is from\n * another instance (the hub restarted or was redeployed) or older than the log (refresh\n * everything), or `null` when it is up to date. Without a cursor, the current one, so a new tab\n * starts from now.\n */\n #since(after: string | null): EventsMessage | null {\n const current = `${this.#epoch}:${this.#seq}`\n if (!after) return {cursor: current, events: []}\n const [epoch, raw] = after.split(':')\n const seq = Number(raw)\n const oldest = this.#log[0]?.seq ?? this.#seq + 1\n if (epoch !== this.#epoch || !Number.isInteger(seq) || (seq < this.#seq && seq + 1 < oldest)) {\n return {cursor: current, events: [], reset: true}\n }\n const events = this.#log.filter((event) => event.seq > seq)\n if (!events.length) return null\n return {\n cursor: `${this.#epoch}:${events[events.length - 1].seq}`,\n events: events.map((e) => e.chunk),\n }\n }\n\n /**\n * WebSocket: `GET /socket?after=<cursor>` sends what the tab missed (or its starting cursor),\n * then each event as {@link #publish} logs it, with no request to wait for. The tab sends\n * `ping` every 20 s to keep the connection open through proxies; the hub answers `pong`.\n *\n * Plain `accept()` rather than hibernation: a hub with open sockets stays in memory with its\n * caches and upstream streams, as it does for waiting long polls.\n */\n #socket(request: Request): Response {\n if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {\n return new Response('Expected a WebSocket', {status: 426})\n }\n this.#touch()\n const {0: client, 1: server} = new WebSocketPair()\n ;(server as WebSocket & {accept(): void}).accept()\n // The storefront sets this only after checking the editor's live-edit session; this Worker\n // has no public URL, so a browser cannot send it.\n const edits = request.headers.get(LIVE_EDIT_HEADER) === '1'\n if (!edits) this.#sockets.add(server)\n const close = () => {\n this.#sockets.delete(server)\n this.#touch()\n }\n server.addEventListener('close', close)\n server.addEventListener('error', close)\n server.addEventListener('message', (event) => {\n if (event.data === 'ping') {\n server.send('pong')\n return\n }\n if (edits && typeof event.data === 'string') void this.#receiveEdit(event.data)\n })\n if (!edits) {\n const missed = this.#since(new URL(request.url).searchParams.get('after'))\n const message = missed ? this.#withPayloads(missed) : null\n server.send(JSON.stringify(message ?? {cursor: `${this.#epoch}:${this.#seq}`, events: []}))\n }\n return new Response(null, {status: 101, webSocket: client} as ResponseInit)\n }\n\n /** An unsaved Studio edit sent over a live-edit socket: `{ document, seq }`, a draft. */\n async #receiveEdit(data: string) {\n if (data.length > MAX_OVERLAY_BYTES || this.#perspective !== 'drafts') return\n try {\n const {document, seq} = JSON.parse(data) as {\n document?: {_id?: unknown; _type?: string}\n seq?: unknown\n }\n if (\n typeof document?._id !== 'string' ||\n !document._id.startsWith('drafts.') ||\n typeof seq !== 'number'\n ) {\n return\n }\n await this.#applyOverlay(document as {_id: string; _type?: string}, seq)\n } catch (error) {\n console.warn('[preview-hub] live edit failed', error)\n }\n }\n\n /**\n * Long poll: `GET /events?after=<cursor>` answers as soon as the log has events after the\n * cursor (see {@link #since}), or with none after {@link POLL_TIMEOUT_MS}.\n *\n * The request stays inside this handler until {@link #publish} wakes it. A streaming response\n * does not work here: once a handler has returned its `Response`, Workers did not run its\n * timers or flush its writes promptly, and SSE events reached tabs 0.7–4 s late (2026-11-23).\n */\n async #poll(request: Request): Promise<Response> {\n this.#touch()\n const after = new URL(request.url).searchParams.get('after')\n const json = (body: unknown) =>\n Response.json(body, {headers: {'cache-control': 'no-store, no-transform'}})\n\n this.#polling++\n try {\n const deadline = Date.now() + POLL_TIMEOUT_MS\n while (!request.signal?.aborted) {\n const message = this.#since(after)\n if (message) return json(this.#withPayloads(message))\n const left = deadline - Date.now()\n if (left <= 0) break\n await new Promise<void>((resolve) => {\n const wake = () => {\n clearTimeout(timer)\n this.#waiters.delete(wake)\n resolve()\n }\n const timer = setTimeout(wake, left)\n this.#waiters.add(wake)\n request.signal?.addEventListener('abort', wake, {once: true})\n })\n }\n return json({cursor: after, events: []})\n } finally {\n this.#polling--\n this.#touch()\n }\n }\n\n async #load(key: string, query: string, params: QueryParams): Promise<unknown> {\n const startedAt = Date.now()\n let response = await this.#fetchSanity(query, params)\n\n // A Live event that arrived while this fetch was in flight may postdate its result.\n const missed = this.#recentEvents.some(\n (event) =>\n event.at >= startedAt && event.tags.some((tag) => response.syncTags?.includes(tag)),\n )\n if (missed) response = await this.#fetchSanity(query, params)\n\n await this.#store(key, query, params, response.result, response.syncTags)\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n return response.result\n }\n\n /** Store a result. Returns whether its hash changed. `tags` defaults to the previous ones. */\n async #store(\n key: string,\n query: string,\n params: QueryParams,\n result: unknown,\n syncTags?: string[],\n ): Promise<boolean> {\n const previous = this.#entries.get(key)\n if (previous) this.#unindex(key, previous.tags)\n\n const entry: Entry = {\n query,\n params,\n result,\n hash: await hashJson(result),\n tags: syncTags ?? previous?.tags ?? [],\n docs: documentIds(result, params),\n local: previous?.local ?? 'unknown',\n mismatches: previous?.mismatches ?? 0,\n retryAt: previous?.retryAt ?? 0,\n usedAt: Date.now(),\n }\n this.#entries.set(key, entry)\n for (const tag of entry.tags) {\n let keys = this.#byTag.get(tag)\n if (!keys) this.#byTag.set(tag, (keys = new Set()))\n keys.add(key)\n }\n this.#evict()\n const changed = previous?.hash !== entry.hash\n // Only Sanity results reach an `off` entry here (local re-evaluation skips them).\n if (changed && entry.local === 'off' && Date.now() >= entry.retryAt) {\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n }\n return changed\n }\n\n #unindex(key: string, tags: string[]) {\n for (const tag of tags) {\n const keys = this.#byTag.get(tag)\n keys?.delete(key)\n if (keys && !keys.size) this.#byTag.delete(tag)\n }\n }\n\n #evict() {\n if (this.#entries.size <= MAX_ENTRIES) return\n const oldest = [...this.#entries].sort((a, b) => a[1].usedAt - b[1].usedAt)\n for (const [key, entry] of oldest.slice(0, this.#entries.size - MAX_ENTRIES)) {\n this.#unindex(key, entry.tags)\n this.#entries.delete(key)\n }\n }\n\n /** Run hub work one task at a time per chain; the chains run independently. */\n #queue(chain: 'local' | 'sweep' | 'verify', task: () => Promise<void>) {\n this.#chains[chain] = this.#chains[chain].then(task).catch((error) => {\n console.warn(`[preview-hub] ${chain} task failed`, error)\n })\n }\n\n /** Evaluate a query locally; `null` when the mirror cannot answer it. */\n async #evaluateLocal(entry: Entry): Promise<unknown | null> {\n await this.#mirror.ready()\n await this.#mirror.ensure(entry.docs)\n // Products a page references only through a `*[_type == 'product' && _id in …]` scan.\n await this.#mirror.ensure(this.#mirror.referencesOf(entry.docs))\n let result = await this.#mirror.evaluate(entry.query, entry.params, this.#perspective)\n // The result may now name documents (products) the mirror does not hold yet.\n const ids = documentIds(result, entry.params)\n if (!this.#mirror.covers(ids)) {\n await this.#mirror.ensure(ids)\n result = await this.#mirror.evaluate(entry.query, entry.params, this.#perspective)\n }\n return result\n }\n\n /** Trust a query's local evaluation only if it reproduces Sanity's result exactly. */\n async #verify(key: string) {\n // Sanity's result lacks unsaved edits, so verifying an overlaid query would always fail.\n const overlaid = this.#entries.get(key)\n if (overlaid && this.#mirror.overlaid(overlaid.docs)) {\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n return\n }\n // Experiment switch: `LOCAL_EVAL = \"off\"` keeps every query on the Live API refetch path.\n if ((this.env as {LOCAL_EVAL?: string}).LOCAL_EVAL === 'off') return\n const entry = this.#entries.get(key)\n if (!entry || entry.local === 'ok') return\n try {\n const local = await this.#evaluateLocal(entry)\n const matches = (await hashJson(local)) === entry.hash\n // A refetch stored a newer result while this one evaluated: judge that one instead.\n if (this.#entries.get(key) !== entry) {\n this.#verifyPending.add(key)\n this.#scheduleVerify()\n return\n }\n if (matches) {\n entry.local = 'ok'\n entry.mismatches = 0\n entry.retryAt = 0\n } else {\n markOff(entry)\n this.#lastVerifyNote = `${key} ${firstDifference(entry.result, local)}`.slice(0, 300)\n console.log(\n '[preview-hub] local result differs; refetch only',\n key,\n firstDifference(entry.result, local),\n )\n }\n } catch (error) {\n markOff(entry)\n this.#lastVerifyNote = `${key} error ${String(error)}`.slice(0, 300)\n console.log('[preview-hub] local evaluation unsupported; refetch only', key, String(error))\n }\n }\n\n /**\n * After mirror mutations: re-evaluate the trusted queries whose results name an edited\n * document, and publish the ones that changed. Every other trusted query is re-evaluated\n * {@link REST_DELAY_MS} after edits stop: some are slow (the Makers list takes ~600 ms of CPU),\n * and running them now would make the tab's refresh requests, ~100 ms later, wait behind them.\n * The Live API sweep checks them against Sanity too.\n */\n async #flushLocal() {\n const started = Date.now()\n const edited = this.#editedDocs\n this.#editedDocs = new Set()\n\n const evaluated: string[] = []\n for (const [key, entry] of this.#entries) {\n if (entry.local !== 'ok') continue\n if (!entry.docs.some((id) => edited.has(id))) {\n this.#restPending.add(key)\n continue\n }\n evaluated.push(key)\n this.#restPending.delete(key)\n // Each result goes out as soon as it is ready, not after the slowest query.\n if (await this.#reevaluate(key, entry)) await this.#publish([key], 'local')\n }\n this.#lastLocalFlush = {\n queuedMs: started - this.#lastMutationAt,\n firstMs: Date.now() - started,\n evaluated,\n }\n\n if (this.#restTimer) clearTimeout(this.#restTimer)\n this.#restTimer = setTimeout(() => {\n this.#restTimer = null\n this.#queue('local', () => this.#flushRest())\n }, REST_DELAY_MS)\n }\n\n /** Re-evaluate the trusted queries the last edits did not name directly. */\n async #flushRest() {\n const keys = [...this.#restPending]\n this.#restPending.clear()\n const changed: string[] = []\n for (const key of keys) {\n const entry = this.#entries.get(key)\n if (!entry || entry.local !== 'ok') continue\n // `groq-js` runs as one long chain of microtasks; yield between queries so requests and\n // stream writes are not held until every evaluation is done.\n await yieldToEventLoop()\n if (await this.#reevaluate(key, entry)) changed.push(key)\n }\n await this.#publish(changed, 'rest')\n }\n\n /** Evaluate one trusted query locally and store it. Returns whether its result changed. */\n async #reevaluate(key: string, entry: Entry): Promise<boolean> {\n try {\n const result = await this.#evaluateLocal(entry)\n return await this.#store(key, entry.query, entry.params, result)\n } catch (error) {\n markOff(entry)\n console.warn('[preview-hub] local evaluation failed', key, error)\n return false\n }\n }\n\n #restPending = new Set<string>()\n #restTimer: ReturnType<typeof setTimeout> | null = null\n #lastLocalFlush: unknown = null\n\n async #fetchSanity(query: string, params: QueryParams): Promise<QueryResponse> {\n const url = this.#sanityUrl('query')\n url.searchParams.set('perspective', this.#perspective)\n url.searchParams.set('returnQuery', 'false')\n // Ask for results at least as new as the last Live event this hub has seen.\n if (this.#lastEventId) url.searchParams.set('lastLiveEventId', this.#lastEventId)\n return this.#post(url, query, params)\n }\n\n /** Raw perspective (published, drafts and versions as stored), for the mirror. */\n async #fetchRaw(query: string, params: QueryParams = {}): Promise<unknown> {\n const url = this.#sanityUrl('query')\n url.searchParams.set('perspective', 'raw')\n url.searchParams.set('returnQuery', 'false')\n return (await this.#post(url, query, params)).result\n }\n\n async #post(url: URL, query: string, params: QueryParams): Promise<QueryResponse> {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${this.env.SANITY_API_READ_TOKEN}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({query, params}),\n })\n if (!response.ok) {\n throw new Error(`Sanity query failed: HTTP ${response.status} ${await response.text()}`)\n }\n return response.json()\n }\n\n #sanityUrl(path: string): URL {\n const {SANITY_PROJECT_ID, SANITY_DATASET, SANITY_API_VERSION} = this.env\n return new URL(\n `https://${SANITY_PROJECT_ID}.api.sanity.io/v${SANITY_API_VERSION}/data/${path}/${SANITY_DATASET}`,\n )\n }\n\n #ensureUpstream() {\n if (this.#upstream) return\n const controller = new AbortController()\n this.#upstream = controller\n void this.#followListener(controller.signal)\n void this.#followLive(controller.signal)\n\n this.#idleTimer ??= setInterval(() => this.#checkIdle(), IDLE_CHECK_MS)\n }\n\n /**\n * Keep one Server-Sent Events stream from Sanity open until `signal` aborts, reconnecting with\n * exponential backoff. `onEvent` returns `false` to drop the connection and reconnect.\n */\n async #follow(\n name: string,\n signal: AbortSignal,\n connect: () => {url: URL; headers?: Record<string, string>},\n onEvent: (event: SseEvent) => boolean | void,\n ) {\n let backoff = 1_000\n const status = (this.#streamStatus[name] = {connects: 0, events: 0, error: ''})\n while (!signal.aborted) {\n try {\n status.connects++\n const {url, headers} = connect()\n const response = await fetch(url, {\n headers: {\n authorization: `Bearer ${this.env.SANITY_API_READ_TOKEN}`,\n accept: 'text/event-stream',\n // Uncompressed: a compressed event stream can be held in the decompressor\n // until more bytes arrive, delaying each event until the next one.\n 'accept-encoding': 'identity',\n ...headers,\n },\n signal,\n })\n if (!response.ok || !response.body) {\n throw new Error(`HTTP ${response.status} ${(await response.text()).slice(0, 200)}`)\n }\n backoff = 1_000\n for await (const event of parseSse(response.body)) {\n status.events++\n if (event.event === 'channelError') status.error = event.data.slice(0, 200)\n if (onEvent(event) === false) break\n }\n } catch (error) {\n if (signal.aborted) return\n status.error = String(error).slice(0, 200)\n console.warn(`[preview-hub] ${name} stream failed`, error)\n }\n if (signal.aborted) return\n await new Promise((resolve) => setTimeout(resolve, backoff))\n backoff = Math.min(backoff * 2, 30_000)\n }\n }\n\n /** Fast path: `/listen` mutation results, applied to the mirror as soon as they commit. */\n #followListener(signal: AbortSignal) {\n let connected = false\n return this.#follow(\n 'Listener',\n signal,\n () => {\n const url = this.#sanityUrl('listen')\n url.searchParams.set('query', this.#mirror.listenQuery)\n url.searchParams.set('includeResult', 'true')\n url.searchParams.set('visibility', 'transaction')\n url.searchParams.set('includeAllVersions', 'true')\n url.searchParams.set('tag', 'preview-hub')\n return {url}\n },\n (event) => {\n if (event.event === 'welcome') {\n // The listener cannot replay what it missed while disconnected: start the mirror\n // over and re-verify every query against Sanity.\n if (connected) this.#resetLocal()\n connected = true\n } else if (event.event === 'mutation') {\n const {documentId, transition, result} = JSON.parse(event.data) as {\n documentId: string\n transition: string\n result?: {_id: string; _type?: string}\n }\n if (this.#mirror.loaded && this.#mirror.apply(documentId, result, transition)) {\n this.#lastMutationAt = Date.now()\n this.#editedDocs.add(baseId(documentId))\n this.#scheduleLocal()\n }\n } else if (['reconnect', 'disconnect', 'channelError'].includes(event.event)) {\n if (event.event === 'channelError') {\n console.warn('[preview-hub] Listener channel error', event.data)\n }\n return false\n }\n },\n )\n }\n\n /** Authority: Live Content API sync tags, ~1 s after each write; replays from its event ID. */\n #followLive(signal: AbortSignal) {\n return this.#follow(\n 'Live Content API',\n signal,\n () => {\n const url = this.#sanityUrl('live/events')\n url.searchParams.set('includeDrafts', 'true')\n return {\n url,\n headers: this.#lastEventId ? {'last-event-id': this.#lastEventId} : undefined,\n }\n },\n (event) => {\n if (event.id) this.#lastEventId = event.id\n if (event.event === 'message') {\n const {tags} = JSON.parse(event.data) as {tags?: string[]}\n if (tags?.length) this.#onTags(tags)\n } else if (event.event === 'restart') {\n // The API lost track of what changed: refetch everything held.\n this.#onTags([...this.#byTag.keys()])\n } else if (event.event === 'reconnect') {\n return false\n }\n },\n )\n }\n\n /**\n * Unsaved Studio edits (LF-INIT-21): the `live-edit` Studio plugin posts the open document's\n * form value through the storefront. It shows in the mirror until the saved document catches\n * up or it goes stale, and trusted queries re-evaluate at once.\n */\n async #applyOverlay(doc: {_id: string; _type?: string}, seq: number): Promise<boolean> {\n this.#touch()\n this.#ensureUpstream()\n await this.#mirror.ready()\n if (!this.#mirror.overlay(doc, seq)) return false\n this.#lastMutationAt = Date.now()\n this.#editedDocs.add(baseId(doc._id))\n this.#flushLocalNow()\n this.#overlayTimer ??= setInterval(() => {\n for (const base of this.#mirror.expireOverlays(OVERLAY_TTL_MS)) this.#editedDocs.add(base)\n if (this.#editedDocs.size) this.#scheduleLocal()\n if (!this.#mirror.overlayCount && this.#overlayTimer) {\n clearInterval(this.#overlayTimer)\n this.#overlayTimer = null\n }\n }, 1_000)\n return true\n }\n\n #overlayTimer: ReturnType<typeof setInterval> | null = null\n\n #verifyPending = new Set<string>()\n #verifyTimer: ReturnType<typeof setTimeout> | null = null\n\n /** Verify pending queries once reads have paused for VERIFY_DELAY_MS, yielding between them. */\n #scheduleVerify() {\n if (this.#verifyTimer) clearTimeout(this.#verifyTimer)\n this.#verifyTimer = setTimeout(() => {\n this.#verifyTimer = null\n const keys = [...this.#verifyPending]\n this.#verifyPending.clear()\n this.#queue('verify', async () => {\n for (const key of keys) {\n await yieldToEventLoop()\n await this.#verify(key)\n }\n })\n }, VERIFY_DELAY_MS)\n }\n\n #resetLocal() {\n this.#mirror.clear()\n for (const [key, entry] of this.#entries) {\n entry.local = 'unknown'\n entry.mismatches = 0\n entry.retryAt = 0\n this.#verifyPending.add(key)\n }\n this.#scheduleVerify()\n }\n\n #localQueued = false\n\n /**\n * Re-evaluate on the local chain's next turn, with no timer: an editor is typing, and on Workers\n * a Durable Object's timers can fire late. Listener mutations keep {@link #scheduleLocal},\n * which coalesces a save's burst of documents.\n */\n #flushLocalNow() {\n if (this.#localQueued) return\n this.#localQueued = true\n this.#queue('local', async () => {\n this.#localQueued = false\n await this.#flushLocal()\n })\n }\n\n #scheduleLocal() {\n if (this.#localTimer) return\n this.#localTimer = setTimeout(() => {\n this.#localTimer = null\n this.#queue('local', () => this.#flushLocal())\n }, LOCAL_DELAY_MS)\n }\n\n #onTags(tags: string[]) {\n this.#recentEvents.push({at: Date.now(), tags})\n if (this.#recentEvents.length > RECENT_EVENTS) this.#recentEvents.shift()\n\n for (const tag of tags) this.#pendingTags.add(tag)\n if (this.#flushTimer) return\n this.#flushTimer = setTimeout(() => {\n this.#flushTimer = null\n this.#queue('sweep', () => this.#flush())\n }, FLUSH_DELAY_MS)\n }\n\n /** Refetch the results a Live event's sync tags name, from Sanity. */\n async #flush() {\n const tags = [...this.#pendingTags]\n this.#pendingTags.clear()\n\n const keys = new Set<string>()\n for (const tag of tags) for (const key of this.#byTag.get(tag) ?? []) keys.add(key)\n if (!keys.size) return\n\n // Every matching result is refetched, locally evaluated or not. In production `/listen`\n // events sometimes reach the hub late (2026-11-23), so this refetch is what bounds an\n // update at ~1.4 s when the fast path is held up.\n const changed: string[] = []\n await Promise.all(\n [...keys].map(async (key) => {\n const entry = this.#entries.get(key)\n if (!entry) return\n // The refetch lacks unsaved edits; applying it would flicker the page back mid-typing.\n if (entry.local === 'ok' && this.#mirror.overlaid(entry.docs)) return\n try {\n const response = await this.#fetchSanity(entry.query, entry.params)\n const didChange = await this.#store(\n key,\n entry.query,\n entry.params,\n response.result,\n response.syncTags,\n )\n if (didChange) changed.push(key)\n } catch (error) {\n // Drop the entry so the next read refetches instead of serving stale data.\n console.warn('[preview-hub] refetch failed', key, error)\n this.#unindex(key, entry.tags)\n this.#entries.delete(key)\n changed.push(key)\n }\n }),\n )\n await this.#publish(changed, 'sweep')\n }\n\n async #publish(changed: string[], source: 'local' | 'rest' | 'sweep') {\n if (!changed.length) return\n const chunk: PreviewInvalidation = {keys: changed.sort(), at: Date.now(), source}\n const seq = ++this.#seq\n this.#log.push({seq, chunk})\n if (this.#log.length > LOG_SIZE) this.#log.shift()\n\n // Push to WebSockets at once, with the new results, then wake the waiting long polls.\n if (!this.#sockets.size) {\n for (const wake of [...this.#waiters]) wake()\n return\n }\n const message = JSON.stringify({\n cursor: `${this.#epoch}:${seq}`,\n events: [{...chunk, ...this.#payload(changed)}],\n })\n for (const socket of this.#sockets) {\n try {\n socket.send(message)\n } catch {\n this.#sockets.delete(socket)\n }\n }\n for (const wake of [...this.#waiters]) wake()\n }\n\n /** The current results (under {@link MAX_PUSH_BYTES}) and labels of changed keys. */\n #payload(keys: string[]): Required<Pick<PreviewInvalidation, 'results' | 'labels'>> {\n const results: Record<string, unknown> = {}\n const labels: Record<string, string[]> = {}\n for (const key of keys) {\n const names = this.#labels.get(key)\n if (names?.size) labels[key] = [...names]\n const entry = this.#entries.get(key)\n if (!entry) continue\n const json = JSON.stringify(entry.result ?? null)\n if (json.length <= MAX_PUSH_BYTES) results[key] = entry.result ?? null\n }\n return {results, labels}\n }\n\n /**\n * Logged events (keys alone) with payloads, for a tab catching up. Each key's current result\n * and labels go on the last event that names it: a tab applies events in order, and a later\n * event supersedes an earlier one. The log's events are not modified.\n */\n #withPayloads(message: EventsMessage): EventsMessage {\n const seen = new Set<string>()\n const events: PreviewInvalidation[] = []\n for (let i = message.events.length - 1; i >= 0; i--) {\n const event = message.events[i]\n const keys = event.keys.filter((key) => !seen.has(key))\n for (const key of keys) seen.add(key)\n events.unshift({...event, ...this.#payload(keys)})\n }\n return {...message, events}\n }\n\n #touch() {\n this.#lastActive = Date.now()\n }\n\n #checkIdle() {\n if (this.#polling > 0 || this.#sockets.size > 0 || Date.now() - this.#lastActive < IDLE_MS) {\n return\n }\n\n this.#upstream?.abort()\n this.#upstream = null\n if (this.#idleTimer) clearInterval(this.#idleTimer)\n this.#idleTimer = null\n this.#entries.clear()\n this.#byTag.clear()\n this.#labels.clear()\n this.#mirror.clear()\n }\n}\n\n/**\n * Stop trusting a query's local evaluation (it differed from Sanity's result, or failed), and\n * back off before checking it again: {@link RETRY_BASE_MS}, doubling per miss.\n */\nfunction markOff(entry: Entry) {\n entry.local = 'off'\n entry.mismatches++\n entry.retryAt = Date.now() + Math.min(RETRY_BASE_MS * 2 ** (entry.mismatches - 1), RETRY_MAX_MS)\n}\n\n/**\n * Base IDs of every `_id` and `_ref` anywhere in a result, plus every string in the params\n * (`getSections({ id })` returns no `_id` of its own). A param that is not a document ID only\n * adds a name the mirror marks as missing.\n */\nfunction documentIds(result: unknown, params: QueryParams): string[] {\n const found = new Set<string>()\n const walk = (value: unknown) => {\n if (Array.isArray(value)) {\n for (const item of value) walk(item)\n } else if (value && typeof value === 'object') {\n for (const [field, child] of Object.entries(value)) {\n if ((field === '_id' || field === '_ref') && typeof child === 'string') {\n found.add(baseId(child))\n } else {\n walk(child)\n }\n }\n }\n }\n walk(result)\n\n const walkParams = (value: unknown) => {\n if (typeof value === 'string') found.add(baseId(value))\n else if (Array.isArray(value)) value.forEach(walkParams)\n else if (value && typeof value === 'object') Object.values(value).forEach(walkParams)\n }\n walkParams(params)\n return [...found]\n}\n\n/** The first path where two JSON values differ, for logging why a local result was rejected. */\nfunction firstDifference(a: unknown, b: unknown, path = '$'): string | null {\n if (canonicalJson(a) === canonicalJson(b)) return null\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)])\n for (const key of keys) {\n const diff = firstDifference(\n (a as Record<string, unknown>)[key],\n (b as Record<string, unknown>)[key],\n `${path}.${key}`,\n )\n if (diff) return diff\n }\n }\n const show = (value: unknown) => JSON.stringify(value)?.slice(0, 80)\n return `${path}: sanity=${show(a)} local=${show(b)}`\n}\n\nfunction yieldToEventLoop(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0))\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const digest = new Uint8Array(\n await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input)),\n )\n return Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Stable key for a query and its params. */\nfunction fingerprint(query: string, params: QueryParams): Promise<string> {\n return sha256Hex(JSON.stringify([query, sortKeys(params)]))\n}\n\n/**\n * Hash of a result with object keys sorted. Sanity returns keys sorted and `groq-js` in projection\n * order, so a raw `JSON.stringify` would make every local result look different.\n */\nfunction hashJson(value: unknown): Promise<string> {\n return sha256Hex(canonicalJson(value))\n}\n\nfunction canonicalJson(value: unknown): string {\n return (\n JSON.stringify(value, (_key, child: unknown) =>\n child && typeof child === 'object' && !Array.isArray(child)\n ? Object.fromEntries(Object.entries(child).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : child,\n ) ?? 'undefined'\n )\n}\n\nfunction sortKeys(params: QueryParams): QueryParams {\n return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b)))\n}\n\n/** Header carrying the preview perspective, e.g. `drafts` or `rABC,drafts`. */\nconst PERSPECTIVE_HEADER = 'x-preview-perspective'\n\n/**\n * Entry point for the storefront's service binding (this Worker has no public URL). It picks the\n * hub for the request's perspective with `getByName()` here, inside this Worker, so the instance\n * can read its perspective from `ctx.id.name`. Through Vite dev's platform proxy, a Durable\n * Object stub reached directly from the storefront arrives without its name.\n */\nexport default {\n fetch(request: Request, env: PreviewHubEnv) {\n const perspective = request.headers.get(PERSPECTIVE_HEADER) ?? 'drafts'\n if (!/^[\\w.,-]{1,256}$/.test(perspective) || ['raw', 'published'].includes(perspective)) {\n return new Response('Invalid perspective', {status: 400})\n }\n // One instance per deployed version: an instance with open upstream streams is not\n // restarted on deploy and would keep running the old code. The old instance shuts down\n // once it has had no tabs and no reads for IDLE_MS.\n return env.PREVIEW_HUB.getByName(`${perspective}|${env.CF_VERSION_METADATA.id}`).fetch(request)\n },\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,WAAW,MAAwD;CACjF,IAAM,0BAAU,IAAI,IAAuB;CAE3C,OAAO;EAAC,MADUA,UAAQ,MAAyB,OAC7B;EAA0B,SAAS,CAAC,GAAG,QAAQ,OAAO,CAAC;CAAC;AAChF;AAEA,SAASA,UAAQ,MAAY,SAAuC;CAClE,IAAM,OAAa,EAAC,GAAG,KAAI;CAC3B,KAAK,IAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GACxC,MAAM,QAAQ,KAAK,IACrB,KAAK,OAAO,MAAM,KAAK,SAAUC,SAAO,IAAI,IAAID,UAAQ,MAAM,OAAO,IAAI,IAAK,IACrEC,SAAO,KAAK,MACrB,KAAK,OAAOD,UAAQ,OAAO,OAAO;CAGtC,IAAI,KAAK,SAAS,YAAa,KAAK,KAAc,SAAS,cAAc,OAAO;CAEhF,IAAM,OAAO,SAAS,UAAU,KAAK,IAAY,CAAC;CAClD,IAAI,CAAC,MAAM,OAAO;CAClB,IAAM,QAAQ,WAAW,KAAK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ACzF;;;;;;;AAWA,IAAA,qBAAe,EACb,MAAM,SAAkB,KAAoB;CAC1C,IAAM,cAAc,QAAQ,QAAQ,IAAI,uBAAkB,KAAK;CAO/D,OANI,CAAC,mBAAmB,KAAK,WAAW,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC,SAAS,WAAW,IAC7E,IAAI,SAAS,uBAAuB,EAAC,QAAQ,IAAG,CAAC,IAKnD,IAAI,YAAY,UAAU,GAAG,YAAY,GAAG,IAAI,oBAAoB,IAAI,CAAC,CAAC,MAAM,OAAO;AAChG,EACF"}
|
|
@@ -278,7 +278,11 @@ const PREVIEW_SOCKET_PATH = "/api/preview/socket", PREVIEW_EVENTS_PATH = "/api/p
|
|
|
278
278
|
* with no keys (`keys: []`): refresh everything. Returns a function that stops following.
|
|
279
279
|
*/
|
|
280
280
|
function subscribePreviewEvents(onChange, options) {
|
|
281
|
-
let socketPath = options?.socketPath ?? "/api/preview/socket", eventsPath = options?.eventsPath ?? "/api/preview/events", onStatus = options?.onStatus,
|
|
281
|
+
let socketPath = options?.socketPath ?? "/api/preview/socket", eventsPath = options?.eventsPath ?? "/api/preview/events", onStatus = options?.onStatus, params = options?.params ?? {}, urlFor = (path) => {
|
|
282
|
+
let url = new URL(path, location.href);
|
|
283
|
+
for (let [key, value] of Object.entries(params)) url.searchParams.set(key, value);
|
|
284
|
+
return cursor && url.searchParams.set("after", cursor), url;
|
|
285
|
+
}, controller = new AbortController(), cursor = "", socket = null, ping, retry, wake, timer, pending = /* @__PURE__ */ new Set(), results = {}, labels = {}, status = null, setStatus = (next) => {
|
|
282
286
|
status !== next && (status = next, onStatus?.(next));
|
|
283
287
|
}, sleep = (ms) => new Promise((resolve) => {
|
|
284
288
|
wake = resolve, retry = setTimeout(() => {
|
|
@@ -302,8 +306,8 @@ function subscribePreviewEvents(onChange, options) {
|
|
|
302
306
|
pending.size && !timer && (timer = setTimeout(flush, 0));
|
|
303
307
|
}, openSocket = (failures) => {
|
|
304
308
|
if (controller.signal.aborted) return;
|
|
305
|
-
let url =
|
|
306
|
-
url.protocol = url.protocol === "https:" ? "wss:" : "ws:"
|
|
309
|
+
let url = urlFor(socketPath);
|
|
310
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
307
311
|
let opened = !1, timedOut = !1, ws = new WebSocket(url);
|
|
308
312
|
socket = ws;
|
|
309
313
|
let openTimeout = setTimeout(() => {
|
|
@@ -323,7 +327,7 @@ function subscribePreviewEvents(onChange, options) {
|
|
|
323
327
|
}, poll = async () => {
|
|
324
328
|
let fails = 0;
|
|
325
329
|
for (setStatus("polling"); !controller.signal.aborted;) try {
|
|
326
|
-
let
|
|
330
|
+
let response = await fetch(urlFor(eventsPath), {
|
|
327
331
|
credentials: "same-origin",
|
|
328
332
|
signal: controller.signal
|
|
329
333
|
});
|
|
@@ -612,4 +616,4 @@ function connectVisualEditor(options) {
|
|
|
612
616
|
}
|
|
613
617
|
export { panelClipPath as a, subscribePreviewEvents as c, mountPreviewBarHost as i, findSanityTarget as l, isTopWindow as n, PREVIEW_EVENTS_PATH as o, mountPreviewBarFrame as r, PREVIEW_SOCKET_PATH as s, connectVisualEditor as t, mountClickToEdit as u };
|
|
614
618
|
|
|
615
|
-
//# sourceMappingURL=host-
|
|
619
|
+
//# sourceMappingURL=host-x2eXr-LJ.js.map
|