output.test.mjs (747222B)
1 import assert from 'node:assert/strict'; 2 import { createHash } from 'node:crypto'; 3 import { execFileSync } from 'node:child_process'; 4 import { 5 cp, 6 link, 7 lstat, 8 mkdir, 9 mkdtemp, 10 readFile, 11 realpath, 12 rm, 13 symlink, 14 writeFile 15 } from 'node:fs/promises'; 16 import os from 'node:os'; 17 import path from 'node:path'; 18 import { performance } from 'node:perf_hooks'; 19 import { test } from 'node:test'; 20 import { fileURLToPath } from 'node:url'; 21 import { generateBuildInfo } from '../../tools/build-info.mjs'; 22 import { auditOutput } from '../../tools/check-output.mjs'; 23 24 // Slow-host verification allows1800s for each setup/copy/compiler/audit test. 25 // Vite children and admission checks keep1800s within their1800s group. 26 // Serial top-level tests keep compatibility work out of the mutation budget. 27 { 28 const source = fileURLToPath(new URL('../../../', import.meta.url)); 29 // Exact HCP043 product shell bytes, immutable compatibility evidence only. 30 const historicalProduct = 31 '<svelte:head><title>Food — HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>Food</h1>\n <p class="notice">Food details are unavailable during development.</p>\n</div>\n'; 32 // Exact unchanged118 producer closure for historical compatibility variants. 33 // Restore before the immutable older overlays; no ancestor Git runtime dependency. 34 /** @type {Record<string, {source:string, sha256:string}>} */ 35 const historicalPublicProducerClosure = { 36 'src/lib/publishing/prepare-listing.ts': { 37 source: 38 "import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport type {\n PublicDraftRecord,\n PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId, newLocalId } from '../private-handles.ts';\nimport { readRelayPolicy, publicRelayTargets } from '../config/relays.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n decodePublicRecord,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n publicPublicationOwner,\n publicPublicationDraftRepository,\n savePublicListingIntent,\n type PublicPublicationRepository,\n type PublicListingSave\n} from '../persistence/public-publications.ts';\nimport {\n publicDraftControllerOwnership,\n publicDraftControllerSnapshot,\n flushPublicDraft,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n newListingReadinessOwnership,\n type NewListingReadiness\n} from './new-listing-readiness.ts';\n\ndeclare const reviewBrand: unique symbol;\nexport type ListingReview = Readonly<{ [reviewBrand]: true }>;\nexport type ListingPreview = Readonly<{\n owner: string;\n command: string;\n draftId: string;\n draftRevision: number;\n identifier: string;\n createdAtSeconds: number;\n form: PublicDraftForm;\n summary: string;\n templateWire: string;\n expectedHash: string;\n targets: readonly string[];\n policyFingerprint: string;\n}>;\ntype Review = Readonly<{\n repository: PublicPublicationRepository;\n controller: PublicDraftController;\n expected: PublicDraftRecord;\n editVersion: number;\n command: string;\n readiness: NewListingReadiness;\n record: PublicRecordHandle;\n previewWire: string;\n current(this: void): boolean;\n}>;\nconst reviews = new WeakMap<ListingReview, Review>();\nconst commands = new WeakMap<\n PublicPublicationRepository,\n Map<string, ListingReview>\n>();\nconst activeReservations = new WeakMap<\n ListingReview,\n Promise<ListingReservation>\n>();\nexport type ListingReviewResult =\n | Readonly<{ status: 'review'; review: ListingReview }>\n | Readonly<{\n status: 'blocked';\n reason:\n | 'invalid_scope'\n | 'invalid_command'\n | 'unavailable'\n | 'invalid_form'\n | 'conflict';\n }>;\nexport type ListingReservation =\n PublicListingSave | Readonly<{ status: 'invalid' }>;\n// Review flushes local draft state and prepares an exact immutable template;\n// it neither reserves a publication nor asks the extension to sign.\nexport async function reviewNewListing(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n readiness: NewListingReadiness,\n command: unknown,\n consent: unknown\n): Promise<ListingReviewResult> {\n try {\n const custody = publicDraftControllerOwnership(controller),\n owner = publicPublicationOwner(repository);\n if (\n !custody ||\n !owner ||\n custody.repository !== publicPublicationDraftRepository(repository)\n )\n return { status: 'blocked', reason: 'invalid_scope' };\n const id = canonicalLocalId(command);\n if (!id) return { status: 'blocked', reason: 'invalid_command' };\n const ready = newListingReadinessOwnership(readiness);\n if (\n !ready ||\n ready.owner !== owner ||\n !ready.current() ||\n consent !== 'reviewed_new_listing'\n )\n return { status: 'blocked', reason: 'unavailable' };\n if (!(await flushPublicDraft(controller)))\n return { status: 'blocked', reason: 'unavailable' };\n const snapshot = publicDraftControllerSnapshot(controller),\n expected = snapshot?.draft;\n if (\n !snapshot ||\n !expected ||\n expected.owner !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n const cached = commands.get(repository)?.get(id);\n if (cached) {\n const original = reviews.get(cached);\n if (\n original &&\n original.controller === controller &&\n original.readiness === readiness &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n ) {\n return { status: 'review', review: cached };\n }\n return { status: 'blocked', reason: 'conflict' };\n }\n const identifier = newLocalId(),\n createdAtSeconds = Math.floor(Date.now() / 1000);\n if (!identifier) return { status: 'blocked', reason: 'unavailable' };\n const form = expected.form;\n if (form.contactType === '' && form.contactValue !== '')\n return { status: 'blocked', reason: 'invalid_form' };\n const contact =\n form.contactType === ''\n ? undefined\n : {\n type: form.contactType,\n value: form.contactValue,\n public: true as const\n };\n const built = buildFoodTemplate({\n identifier,\n title: form.title,\n description: form.description,\n location: form.location,\n amount: form.amount,\n currency: form.currency,\n unit: form.unit,\n ...(form.quantity === '' ? {} : { quantity: form.quantity }),\n created_at: createdAtSeconds,\n published_at: createdAtSeconds,\n status: 'active',\n ...(contact ? { contact } : {})\n });\n if (!built.ok) return { status: 'blocked', reason: 'invalid_form' };\n const manifest = readRelayPolicy(ready.policy),\n targets = publicRelayTargets(ready.policy, 'write');\n const templateWire = JSON.stringify({\n pubkey: owner,\n kind: 30402,\n created_at: createdAtSeconds,\n tags: built.wire_parts.tags,\n content: built.wire_parts.content\n });\n const template = inspectLocalTemplate(templateWire, owner, 30402);\n if (!template || !manifest.postingEnabled || targets.length === 0)\n return { status: 'blocked', reason: 'unavailable' };\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(manifest))\n );\n const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>\n value.toString(16).padStart(2, '0')\n ).join('');\n // Hashing is outside any IDB transaction; recheck original mutable owners.\n if (\n !ready.current() ||\n publicPublicationOwner(repository) !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n // Another review may have completed while this one awaited hashing. The\n // first retained command owns its ID/time/template; never replace it.\n const racing = commands.get(repository)?.get(id);\n if (racing) {\n const original = reviews.get(racing);\n if (\n original &&\n original.controller === controller &&\n original.readiness === readiness &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'review', review: racing };\n return { status: 'blocked', reason: 'conflict' };\n }\n const admitted = decodePublicRecord(\n JSON.stringify({\n schema: 1,\n family: 'public_operation',\n owner,\n id,\n revision: 0,\n source: { type: 'draft', id: expected.id, revision: expected.revision },\n capture: {\n kind: 30402,\n wire: templateWire,\n hash: template.hash,\n targets,\n policyFingerprint\n },\n artifact: null,\n receipts: []\n }),\n owner,\n id\n );\n if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' };\n const review = Object.freeze({}) as ListingReview;\n reviews.set(review, {\n repository,\n controller,\n expected,\n editVersion: snapshot.editVersion,\n command: id,\n readiness,\n record: admitted.value,\n previewWire: JSON.stringify({\n owner,\n command: id,\n draftId: expected.id,\n draftRevision: expected.revision,\n identifier,\n createdAtSeconds,\n form,\n summary: built.summary,\n templateWire,\n expectedHash: template.hash,\n targets,\n policyFingerprint\n }),\n current: () =>\n ready.current() && publicPublicationOwner(repository) === owner\n });\n const cache = commands.get(repository) ?? new Map<string, ListingReview>();\n cache.set(id, review);\n commands.set(repository, cache);\n return { status: 'review', review };\n } catch {\n return { status: 'blocked', reason: 'unavailable' };\n }\n}\nexport function listingReviewSnapshot(\n review: ListingReview\n): ListingPreview | undefined {\n const value = reviews.get(review);\n return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;\n}\n// Internal original custody, not a signing or transport permission. The later\n// controller must reread the persisted intent and obtain its own effect lease.\nexport function listingReviewOwnership(review: ListingReview) {\n const original = reviews.get(review);\n const ready = original && newListingReadinessOwnership(original.readiness);\n return original && ready && original.current()\n ? {\n repository: original.repository,\n record: original.record,\n command: original.command,\n readiness: ready,\n current: original.current\n }\n : undefined;\n}\n// One original review deduplicates simultaneous clicks. Failed/uncertain work\n// remains the same capture for later explicit retry; no fresh ID/time/template.\nexport function reserveNewListing(\n review: ListingReview,\n consent: unknown\n): Promise<ListingReservation> {\n const value = reviews.get(review);\n if (!value || consent !== 'publish_reviewed_listing')\n return Promise.resolve({ status: 'invalid' });\n const active = activeReservations.get(review);\n if (active) return active;\n const work = savePublicListingIntent(\n value.repository,\n value.controller,\n value.record,\n value.expected,\n value.editVersion,\n value.command,\n value.current\n ).finally(() => {\n if (activeReservations.get(review) === work)\n activeReservations.delete(review);\n });\n activeReservations.set(review, work);\n return work;\n}\n", 39 sha256: 'a362b18fce125b16d9f488b702cecdda1fc683f8feab25b9dca368712a40fd4e' 40 }, 41 'src/lib/publishing/new-listing-readiness.ts': { 42 source: 43 "import {\n identityMessagingOwnership,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport { privateSessionOwnership } from '../runtime/private-session.ts';\nimport {\n inboxSetupViewOwnership,\n inboxSetupViewSnapshot,\n type InboxSetupView\n} from '../messaging/inbox-setup-view.ts';\nimport {\n inboxResolutionSnapshot,\n inboxResolverCurrentAfterSample\n} from '../messaging/resolve-inbox.ts';\nimport { existingInboxSetupSnapshot } from '../messaging/inbox-setup-verification.ts';\nimport type { InboxAccessObservation } from '../messaging/readiness.ts';\nimport type { RelayPolicy } from '../config/relays.ts';\n\ndeclare const readinessBrand: unique symbol;\nexport type NewListingReadiness = Readonly<{ [readinessBrand]: true }>;\ntype Ownership = Readonly<{\n owner: string;\n identity: IdentitySession;\n policy: RelayPolicy;\n current(this: void): boolean;\n signingCurrent(this: void): boolean;\n}>;\nconst reviews = new WeakMap<\n NewListingReadiness,\n {\n ownership: Ownership;\n close(): void;\n }\n>();\n\n// Readiness is a prerequisite for a later new-listing command, not permission\n// to sign, write a preference, reserve a listing or publish an event. Its owners\n// must still validate the exact draft/author/template and final explicit action.\nfunction sample(identity: IdentitySession, setup: InboxSetupView | undefined) {\n try {\n if (typeof window === 'undefined') return;\n const actor = identityMessagingOwnership(identity);\n const own = inboxSetupViewOwnership(setup);\n const state = inboxSetupViewSnapshot(setup);\n if (\n !actor?.current() ||\n !own?.current() ||\n own.identity !== identity ||\n !own.session ||\n !own.resolver ||\n state.busy ||\n !state.setupComplete\n )\n return;\n const privateOwner = privateSessionOwnership(own.session);\n if (\n !privateOwner?.current() ||\n privateOwner.owner !== actor.owner ||\n privateOwner.session !== actor.session\n )\n return;\n const initial = inboxResolutionSnapshot(own.resolver);\n if (!initial.knownBase || initial.author !== actor.owner) return;\n let access: InboxAccessObservation | undefined;\n const ready = existingInboxSetupSnapshot(\n identity,\n own.session,\n own.policy,\n own.resolver,\n own.observeAccess\n ? (context) => {\n access = own.observeAccess!(context);\n return access;\n }\n : undefined\n );\n const final = inboxResolutionSnapshot(own.resolver);\n const accessCurrent = access?.current() ?? false;\n const actual = inboxSetupViewOwnership(setup);\n const finalState = inboxSetupViewSnapshot(setup);\n if (\n !ready.setupComplete ||\n !ready.newListingReady ||\n !accessCurrent ||\n final.knownBase?.id !== initial.knownBase.id ||\n final.status !== 'ready' ||\n !actor.current() ||\n !privateOwner.current() ||\n !own.current() ||\n !actual?.current() ||\n actual.identity !== identity ||\n actual.policy !== own.policy ||\n actual.session !== own.session ||\n actual.resolver !== own.resolver ||\n finalState.busy ||\n !finalState.setupComplete ||\n !inboxResolverCurrentAfterSample(own.resolver)\n )\n return;\n return {\n actor,\n own,\n privateOwner,\n preferenceId: final.knownBase.id,\n accessCurrent: () => access?.current() ?? false\n };\n } catch {\n return;\n }\n}\n\n// Detached display information never mints or replaces the original review.\n// Draft saving has no dependency on this module and remains available here.\nexport function newListingReadinessSnapshot(\n identity: IdentitySession,\n setup: InboxSetupView | undefined\n) {\n const ready = !!sample(identity, setup);\n return {\n draft: true as const,\n readyToReview: ready,\n preferenceWrite: 'not_requested' as const,\n copy: ready\n ? 'Messages: ready to receive replies'\n : 'Enable messages before publishing so buyers can contact you.'\n };\n}\nexport function captureNewListingReadiness(\n identity: IdentitySession,\n setup: InboxSetupView | undefined,\n review: unknown\n): NewListingReadiness | undefined {\n if (review !== 'reviewed_new_listing_inbox') return;\n const captured = sample(identity, setup);\n if (!captured) return;\n const capturedResolver = captured.own.resolver;\n if (!capturedResolver) return;\n let active = true;\n // Continuity of an already admitted original signing action. Reacquiring\n // messaging capability during that action would reject its own busy prompt.\n // This checks retained original generations/access, never admits a new action.\n const signingCurrent = () => {\n const actual = inboxSetupViewOwnership(setup);\n const state = inboxSetupViewSnapshot(setup);\n const resolved = inboxResolutionSnapshot(capturedResolver);\n return (\n active &&\n captured.actor.current() &&\n captured.own.current() &&\n captured.privateOwner.current() &&\n captured.accessCurrent() &&\n !!actual?.current() &&\n actual.identity === captured.own.identity &&\n actual.policy === captured.own.policy &&\n actual.session === captured.own.session &&\n actual.resolver === captured.own.resolver &&\n !state.busy &&\n state.setupComplete &&\n resolved.status === 'ready' &&\n resolved.author === captured.actor.owner &&\n resolved.knownBase?.id === captured.preferenceId &&\n inboxResolverCurrentAfterSample(capturedResolver) &&\n active &&\n captured.actor.current() &&\n captured.privateOwner.current()\n );\n };\n const current = () => {\n if (\n !active ||\n !captured.actor.current() ||\n !captured.own.current() ||\n !captured.privateOwner.current()\n )\n return false;\n const actual = sample(identity, setup);\n return (\n !!actual &&\n active &&\n actual.actor.owner === captured.actor.owner &&\n actual.actor.session === captured.actor.session &&\n actual.own.identity === captured.own.identity &&\n actual.own.policy === captured.own.policy &&\n actual.own.session === captured.own.session &&\n actual.own.resolver === captured.own.resolver &&\n actual.preferenceId === captured.preferenceId &&\n captured.actor.current() &&\n captured.own.current() &&\n captured.privateOwner.current()\n );\n };\n const token = Object.freeze({}) as NewListingReadiness;\n reviews.set(token, {\n ownership: {\n owner: captured.actor.owner,\n identity,\n policy: captured.own.policy,\n current,\n signingCurrent\n },\n close: () => {\n active = false;\n }\n });\n return token;\n}\nexport function newListingReadinessOwnership(\n token: NewListingReadiness | undefined\n): Ownership | undefined {\n const original = token && reviews.get(token);\n return original?.ownership.current() ? { ...original.ownership } : undefined;\n}\nexport function closeNewListingReadiness(token: NewListingReadiness): void {\n reviews.get(token)?.close();\n}\n", 44 sha256: '0f88210b837998dbc459986e2648e0a11f3a688451a9a60f1da58d3b9d1d6e1d' 45 }, 46 'src/lib/publishing/listing-editor.ts': { 47 source: 48 "import {\n exactLocalFields,\n type PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId, newLocalId } from '../private-handles.ts';\nimport type { InboxSetupView } from '../messaging/inbox-setup-view.ts';\nimport {\n captureNewListingReadiness,\n closeNewListingReadiness,\n type NewListingReadiness\n} from './new-listing-readiness.ts';\nimport {\n reviewNewListing,\n listingReviewSnapshot,\n listingReviewOwnership,\n type ListingReview,\n type ListingReviewResult\n} from './prepare-listing.ts';\nimport { decodeProductReference } from '../nostr/references.ts';\nimport {\n openOwnedEditSource,\n ownedEditSourceSnapshot,\n authorizeOwnedEditSource,\n closeOwnedEditSource,\n type OwnedEditSource\n} from './edit-source.ts';\nimport type { PublicRuntime } from '../runtime/public-runtime.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicPublicationRepository,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport {\n publicDraftRepositoryOwner,\n type PublicDraftRepository\n} from '../persistence/drafts.ts';\nimport {\n createPublicDraftController,\n publicDraftControllerSnapshot,\n editPublicDraft,\n flushPublicDraft,\n retryPublicDraft,\n saveAndClosePublicDraft,\n closePublicDraftController,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n identityViewSession,\n identityViewMatchesOwner,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport {\n identitySessionSnapshot,\n subscribeIdentityInvalidation\n} from '../runtime/identity-session.ts';\nimport {\n readListingOperationView,\n closeListingOperationView,\n type ListingOperationView\n} from './listing-operation-view.ts';\n\ndeclare const editorBrand: unique symbol;\nexport type ListingEditor = Readonly<{ [editorBrand]: true }>;\nexport type ListingEditorRoute =\n | Readonly<{ mode: 'new' }>\n | Readonly<{ mode: 'draft'; draftId: string }>\n | Readonly<{ mode: 'edit'; naddr: string }>;\nexport type ListingEditorSnapshot = Readonly<{\n mode: ListingEditorRoute['mode'];\n owner: string;\n form: PublicDraftForm;\n editable: boolean;\n draftId: string | null;\n state: 'editing' | 'saving' | 'saved' | 'failed' | 'read-only';\n failure: string | null;\n coordinate: string | null;\n sourceEventId: string | null;\n sourcePublishedAtSeconds?: number;\n operations: readonly ListingOperationView[];\n}>;\ntype Editor = Readonly<{\n current(): boolean;\n retire(): void;\n snapshot(): ListingEditorSnapshot | undefined;\n edit(form: unknown): Promise<boolean>;\n flush(): Promise<boolean>;\n saveClose(): Promise<boolean>;\n review(\n setup: InboxSetupView | undefined,\n form: PublicDraftForm\n ): Promise<ListingReviewResult>;\n reviewCurrent(review: ListingReview): boolean;\n source(): OwnedEditSource | undefined;\n observe(): void;\n subscribe(listener: () => void): () => void;\n}>;\nconst editors = new WeakMap<ListingEditor, Editor>();\nconst active = new WeakMap<\n IdentityViewContext,\n Readonly<{ stamp: symbol; retire(): void }>\n>();\nconst emptyForm: PublicDraftForm = {\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n};\nfunction routeSnapshot(value: unknown): ListingEditorRoute | undefined {\n try {\n if (exactLocalFields(value, ['mode']) && value.mode === 'new')\n return { mode: 'new' };\n if (\n exactLocalFields(value, ['mode', 'draftId']) &&\n value.mode === 'draft'\n ) {\n const draftId = canonicalLocalId(value.draftId);\n return draftId ? { mode: 'draft', draftId } : undefined;\n }\n if (exactLocalFields(value, ['mode', 'naddr']) && value.mode === 'edit') {\n const reference = decodeProductReference(value.naddr);\n return reference ? { mode: 'edit', naddr: reference.naddr } : undefined;\n }\n } catch {\n return;\n }\n}\n// Owner admission precedes database opening and all protected hydration. Edit\n// mode presents validated local values; independent head authorization is later.\nexport async function openListingEditor(\n context: IdentityViewContext,\n input: unknown,\n signal?: AbortSignal,\n runtime?: PublicRuntime\n): Promise<\n | Readonly<{ status: 'ready'; editor: ListingEditor }>\n | Readonly<{\n status: 'unavailable';\n reason: 'owner' | 'resource' | 'storage' | 'source';\n }>\n> {\n const session = identityViewSession(context),\n route = routeSnapshot(input);\n if (!session || signal?.aborted)\n return { status: 'unavailable', reason: 'owner' };\n const identity = identitySessionSnapshot(session),\n owner = 'publicKey' in identity ? identity.publicKey : undefined;\n if (!owner || !identityViewMatchesOwner(context, owner))\n return { status: 'unavailable', reason: 'owner' };\n if (\n !route ||\n (route.mode === 'edit' &&\n decodeProductReference(route.naddr)?.pubkey !== owner)\n )\n return { status: 'unavailable', reason: 'resource' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable', reason: 'storage' };\n active.get(context)?.retire();\n const stamp = Symbol(),\n listeners = new Map<symbol, () => void>(),\n cancellation = new AbortController();\n let alive = true,\n closing = false,\n unsubscribe = () => {},\n database: BrowserDatabase | undefined,\n repository: PublicDraftRepository | undefined,\n controller: PublicDraftController | undefined;\n const operations = new Map<string, ListingOperationView>();\n let editSource: OwnedEditSource | undefined;\n let acquiringEditDraft:\n Promise<PublicDraftController | undefined> | undefined;\n let reviewed:\n | {\n setup: InboxSetupView | undefined;\n proof: NewListingReadiness;\n review: ListingReview;\n }\n | undefined;\n let reviewing: Promise<ListingReviewResult> | undefined;\n let reviewingForm: string | undefined;\n let reviewingSetup: InboxSetupView | undefined;\n function clearReview() {\n if (reviewed) closeNewListingReadiness(reviewed.proof);\n reviewed = undefined;\n }\n function current() {\n return (\n alive &&\n active.get(context)?.stamp === stamp &&\n identityViewSession(context) === session &&\n identityViewMatchesOwner(context, owner) &&\n (!repository || publicDraftRepositoryOwner(repository) === owner)\n );\n }\n let notifying = false;\n function notify() {\n if (notifying) return;\n notifying = true;\n try {\n for (const [key, listener] of Array.from(listeners.entries()))\n if (listeners.get(key) === listener) {\n try {\n listener();\n } catch {\n /*Presentation observers cannot authorize or retain ownership.*/\n }\n }\n } finally {\n notifying = false;\n }\n }\n function retire() {\n if (!alive) return;\n alive = false;\n unsubscribe();\n signal?.removeEventListener('abort', retire);\n cancellation.abort();\n clearReview();\n if (editSource) closeOwnedEditSource(editSource);\n if (controller) closePublicDraftController(controller);\n for (const operation of operations.values())\n closeListingOperationView(operation);\n if (database) closeBrowserDatabase(database);\n if (active.get(context)?.stamp === stamp) active.delete(context);\n notify();\n listeners.clear();\n }\n active.set(context, { stamp, retire });\n unsubscribe = subscribeIdentityInvalidation(session, retire);\n signal?.addEventListener('abort', retire, { once: true });\n if (signal?.aborted) retire();\n function unavailable(reason: 'resource' | 'storage' | 'source') {\n retire();\n return { status: 'unavailable' as const, reason };\n }\n try {\n const opened = await openBrowserDatabase(cancellation.signal);\n if (opened.state !== 'ready') return unavailable('storage');\n if (!current()) {\n closeBrowserDatabase(opened.owner);\n return unavailable('storage');\n }\n database = opened.owner;\n const publications = createPublicPublicationRepository(database, owner);\n repository = publications && publicPublicationDraftRepository(publications);\n if (!publications || !repository || !current())\n return unavailable('storage');\n const drafts = repository;\n let sourceForm: PublicDraftForm | undefined,\n coordinate: string | null = null,\n sourceEventId: string | null = null;\n if (route.mode === 'edit') {\n editSource = await openOwnedEditSource(\n publications,\n context,\n route.naddr,\n runtime,\n cancellation.signal\n );\n if (!current()) return unavailable('source');\n const retained = editSource && ownedEditSourceSnapshot(editSource);\n if (!retained) return unavailable('source');\n sourceForm = retained.form;\n coordinate = route.naddr;\n sourceEventId = retained.sourceEventId;\n } else {\n const acquired = await createPublicDraftController(\n drafts,\n emptyForm,\n route.mode === 'draft' ? route.draftId : undefined\n );\n if (!current()) {\n if (acquired) closePublicDraftController(acquired);\n return unavailable('resource');\n }\n controller = acquired;\n if (!controller) return unavailable('resource');\n if (route.mode === 'draft') {\n const quota = publicPublicationQuotaRepository(publications);\n if (!quota) return unavailable('source');\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) return unavailable('source');\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) return unavailable('source');\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(publications, item.id);\n if (!current()) return unavailable('source');\n const row =\n read.status === 'found' &&\n publicRecordSnapshot(read.record, owner, item.id);\n if (!row || row.family !== 'public_operation')\n return unavailable('source');\n if (row.source.type !== 'draft' || row.source.id !== route.draftId)\n continue;\n if (operations.size >= 100) return unavailable('source');\n const operation = await readListingOperationView(\n publications,\n session,\n item.id\n );\n if (!current()) {\n if (operation.status === 'found')\n closeListingOperationView(operation.view);\n return unavailable('source');\n }\n if (operation.status !== 'found') return unavailable('source');\n operations.set(item.id, operation.view);\n }\n }\n }\n if (!current()) return unavailable('source');\n function reviewCurrent(review: ListingReview) {\n const preview = listingReviewSnapshot(review),\n local = controller && publicDraftControllerSnapshot(controller);\n return !!(\n current() &&\n !closing &&\n !operations.size &&\n route &&\n route.mode !== 'edit' &&\n reviewed?.review === review &&\n listingReviewOwnership(review)?.current() &&\n preview &&\n local?.state === 'saved' &&\n local.draft &&\n preview.owner === owner &&\n preview.draftId === local.draft.id &&\n preview.draftRevision === local.draft.revision &&\n JSON.stringify(preview.form) === JSON.stringify(local.form)\n );\n }\n const value: Editor = {\n current,\n retire,\n source: () => (current() ? editSource : undefined),\n observe: () => {\n if (current()) notify();\n },\n snapshot() {\n if (!current()) {\n retire();\n return;\n }\n const local = controller && publicDraftControllerSnapshot(controller);\n return {\n mode: route.mode,\n owner,\n form: local ? local.form : { ...(sourceForm ?? emptyForm) },\n editable:\n operations.size === 0 &&\n (route.mode !== 'edit' ||\n !!(editSource && authorizeOwnedEditSource(editSource))),\n draftId: local?.draft?.id ?? null,\n state:\n local && operations.size === 0\n ? local.state === 'closed'\n ? 'failed'\n : local.state\n : 'read-only',\n failure: local?.failure ?? null,\n coordinate,\n sourceEventId,\n ...(editSource\n ? {\n sourcePublishedAtSeconds:\n ownedEditSourceSnapshot(editSource)?.publishedAtSeconds\n }\n : {}),\n operations: Array.from(operations.values())\n };\n },\n async edit(input) {\n if (!current()) {\n retire();\n return false;\n }\n if (route.mode === 'edit') {\n if (\n !editSource ||\n !authorizeOwnedEditSource(editSource) ||\n !sourceForm\n )\n return false;\n if (!controller) {\n acquiringEditDraft ??= createPublicDraftController(\n drafts,\n sourceForm\n );\n const acquired = await acquiringEditDraft;\n if (!current() || !authorizeOwnedEditSource(editSource)) {\n if (acquired) closePublicDraftController(acquired);\n return false;\n }\n controller = acquired;\n }\n }\n if (!controller || operations.size) return false;\n if (!editPublicDraft(controller, input)) return false;\n clearReview();\n notify();\n const pending = flushPublicDraft(controller);\n await Promise.resolve();\n if (!current()) {\n retire();\n return false;\n }\n notify();\n const saved = await pending;\n if (!current()) {\n retire();\n return false;\n }\n notify();\n return saved;\n },\n async flush() {\n if (!current()) {\n retire();\n return false;\n }\n if (!controller || operations.size) return false;\n const pending = flushPublicDraft(controller);\n await Promise.resolve();\n if (!current()) {\n retire();\n return false;\n }\n notify();\n const saved = await pending;\n if (!current()) {\n retire();\n return false;\n }\n notify();\n return saved;\n },\n async saveClose() {\n if (!current() || !controller || operations.size || closing)\n return false;\n closing = true;\n try {\n if (publicDraftControllerSnapshot(controller)?.state === 'failed') {\n const retried = await retryPublicDraft(controller);\n if (!current()) {\n retire();\n return false;\n }\n notify();\n if (!retried) return false;\n }\n const saved = await saveAndClosePublicDraft(controller);\n if (!current()) {\n retire();\n return false;\n }\n if (!saved) {\n notify();\n return false;\n }\n retire();\n return true;\n } finally {\n closing = false;\n }\n },\n review(setup, input) {\n const local = controller && publicDraftControllerSnapshot(controller);\n if (\n !current() ||\n closing ||\n !controller ||\n !local ||\n route.mode === 'edit' ||\n operations.size ||\n !exactLocalFields(input, Object.keys(emptyForm)) ||\n JSON.stringify(input) !== JSON.stringify(local.form)\n )\n return Promise.resolve({\n status: 'blocked',\n reason: 'invalid_scope'\n });\n if (\n reviewed &&\n reviewed.setup === setup &&\n reviewCurrent(reviewed.review)\n )\n return Promise.resolve({ status: 'review', review: reviewed.review });\n const formWire = JSON.stringify(local.form);\n if (reviewing)\n return reviewingForm === formWire && reviewingSetup === setup\n ? reviewing\n : Promise.resolve({ status: 'blocked', reason: 'conflict' });\n clearReview();\n const proof = captureNewListingReadiness(\n session,\n setup,\n 'reviewed_new_listing_inbox'\n ),\n command = newLocalId();\n if (!proof || !command) {\n if (proof) closeNewListingReadiness(proof);\n return Promise.resolve({ status: 'blocked', reason: 'unavailable' });\n }\n const original = controller;\n reviewingForm = formWire;\n reviewingSetup = setup;\n const pending = reviewNewListing(\n publications,\n original,\n proof,\n command,\n 'reviewed_new_listing'\n )\n .then((result): ListingReviewResult => {\n const actual = publicDraftControllerSnapshot(original);\n if (\n !current() ||\n closing ||\n !actual ||\n JSON.stringify(actual.form) !== formWire ||\n result.status !== 'review'\n ) {\n closeNewListingReadiness(proof);\n return result.status === 'blocked'\n ? result\n : { status: 'blocked', reason: 'conflict' };\n }\n reviewed = { setup, proof, review: result.review };\n if (!reviewCurrent(result.review)) {\n clearReview();\n return { status: 'blocked', reason: 'conflict' };\n }\n return result;\n })\n .finally(() => {\n if (reviewing === pending) {\n reviewing = undefined;\n reviewingForm = undefined;\n reviewingSetup = undefined;\n }\n });\n reviewing = pending;\n return pending;\n },\n reviewCurrent,\n subscribe(listener) {\n if (!current()) return () => {};\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n }\n };\n const editor = Object.freeze({}) as ListingEditor;\n editors.set(editor, value);\n return { status: 'ready', editor };\n } catch {\n return unavailable('storage');\n }\n}\nexport function listingEditorSnapshot(\n editor: ListingEditor\n): ListingEditorSnapshot | undefined {\n return editors.get(editor)?.snapshot();\n}\nexport function editListingEditor(\n editor: ListingEditor,\n form: unknown\n): Promise<boolean> {\n return editors.get(editor)?.edit(form) ?? Promise.resolve(false);\n}\nexport function flushListingEditor(editor: ListingEditor): Promise<boolean> {\n return editors.get(editor)?.flush() ?? Promise.resolve(false);\n}\nexport function closeListingEditor(editor: ListingEditor): void {\n editors.get(editor)?.retire();\n}\nexport function listingEditorEditSource(\n editor: ListingEditor\n): OwnedEditSource | undefined {\n return editors.get(editor)?.source();\n}\nexport function observeListingEditor(editor: ListingEditor): void {\n editors.get(editor)?.observe();\n}\nexport function saveAndCloseListingEditor(\n editor: ListingEditor\n): Promise<boolean> {\n return editors.get(editor)?.saveClose() ?? Promise.resolve(false);\n}\nexport function subscribeListingEditor(\n editor: ListingEditor,\n listener: () => void\n): () => void {\n return editors.get(editor)?.subscribe(listener) ?? (() => {});\n}\n// Original editor custody remains private. Review never reserves or signs.\nexport function reviewListingEditor(\n editor: ListingEditor,\n setup: InboxSetupView | undefined,\n form: PublicDraftForm\n): Promise<ListingReviewResult> {\n return (\n editors.get(editor)?.review(setup, form) ??\n Promise.resolve({ status: 'blocked', reason: 'invalid_scope' })\n );\n}\nexport function listingEditorReviewCurrent(\n editor: ListingEditor,\n review: ListingReview\n): boolean {\n return editors.get(editor)?.reviewCurrent(review) ?? false;\n}\n", 49 sha256: 'fa2c698892b820f10adc0c816641da6a2c40b5cfc3df8db2880f61659d81b4ec' 50 }, 51 'src/lib/publishing/edit-source.ts': { 52 source: 53 "import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport {\n projectFoodParts,\n type FoodProjection\n} from '../contracts/food-availability-v1/read.ts';\nimport type { PublicDraftForm } from '../contracts/local-records.ts';\nimport { decodeProductReference } from '../nostr/references.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport {\n publicPublicationOwner,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from '../persistence/public-publications.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport { readPublicDraft } from '../persistence/drafts.ts';\nimport {\n identityViewSession,\n identityViewMatchesOwner,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n publicViewOwnsRun,\n publicViewRunCurrent,\n publicViewProjectionAvailable,\n type PublicRuntime,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n createPublicViewHeadResolver,\n resolveHeads,\n headResolutionSnapshot,\n closeHeadResolver,\n type HeadResolver\n} from '../catalog/resolve-head.ts';\nimport { createPublicHeadCandidate, publicHeadKey } from '../catalog/heads.ts';\n\ndeclare const sourceBrand: unique symbol;\nexport type OwnedEditSource = Readonly<{ [sourceBrand]: true }>;\nexport type OwnedEditSourceSnapshot = Readonly<{\n owner: string;\n coordinate: string;\n sourceEventId: string;\n sourceCommand: string;\n publishedAtSeconds: number;\n form: PublicDraftForm;\n status:\n 'read-only' | 'checking' | 'ready' | 'partial' | 'conflict' | 'withdrawn';\n current?: FoodProjection;\n currentEventId?: string;\n definitiveAbsence: false;\n}>;\ntype Source = {\n snapshot(): OwnedEditSourceSnapshot | undefined;\n authorize():\n | Readonly<{\n repository: PublicPublicationRepository;\n owner: string;\n coordinate: string;\n baseWire: string;\n sourceCommand: string;\n publishedAtSeconds: number;\n current(): boolean;\n }>\n | undefined;\n close(): void;\n};\nconst sources = new WeakMap<OwnedEditSource, Source>();\n// Retained prototype custody precedes network work. A public/Tera event, a\n// snapshot, or an arbitrary same-author signature is not adopted as local source.\nexport async function openOwnedEditSource(\n repository: PublicPublicationRepository,\n context: IdentityViewContext,\n value: unknown,\n runtime?: PublicRuntime,\n signal?: AbortSignal\n): Promise<OwnedEditSource | undefined> {\n let view: PublicView | undefined, resolver: HeadResolver | undefined;\n let closed = false,\n off = () => {};\n function close() {\n if (closed) return;\n closed = true;\n off();\n signal?.removeEventListener('abort', close);\n try {\n if (resolver) closeHeadResolver(resolver);\n } finally {\n if (view) disposePublicView(view);\n }\n }\n try {\n const owner = publicPublicationOwner(repository),\n session = identityViewSession(context),\n reference = decodeProductReference(value),\n drafts = publicPublicationDraftRepository(repository),\n quota = publicPublicationQuotaRepository(repository);\n if (\n !owner ||\n !session ||\n !reference ||\n reference.pubkey !== owner ||\n !drafts ||\n !quota ||\n signal?.aborted ||\n !identityViewMatchesOwner(context, owner)\n )\n return;\n const current = () =>\n !closed &&\n !signal?.aborted &&\n identityViewSession(context) === session &&\n identityViewMatchesOwner(context, owner) &&\n publicPublicationOwner(repository) === owner;\n off = subscribeIdentityInvalidation(session, close);\n signal?.addEventListener('abort', close, { once: true });\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) {\n close();\n return;\n }\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) {\n close();\n return;\n }\n let retained:\n | Readonly<{\n form: PublicDraftForm;\n wire: string;\n command: string;\n publishedAt: number;\n eventId: string;\n }>\n | undefined;\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(repository, item.id);\n if (!current()) {\n close();\n return;\n }\n const row =\n read.status === 'found' &&\n publicRecordSnapshot(read.record, owner, item.id);\n // Incomplete critical storage is not an absence that permits adoption.\n if (!row || row.family !== 'public_operation') {\n close();\n return;\n }\n if (\n row.capture.kind !== 30402 ||\n !row.artifact ||\n row.source.type !== 'draft'\n )\n continue;\n const template = inspectLocalTemplate(row.capture.wire, owner, 30402),\n projected = template && projectFoodParts(template);\n if (\n !template ||\n !projected ||\n projected.outcome !== 'focused' ||\n projected.projection.identifier !== reference.identifier\n )\n continue;\n const source = await readPublicDraft(drafts, row.source.id);\n if (!current()) {\n close();\n return;\n }\n if (!source.ok || source.value.revision !== row.source.revision) continue;\n const form = source.value.form,\n food = projected.projection;\n if (form.contactType === '' && form.contactValue !== '') continue;\n const built = buildFoodTemplate({\n identifier: food.identifier,\n title: form.title,\n description: form.description,\n location: form.location,\n amount: form.amount,\n currency: form.currency,\n unit: form.unit,\n ...(form.quantity === '' ? {} : { quantity: form.quantity }),\n published_at: food.published_at,\n created_at: template.created_at,\n status: food.status,\n ...(form.contactType === ''\n ? {}\n : {\n contact: {\n type: form.contactType,\n value: form.contactValue,\n public: true as const\n }\n })\n });\n if (\n !built.ok ||\n JSON.stringify({\n pubkey: owner,\n kind: 30402,\n created_at: template.created_at,\n tags: built.wire_parts.tags,\n content: built.wire_parts.content\n }) !== row.capture.wire\n )\n continue;\n const verified = verifyEnvelope(row.artifact.wire),\n signed = verified.ok && verifiedEnvelopeSnapshot(verified.value);\n if (\n !signed ||\n signed.id !== row.artifact.eventId ||\n signed.id !== row.capture.hash ||\n JSON.stringify({\n pubkey: signed.pubkey,\n kind: signed.kind,\n created_at: signed.created_at,\n tags: signed.tags,\n content: signed.content\n }) !== row.capture.wire\n )\n continue;\n if (retained) {\n close();\n return;\n }\n retained = {\n form,\n wire: row.artifact.wire,\n command: row.id,\n publishedAt: food.published_at,\n eventId: signed.id\n };\n }\n if (!retained || !current()) {\n close();\n return;\n }\n const base = retained,\n proof = verifyEnvelope(base.wire);\n const head = proof.ok && createPublicHeadCandidate(proof.value);\n if (!head) {\n close();\n return;\n }\n const key = publicHeadKey(head);\n let run: ReturnType<typeof beginPublicViewRun> | undefined;\n if (runtime) {\n // A separate view/run and exact coordinate+deletion requests are independent\n // of keyword search. Genuine retained proof seeds the ordinary selector.\n view = createPublicView(runtime);\n run = beginPublicViewRun(view);\n resolver = createPublicViewHeadResolver(view, run, {\n nowSeconds: () => Math.floor(Date.now() / 1000)\n });\n resolveHeads(resolver, [head]);\n }\n const networkOwned = () =>\n !!(\n view &&\n run &&\n publicViewOwnsRun(view, run) &&\n publicViewProjectionAvailable(view)\n );\n function snapshot(): OwnedEditSourceSnapshot | undefined {\n if (!current()) {\n close();\n return;\n }\n const row =\n resolver && networkOwned()\n ? headResolutionSnapshot(resolver).find((row) => row.key === key)\n : undefined;\n const scopes = row && [row.headSources, row.deletionSources];\n const complete = !!(\n row &&\n view &&\n run &&\n publicViewRunCurrent(view, run) &&\n row.coverage === 'bounded-eose' &&\n !row.lastKnown &&\n scopes?.every(\n (scope) =>\n scope?.state === 'eose' && scope.result.coverage === 'bounded-eose'\n )\n );\n const competing = row && row.state.head.id !== base.eventId;\n const status: OwnedEditSourceSnapshot['status'] = !runtime\n ? 'read-only'\n : row?.deletion.outcome === 'suppressed'\n ? 'withdrawn'\n : competing\n ? 'conflict'\n : complete &&\n row?.state.food &&\n row.state.display === 'focused_known'\n ? 'ready'\n : scopes?.some((scope) => scope?.state === 'active')\n ? 'checking'\n : 'partial';\n return {\n owner: owner!,\n coordinate: reference!.naddr,\n sourceEventId: base.eventId,\n sourceCommand: base.command,\n publishedAtSeconds: base.publishedAt,\n form: { ...base.form },\n status,\n ...(row?.state.food ? { current: row.state.food } : {}),\n ...(row ? { currentEventId: row.state.head.id } : {}),\n definitiveAbsence: false\n };\n }\n const token = Object.freeze({}) as OwnedEditSource;\n sources.set(token, {\n snapshot,\n close,\n authorize() {\n if (snapshot()?.status !== 'ready') return;\n return {\n repository,\n owner,\n coordinate: reference.naddr,\n baseWire: base.wire,\n sourceCommand: base.command,\n publishedAtSeconds: base.publishedAt,\n current: () => snapshot()?.status === 'ready'\n };\n }\n });\n return token;\n } catch {\n close();\n return;\n }\n}\nexport function ownedEditSourceSnapshot(\n source: OwnedEditSource\n): OwnedEditSourceSnapshot | undefined {\n return sources.get(source)?.snapshot();\n}\n// Internal original edit custody only, never a signing/delivery lease.\nexport function authorizeOwnedEditSource(source: OwnedEditSource) {\n return sources.get(source)?.authorize();\n}\nexport function closeOwnedEditSource(source: OwnedEditSource): void {\n sources.get(source)?.close();\n}\n", 54 sha256: '985634e4c4eb2cd12839409552b1c56cd518021d4f031166a3c1ab8c4a0e7eff' 55 }, 56 'src/lib/runtime/public-runtime.ts': { 57 source: 58 "import { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport type { RelayPolicy } from '../config/relays.ts';\nimport { qualifiedNip50Sources } from '../nostr/search-sources.ts';\nimport {\n getPublicPool,\n subscribePublicPool,\n closePublicPool,\n type PublicPool\n} from '../nostr/public-pool.ts';\nimport {\n getPublicStore,\n insertPublicEnvelope,\n closePublicStore,\n publicStoreRetention,\n publicStoreKnownEvidence,\n publicStoreEnvelope,\n type PublicStore\n} from '../nostr/public-store.ts';\nimport {\n createPublicScheduler,\n createPublicRun,\n openPublicRequest,\n openInboxRequest,\n disposePublicRun,\n closePublicScheduler,\n publicRunSnapshot,\n type PublicScheduler,\n type PublicRun,\n type PublicRequest,\n type RequestKind,\n type RequestClock\n} from '../nostr/request-scope.ts';\nimport type { PublicFilter } from '../nostr/exports.ts';\nimport { inboxPreferenceQueries } from '../nostr/inbox-queries.ts';\nimport {\n publicHeadEnvelope,\n publicHeadSnapshot,\n type PublicHead\n} from '../catalog/heads.ts';\nimport type { KnownPublicEvidence } from '../catalog/retention.ts';\nimport type { VerifiedEnvelope } from '../nostr/verified-envelope.ts';\ndeclare const contextBrand: unique symbol;\ndeclare const runtimeBrand: unique symbol;\ndeclare const viewBrand: unique symbol;\nexport type PublicRuntimeContext = Readonly<{ readonly [contextBrand]: true }>;\nexport type PublicRuntime = Readonly<{ readonly [runtimeBrand]: true }>;\nexport type PublicView = Readonly<{ readonly [viewBrand]: true }>;\nexport const PUBLIC_RUNTIME_CONTEXT = 'harvestcircle_public_runtime';\ninterface RuntimeOwner {\n readonly pool: PublicPool;\n readonly store: PublicStore;\n readonly scheduler: PublicScheduler;\n readonly policy: RelayPolicy;\n readonly views: Map<PublicView, () => boolean>;\n readonly closed: () => boolean;\n readonly projectionValid: (retry?: boolean) => boolean;\n readonly invalidateProjection: () => void;\n readonly close: () => void;\n}\ninterface ContextOwner {\n readonly value: () => PublicRuntime | undefined;\n readonly mount: (\n policy: RelayPolicy,\n clock?: RequestClock\n ) => PublicRuntime | undefined;\n readonly ready: Promise<PublicRuntime | undefined>;\n readonly close: () => void;\n}\ninterface ViewOwner {\n readonly runtime: RuntimeOwner;\n readonly begin: () => PublicRun;\n readonly current: (run: PublicRun) => boolean;\n readonly settling: () => boolean;\n readonly settleWith: (refresh: () => void) => void;\n readonly dispose: () => boolean;\n}\nconst contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(),\n runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(),\n views = new WeakMap<PublicView, ViewOwner>();\nlet browserContext: PublicRuntimeContext | undefined;\nfunction contextOf(token: PublicRuntimeContext): ContextOwner {\n const owner = contexts.get(token);\n if (!owner) throw new Error('public_runtime_context_invalid');\n return owner;\n}\nfunction runtimeOf(token: PublicRuntime): RuntimeOwner {\n const owner = runtimes.get(token);\n if (!owner) throw new Error('public_runtime_invalid');\n if (owner.closed()) throw new Error('public_runtime_closed');\n return owner;\n}\nfunction viewOf(token: PublicView): ViewOwner {\n const owner = views.get(token);\n if (!owner) throw new Error('public_view_invalid');\n return owner;\n}\n// Context construction is SSR-pure. Root onMount acquires the browser lifetime;\n// children can await readiness even when their onMount runs before the root's.\nexport function createPublicRuntimeContext(): PublicRuntimeContext {\n let value: PublicRuntime | undefined,\n closed = false;\n let ready: (value: PublicRuntime | undefined) => void = () => {};\n let selectedClock: RequestClock | undefined;\n const promise = new Promise<PublicRuntime | undefined>((resolve) => {\n ready = resolve;\n });\n const owner: ContextOwner = {\n value: () => (closed ? undefined : value),\n ready: promise,\n mount(policy, clock) {\n if (closed) throw new Error('public_runtime_closed');\n if (typeof window === 'undefined') return undefined;\n if (value) {\n const prior = runtimes.get(value);\n if (!prior || prior.policy !== policy)\n throw new Error('public_runtime_policy_changed');\n if (clock !== selectedClock)\n throw new Error('public_runtime_clock_changed');\n return value;\n }\n if (browserContext && browserContext !== contextToken)\n throw new Error('public_runtime_owner_changed');\n const pool = getPublicPool(policy),\n store = getPublicStore();\n if (!pool || !store) return undefined;\n const scheduler = createPublicScheduler(clock),\n registered = new Map<PublicView, () => boolean>();\n let terminal = false,\n invalidated = false,\n invalidating = false;\n const token = Object.freeze({}) as PublicRuntime;\n const runtime: RuntimeOwner = {\n pool,\n store,\n scheduler,\n policy,\n views: registered,\n closed: () => terminal,\n projectionValid(retry = true) {\n const retained = publicStoreRetention(store);\n if (retained.stopped || (!terminal && retained.closed))\n invalidated = true;\n // A settler reads the terminal flag without recursively retrying its\n // own disposal. The outer cleanup loop keeps failed controls live.\n if (invalidated && retry) runtime.invalidateProjection();\n return !invalidated;\n },\n invalidateProjection() {\n invalidated = true;\n if (invalidating) return;\n invalidating = true;\n let failed = false;\n try {\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n } finally {\n invalidating = false;\n }\n if (failed) throw new Error('public_projection_close_failed');\n },\n close() {\n terminal = true;\n let failed = false;\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n // Reentrant or failed settlement cannot preserve a coherent projection\n // across store teardown. Terminal uncertainty clears every view.\n if (failed) invalidated = true;\n try {\n closePublicScheduler(scheduler);\n } catch {\n failed = true;\n }\n try {\n closePublicPool(pool);\n } catch {\n failed = true;\n }\n try {\n closePublicStore(store);\n } catch {\n failed = true;\n }\n if (failed) throw new Error('public_runtime_close_failed');\n }\n };\n runtimes.set(token, runtime);\n value = token;\n browserContext = contextToken;\n selectedClock = clock;\n ready(token);\n return token;\n },\n close() {\n closed = true;\n ready(undefined);\n if (value) {\n const runtime = runtimes.get(value);\n if (runtime) runtime.close();\n }\n }\n };\n const contextToken = Object.freeze({}) as PublicRuntimeContext;\n contexts.set(contextToken, owner);\n return contextToken;\n}\nexport function publicRuntime(\n context: PublicRuntimeContext\n): PublicRuntime | undefined {\n return contextOf(context).value();\n}\nexport function publicRuntimeReady(\n context: PublicRuntimeContext\n): Promise<PublicRuntime | undefined> {\n return contextOf(context).ready;\n}\nexport function mountPublicRuntime(\n context: PublicRuntimeContext,\n policy: RelayPolicy = deploymentRelayPolicy,\n clock?: RequestClock\n): PublicRuntime | undefined {\n return contextOf(context).mount(policy, clock);\n}\nexport function closePublicRuntime(context: PublicRuntimeContext): void {\n contextOf(context).close();\n}\nexport function createPublicView(runtime: PublicRuntime): PublicView {\n const shared = runtimeOf(runtime);\n if (!shared.projectionValid())\n throw new Error('public_projection_unavailable');\n const token = Object.freeze({}) as PublicView;\n let run: PublicRun | undefined,\n disposed = false;\n let generation = 0,\n settler: (() => void) | undefined,\n settling = false;\n function settle() {\n const refresh = settler;\n settler = undefined; // Detach before any caller-controlled clock reentry.\n if (!refresh) return;\n settling = true;\n try {\n refresh?.();\n } catch (error) {\n if (!settler) settler = refresh;\n throw error;\n } finally {\n settling = false;\n }\n }\n const owner: ViewOwner = {\n runtime: shared,\n begin() {\n if (disposed || shared.closed() || !shared.projectionValid())\n throw new Error('public_view_closed');\n const operation = ++generation,\n previous = run;\n // Generation reserves the transition; keep failed old controls retryable.\n try {\n settle();\n } finally {\n if (previous) disposePublicRun(previous);\n }\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n )\n throw new Error('public_view_run_superseded');\n const candidate = createPublicRun(shared.scheduler, shared.policy);\n // Run creation samples the injected clock. It may synchronously start a\n // newer view generation before returning; never overwrite that owner.\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n ) {\n disposePublicRun(candidate);\n throw new Error('public_view_run_superseded');\n }\n run = candidate;\n return run;\n },\n settling: () => settling,\n settleWith(refresh) {\n const previous = settler;\n settler = refresh;\n previous?.();\n },\n current(candidate) {\n return !disposed && !shared.closed() && run === candidate;\n },\n dispose() {\n disposed = true;\n generation++;\n if (settling) return false;\n try {\n settle();\n if (run) disposePublicRun(run);\n shared.views.delete(token);\n return true;\n } catch {\n return false;\n }\n }\n };\n views.set(token, owner);\n shared.views.set(token, () => owner.dispose());\n return token;\n}\nexport function beginPublicViewRun(view: PublicView): PublicRun {\n return viewOf(view).begin();\n}\nexport function publicViewRunCurrent(\n view: PublicView,\n run: PublicRun\n): boolean {\n return viewOf(view).current(run) && publicRunSnapshot(run).active;\n}\n// Ownership survives an ordinary deadline so a foreground owner can publish\n// its terminal result once. Supersession/disposal/shared closure revoke it.\nexport function publicViewOwnsRun(view: PublicView, run: PublicRun): boolean {\n return viewOf(view).current(run);\n}\nexport function disposePublicView(view: PublicView): void {\n if (!viewOf(view).dispose()) throw new Error('public_view_close_failed');\n}\nexport function subscribePublicView(\n view: PublicView,\n run: PublicRun,\n kind: RequestKind,\n filters: readonly PublicFilter[],\n onVerified: (event: VerifiedEnvelope) => void,\n sampleSource?: string\n): PublicRequest {\n const owner = viewOf(view);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n // Copy the request template once before SDK effects; caller mutations cannot\n // retarget this request. Product filter builders remain HCP038 and later.\n const frozen = JSON.stringify(filters);\n return openPublicRequest(\n run,\n kind,\n (next) =>\n subscribePublicPool(\n owner.runtime.pool,\n JSON.parse(frozen) as PublicFilter[],\n next,\n sampleSource\n ),\n (event) => {\n if (!owner.current(run)) return;\n const result = insertPublicEnvelope(owner.runtime.store, event);\n if (result === 'limit' || result === 'rejected' || result === 'closed') {\n owner.runtime.invalidateProjection();\n return;\n }\n if (\n (result === 'accepted' || result === 'duplicate') &&\n owner.current(run)\n )\n onVerified(event);\n },\n sampleSource\n );\n}\n\nexport function publicViewNip50Sources(view: PublicView): readonly string[] {\n return qualifiedNip50Sources(viewOf(view).runtime.policy);\n}\n\n// Public metadata, dedicated ownership: no preference enters the food store.\n// Fixed anonymous origins, clocks, scheduler and aggregate ingress stay shared.\nexport function subscribeInboxPreference(\n view: PublicView,\n run: PublicRun,\n author: unknown,\n onVerified: (event: VerifiedEnvelope, inboxSource?: string) => void\n): PublicRequest {\n const owner = viewOf(view),\n filters = inboxPreferenceQueries(author);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n return openInboxRequest(\n run,\n author,\n (next) => subscribePublicPool(owner.runtime.pool, filters, next),\n (event, inboxSource) => {\n if (owner.current(run)) onVerified(event, inboxSource);\n }\n );\n}\n\n// Capacity invalidation differs from ordinary teardown: last-known snapshots\n// remain available on normal close, while a breached working set clears all views.\nexport function publicViewProjectionAvailable(view: PublicView): boolean {\n const owner = viewOf(view);\n return owner.runtime.projectionValid(!owner.settling());\n}\nexport function publicViewKnownEvidence(\n view: PublicView,\n head: PublicHead\n): KnownPublicEvidence {\n return publicStoreKnownEvidence(viewOf(view).runtime.store, head);\n}\nexport function retainPublicViewHeads(\n view: PublicView,\n run: PublicRun,\n heads: readonly PublicHead[]\n): boolean {\n const owner = viewOf(view);\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n const active = publicRunSnapshot(run).active;\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n if (!active) {\n // Inactive materialization cannot install or charge another event. Require\n // every genuine head to have already passed the shared retained cache.\n for (const head of heads) {\n if (\n !publicStoreEnvelope(owner.runtime.store, publicHeadSnapshot(head).id)\n )\n throw new Error('public_view_uncached_head');\n }\n return owner.current(run) && owner.runtime.projectionValid();\n }\n for (const head of heads) {\n const result = insertPublicEnvelope(\n owner.runtime.store,\n publicHeadEnvelope(head)\n );\n if (result !== 'accepted' && result !== 'duplicate') {\n owner.runtime.invalidateProjection();\n return false;\n }\n }\n return owner.runtime.projectionValid();\n}\n\n// Trusted model binding holds only the current projection for this view.\n// Replacement/disposal settles it while retained shared lifecycle proof is live.\nexport function settlePublicViewProjection(\n view: PublicView,\n refresh: () => void\n): void {\n viewOf(view).settleWith(refresh);\n}\n", 59 sha256: 'fa2e27d72b82b6bef73693cf93f19614e61ea51ebd11eb40d8ca4ec723f0c14e' 60 }, 61 'src/lib/publishing/editor-workflow.ts': { 62 source: 63 "import {\n exactLocalFields,\n type PublicDraftForm\n} from '../contracts/local-records.ts';\nimport {\n buildFoodTemplate,\n type FoodDraftErrorCode\n} from '../contracts/food-availability-v1/write.ts';\nimport type { InboxSetupView } from '../messaging/inbox-setup-view.ts';\nimport {\n reviewListingEditor,\n listingEditorReviewCurrent,\n type ListingEditor\n} from './listing-editor.ts';\nimport {\n listingReviewSnapshot,\n type ListingReview,\n type ListingPreview\n} from './prepare-listing.ts';\n\nexport type EditorFormError = Readonly<{\n field: keyof PublicDraftForm;\n message: string;\n}>;\nconst fields = [\n 'title',\n 'description',\n 'location',\n 'amount',\n 'currency',\n 'unit',\n 'quantity',\n 'contactType',\n 'contactValue'\n] as const;\nexport function validateEditorForm(\n input: PublicDraftForm\n): readonly EditorFormError[] {\n try {\n if (\n !exactLocalFields(input, fields) ||\n fields.some((field) => typeof input[field] !== 'string')\n )\n return [{ field: 'title', message: 'Keep all listing fields as text.' }];\n if (input.contactType === '' && input.contactValue !== '')\n return [\n {\n field: 'contactValue',\n message: 'Choose a public contact type or remove the contact details.'\n }\n ];\n const built = buildFoodTemplate({\n identifier: '00000000-0000-4000-8000-000000000001',\n created_at: 1,\n published_at: 1,\n status: 'active',\n title: input.title,\n description: input.description,\n location: input.location,\n amount: input.amount,\n currency: input.currency,\n unit: input.unit,\n ...(input.quantity === '' ? {} : { quantity: input.quantity }),\n ...(input.contactType === ''\n ? {}\n : {\n contact: {\n type: input.contactType,\n value: input.contactValue,\n public: true as const\n }\n })\n });\n if (built.ok) return [];\n const messages: Partial<Record<FoodDraftErrorCode, EditorFormError>> = {\n title_invalid: {\n field: 'title',\n message: 'Use a product name within the public text limit.'\n },\n location_invalid: {\n field: 'location',\n message: 'Use a public area within the text limit.'\n },\n description_invalid: {\n field: 'description',\n message: 'Add a complete description within the public text limit.'\n },\n summary_invalid: {\n field: 'description',\n message: 'Use supported public text in the description.'\n },\n price_invalid: {\n field: 'amount',\n message: 'Use a supported price, currency and price unit.'\n },\n quantity_invalid: {\n field: 'quantity',\n message: 'Use a supported advertised quantity in the selected unit.'\n },\n contact_invalid: {\n field: 'contactValue',\n message: 'Use supported public contact details for the selected type.'\n }\n };\n return [\n messages[built.error.code] ?? {\n field: 'description',\n message: 'The public listing exceeds its supported limits.'\n }\n ];\n } catch {\n return [\n {\n field: 'title',\n message:\n 'The listing fields could not be read. Keep your current input.'\n }\n ];\n }\n}\ndeclare const reviewBrand: unique symbol;\nexport type EditorReview = Readonly<{ [reviewBrand]: true }>;\ntype Owned = Readonly<{ editor: ListingEditor; original: ListingReview }>;\nconst reviews = new WeakMap<EditorReview, Owned>();\nexport type EditorReviewSnapshot = ListingPreview &\n Readonly<{ content: string; tags: readonly (readonly string[])[] }>;\nexport async function openEditorReview(\n editor: ListingEditor,\n setup: InboxSetupView | undefined,\n form: PublicDraftForm\n): Promise<\n | Readonly<{ status: 'review'; review: EditorReview }>\n | Readonly<{\n status: 'blocked';\n errors: readonly EditorFormError[];\n message: string;\n }>\n> {\n const errors = validateEditorForm(form);\n if (errors.length)\n return {\n status: 'blocked',\n errors,\n message: 'Check the linked fields. Your input remains here.'\n };\n const result = await reviewListingEditor(editor, setup, form);\n if (\n result.status !== 'review' ||\n !listingEditorReviewCurrent(editor, result.review)\n )\n return {\n status: 'blocked',\n errors: [],\n message:\n result.status === 'blocked' && result.reason === 'unavailable'\n ? 'Enable messages before reviewing this listing. Your draft remains in this browser.'\n : 'The saved listing or account changed. Keep your input and review the current values again.'\n };\n const review = Object.freeze({}) as EditorReview;\n reviews.set(review, { editor, original: result.review });\n return { status: 'review', review };\n}\nexport function editorReviewSnapshot(\n review: EditorReview\n): EditorReviewSnapshot | undefined {\n const owned = reviews.get(review);\n if (!owned || !listingEditorReviewCurrent(owned.editor, owned.original))\n return;\n const preview = listingReviewSnapshot(owned.original);\n if (!preview) return;\n const wire = JSON.parse(preview.templateWire) as {\n content: string;\n tags: string[][];\n };\n return { ...preview, content: wire.content, tags: wire.tags };\n}\nexport function closeEditorReview(review: EditorReview): void {\n reviews.delete(review);\n}\n", 64 sha256: '5bc8827c5ff167e0974f03a87e4e9db350e42f30c511f199b785c30ad365d838' 65 }, 66 'src/lib/components/ListingEditor.svelte': { 67 source: 68 "<script lang=\"ts\">\n /* global document, setInterval, clearInterval */\n import { getContext, onMount, tick } from 'svelte';\n import ListingReview from './ListingReview.svelte';\n import ConflictNotice from './ConflictNotice.svelte';\n import InboxSetup from './InboxSetup.svelte';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n type PublicRuntimeContext,\n type PublicRuntime\n } from '../runtime/public-runtime.ts';\n import {\n createRuntimeInboxSetupView,\n inboxSetupViewSnapshot,\n subscribeInboxSetupView,\n closeInboxSetupView,\n type InboxSetupView\n } from '../messaging/inbox-setup-view.ts';\n import {\n openEditorReview,\n editorReviewSnapshot,\n closeEditorReview,\n type EditorReview,\n type EditorFormError\n } from '../publishing/editor-workflow.ts';\n import CapabilityGate from './CapabilityGate.svelte';\n import Notice from './Notice.svelte';\n import OperationStatus from './OperationStatus.svelte';\n import { foodUnits } from '../contracts/food-availability-v1/values.ts';\n import type { PublicDraftForm } from '../contracts/local-records.ts';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n type IdentityViewContext\n } from '../runtime/view-context.ts';\n import {\n openListingEditor,\n listingEditorSnapshot,\n editListingEditor,\n saveAndCloseListingEditor,\n closeListingEditor,\n subscribeListingEditor,\n listingEditorEditSource,\n observeListingEditor,\n type ListingEditor as Editor,\n type ListingEditorRoute,\n type ListingEditorSnapshot\n } from '../publishing/listing-editor.ts';\n import { internalHref } from '../navigation-url.ts';\n let {\n route,\n onfirstsave,\n onsavedclose,\n inboxController\n }: {\n route: ListingEditorRoute;\n onfirstsave?: (draftId: string, current: () => boolean) => Promise<void>;\n onsavedclose?: () => Promise<void>;\n inboxController?: InboxSetupView;\n } = $props();\n const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);\n const publicContext = getContext<PublicRuntimeContext>(\n PUBLIC_RUNTIME_CONTEXT\n );\n let runtime = $state.raw<PublicRuntime | undefined>(),\n setup = $state.raw<InboxSetupView | undefined>();\n let setupState = $state(inboxSetupViewSnapshot(undefined));\n let review = $state.raw<EditorReview | undefined>(),\n reviewBusy = $state(false);\n let errors = $state<readonly EditorFormError[]>([]),\n reviewMessage = $state('');\n let identity = $state(identityViewSnapshot(context)),\n mounted = $state(false),\n editor = $state.raw<Editor | undefined>(),\n snapshot = $state<ListingEditorSnapshot>(),\n unavailable = $state(false);\n let closeBusy = $state(false),\n navigationFailed = $state(false);\n let firstNavigation: Promise<void> | undefined;\n let firstOwner: Editor | undefined;\n type Form = {\n -readonly [Key in keyof PublicDraftForm]: PublicDraftForm[Key];\n };\n const blankForm = (): Form => ({\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n });\n let form = $state<Form>(blankForm());\n const admittedAuthor = $derived(\n identity.identity.state !== 'guest' && identity.identity.state !== 'pending'\n ? identity.identity.publicKey\n : undefined\n );\n const active = $derived(mounted && identity.mounted);\n const visible = $derived(\n snapshot &&\n editor &&\n identity.mounted &&\n identity.identity.state !== 'guest' &&\n identity.identity.state !== 'pending' &&\n identity.identity.publicKey === snapshot.owner &&\n listingEditorSnapshot(editor)\n );\n onMount(() => {\n mounted = true;\n const off = subscribeIdentityView(context, (next) => {\n identity = next;\n });\n if (publicContext)\n void publicRuntimeReady(publicContext)\n .then((value) => {\n if (mounted) runtime = value;\n })\n .catch(() => {\n /* Draft saving does not depend on inbox setup. */\n });\n return () => {\n mounted = false;\n off();\n };\n });\n $effect(() => {\n const author = admittedAuthor,\n available = active,\n source = runtime,\n supplied = inboxController;\n if (!available || !author) {\n setup = undefined;\n setupState = inboxSetupViewSnapshot(undefined);\n return;\n }\n const owned =\n supplied ?? (source && createRuntimeInboxSetupView(context, source));\n setup = owned;\n const off = owned\n ? subscribeInboxSetupView(owned, (next) => {\n setupState = next;\n })\n : () => {};\n return () => {\n off();\n if (owned) closeInboxSetupView(owned);\n };\n });\n const visibleReview = $derived.by(() => {\n if (!setupState.owner || !snapshot || !visible || !review) return;\n return editorReviewSnapshot(review) ? review : undefined;\n });\n $effect(() => {\n const resource = route,\n author = admittedAuthor,\n editRuntime = route.mode === 'edit' ? runtime : undefined;\n if (!active || !author) {\n editor = undefined;\n snapshot = undefined;\n form = blankForm();\n unavailable = false;\n return;\n }\n const cancellation = new AbortController();\n let alive = true,\n owned: Editor | undefined,\n off = () => {};\n const observer =\n resource.mode === 'edit'\n ? setInterval(() => {\n if (owned) observeListingEditor(owned);\n }, 250)\n : undefined;\n editor = undefined;\n snapshot = undefined;\n review = undefined;\n errors = [];\n reviewMessage = '';\n form = blankForm();\n unavailable = false;\n void openListingEditor(\n context,\n resource,\n cancellation.signal,\n editRuntime\n ).then((result) => {\n if (!alive) {\n if (result.status === 'ready') closeListingEditor(result.editor);\n return;\n }\n if (result.status !== 'ready') {\n unavailable = true;\n return;\n }\n owned = result.editor;\n editor = owned;\n const next = listingEditorSnapshot(owned);\n if (!next) {\n unavailable = true;\n return;\n }\n snapshot = next;\n form = { ...next.form };\n off = subscribeListingEditor(owned, () => {\n snapshot = owned && listingEditorSnapshot(owned);\n if (\n snapshot?.state === 'saved' &&\n snapshot.draftId &&\n resource.mode === 'new' &&\n owned &&\n firstOwner !== owned &&\n !closeBusy &&\n onfirstsave\n ) {\n firstOwner = owned;\n firstNavigation = onfirstsave(\n snapshot.draftId,\n () =>\n alive &&\n mounted &&\n editor === owned &&\n !!owned &&\n !!listingEditorSnapshot(owned)\n ).catch(() => {\n if (alive) navigationFailed = true;\n });\n }\n if (!snapshot) {\n unavailable = true;\n form = blankForm();\n }\n });\n });\n return () => {\n alive = false;\n if (observer !== undefined) clearInterval(observer);\n cancellation.abort();\n off();\n if (owned) closeListingEditor(owned);\n form = blankForm();\n };\n });\n function changed() {\n const original = editor;\n if (!original || !listingEditorSnapshot(original)?.editable) return;\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n void editListingEditor(original, { ...form });\n }\n async function showReview() {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (\n reviewBusy ||\n closeBusy ||\n !original ||\n !listingEditorSnapshot(original)?.editable\n )\n return;\n reviewBusy = true;\n try {\n const result = await openEditorReview(original, setup, { ...form });\n if (\n !mounted ||\n editor !== original ||\n route !== resource ||\n admittedAuthor !== author ||\n !listingEditorSnapshot(original)\n ) {\n if (result.status === 'review') closeEditorReview(result.review);\n return;\n }\n if (result.status === 'blocked') {\n errors = result.errors;\n reviewMessage = result.message;\n await tick();\n document.querySelector<HTMLElement>('#listing-review-errors')?.focus();\n return;\n }\n if (review) closeEditorReview(review);\n review = result.review;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor === original && editorReviewSnapshot(result.review))\n document.querySelector<HTMLElement>('#listing-review-heading')?.focus();\n } finally {\n reviewBusy = false;\n }\n }\n async function editDetails() {\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor && listingEditorSnapshot(editor)?.editable)\n document.querySelector<HTMLInputElement>('#listing-title')?.focus();\n }\n function fieldError(field: keyof PublicDraftForm) {\n return errors.find((value) => value.field === field);\n }\n function fieldId(field: keyof PublicDraftForm) {\n return (\n 'listing-' +\n (field === 'contactType'\n ? 'contact-type'\n : field === 'contactValue'\n ? 'contact-value'\n : field)\n );\n }\n function connect() {\n return connectIdentityView(context);\n }\n async function saveClose() {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (closeBusy || !original || !listingEditorSnapshot(original)?.editable)\n return;\n closeBusy = true;\n try {\n const saved = await saveAndCloseListingEditor(original);\n await firstNavigation;\n if (\n !saved ||\n !mounted ||\n editor !== original ||\n route !== resource ||\n !author ||\n admittedAuthor !== author\n )\n return;\n await onsavedclose?.();\n } catch {\n if (mounted) navigationFailed = true;\n } finally {\n closeBusy = false;\n }\n }\n function disconnect() {\n disconnectIdentityView(context);\n }\n const title = $derived(\n route.mode === 'new'\n ? 'New listing'\n : route.mode === 'draft'\n ? 'Continue draft'\n : 'Edit listing'\n );\n</script>\n\n<svelte:head\n ><title>{title} \u00b7 HarvestCircle</title><meta\n name=\"robots\"\n content=\"noindex\"\n /></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a\n href={internalHref(\n route.mode === 'edit' ? `/products/${route.naddr}` : '/selling'\n )}>{route.mode === 'edit' ? 'Back to listing' : 'Back to Selling'}</a\n >\n <h1>{title}</h1>\n {#if !visible}\n <CapabilityGate\n identity={identity.identity}\n required=\"connection\"\n focusTarget=\"protected\"\n onconnect={mounted ? connect : undefined}\n ondisconnect={disconnect}\n />\n {#if unavailable}<Notice\n tone=\"warning\"\n text={route.mode === 'draft'\n ? 'This draft is not available here.'\n : route.mode === 'edit'\n ? 'Supported local listing values are not available for editing. Keep this listing read-only.'\n : 'Browser storage is unavailable. Your existing local data has not been reset.'}\n />{:else if identity.identity.state !== 'guest' && identity.identity.state !== 'pending'}<p\n role=\"status\"\n >\n Loading local values.\n </p>{/if}\n {:else}\n {#if route.mode === 'edit' && editor && listingEditorEditSource(editor)}\n <ConflictNotice\n source={listingEditorEditSource(editor)!}\n proposed={form}\n />\n {#if visible.editable}<Notice\n tone=\"info\"\n text=\"These changes can be saved locally. Publishing changes is not available.\"\n />{/if}\n {/if}\n {#if !visible.editable}<Notice\n tone=\"info\"\n text={route.mode === 'draft'\n ? 'This draft has a retained listing operation. Keep its original outcome for reconciliation.'\n : 'These retained local values are read-only until the current listing is checked.'}\n />{:else}<p>\n Changes are saved in this browser. Browser storage is not a backup.\n </p>{/if}\n {#if visibleReview}<ListingReview\n review={visibleReview}\n onedit={editDetails}\n />{:else}\n {#if reviewMessage}<Notice tone=\"warning\" text={reviewMessage} />{/if}\n {#if errors.length}<div\n id=\"listing-review-errors\"\n tabindex=\"-1\"\n role=\"alert\"\n >\n <p>Check these listing fields. Your input remains here.</p>\n <ul>\n {#each errors as error (error.field)}<li>\n <a href={internalHref('#' + fieldId(error.field))}\n >{error.message}</a\n >\n </li>{/each}\n </ul>\n </div>{/if}\n <form\n class=\"stack\"\n onsubmit={(event) => event.preventDefault()}\n novalidate\n >\n <div class=\"field\">\n <label class=\"label\" for=\"listing-title\">Product name</label><input\n id=\"listing-title\"\n aria-invalid={fieldError('title') ? 'true' : undefined}\n aria-errormessage={fieldError('title')\n ? 'listing-title-error'\n : undefined}\n type=\"text\"\n value={form.title}\n oninput={(event) => {\n form = { ...form, title: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('title')}<p id=\"listing-title-error\">\n {fieldError('title')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-description\">Description</label\n ><textarea\n id=\"listing-description\"\n aria-invalid={fieldError('description') ? 'true' : undefined}\n aria-errormessage={fieldError('description')\n ? 'listing-description-error'\n : undefined}\n rows=\"6\"\n value={form.description}\n oninput={(event) => {\n form = { ...form, description: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}></textarea>\n {#if fieldError('description')}<p id=\"listing-description-error\">\n {fieldError('description')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-location\">Public area</label>\n <p id=\"listing-location-hint\" class=\"text-small\">\n A town or collection area is enough.\n </p>\n <input\n id=\"listing-location\"\n aria-invalid={fieldError('location') ? 'true' : undefined}\n aria-errormessage={fieldError('location')\n ? 'listing-location-error'\n : undefined}\n type=\"text\"\n aria-describedby=\"listing-location-hint\"\n value={form.location}\n oninput={(event) => {\n form = { ...form, location: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('location')}<p id=\"listing-location-error\">\n {fieldError('location')?.message}\n </p>{/if}\n </div>\n <div class=\"cluster\">\n <div class=\"field\">\n <label class=\"label\" for=\"listing-amount\">Price</label><input\n id=\"listing-amount\"\n aria-invalid={fieldError('amount') ? 'true' : undefined}\n aria-errormessage={fieldError('amount')\n ? 'listing-amount-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n value={form.amount}\n oninput={(event) => {\n form = { ...form, amount: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('amount')}<p id=\"listing-amount-error\">\n {fieldError('amount')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-currency\">Currency</label><input\n id=\"listing-currency\"\n aria-invalid={fieldError('currency') ? 'true' : undefined}\n aria-errormessage={fieldError('currency')\n ? 'listing-currency-error'\n : undefined}\n type=\"text\"\n maxlength=\"3\"\n value={form.currency}\n oninput={(event) => {\n form = { ...form, currency: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('currency')}<p id=\"listing-currency-error\">\n {fieldError('currency')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-unit\">Per</label><select\n id=\"listing-unit\"\n aria-invalid={fieldError('unit') ? 'true' : undefined}\n aria-errormessage={fieldError('unit')\n ? 'listing-unit-error'\n : undefined}\n value={form.unit}\n onchange={(event) => {\n form = { ...form, unit: event.currentTarget.value };\n changed();\n }}\n disabled={!visible.editable}\n ><option value=\"\">Choose a unit</option\n >{#each foodUnits as unit (unit)}<option value={unit}\n >{unit}</option\n >{/each}</select\n >\n {#if fieldError('unit')}<p id=\"listing-unit-error\">\n {fieldError('unit')?.message}\n </p>{/if}\n </div>\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-quantity\"\n >Advertised quantity (optional)</label\n >\n <p id=\"listing-quantity-unit\">\n {form.unit || 'Uses the selected price unit'}\n </p>\n <input\n id=\"listing-quantity\"\n aria-invalid={fieldError('quantity') ? 'true' : undefined}\n aria-errormessage={fieldError('quantity')\n ? 'listing-quantity-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n aria-describedby=\"listing-quantity-unit\"\n value={form.quantity}\n oninput={(event) => {\n form = { ...form, quantity: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('quantity')}<p id=\"listing-quantity-error\">\n {fieldError('quantity')?.message}\n </p>{/if}\n </div>\n <details>\n <summary>Add public contact details (optional)</summary>\n <div class=\"stack\">\n <p>Only add contact details you want to include publicly.</p>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-type\"\n >Public contact type</label\n ><select\n id=\"listing-contact-type\"\n aria-invalid={fieldError('contactType') ? 'true' : undefined}\n aria-errormessage={fieldError('contactType')\n ? 'listing-contact-type-error'\n : undefined}\n value={form.contactType}\n onchange={(event) => {\n const value = event.currentTarget.value;\n if (\n value === '' ||\n value === 'email' ||\n value === 'phone' ||\n value === 'https'\n ) {\n form = { ...form, contactType: value };\n changed();\n }\n }}\n disabled={!visible.editable}\n ><option value=\"\">No public contact</option><option\n value=\"email\">Email</option\n ><option value=\"phone\">Phone</option><option value=\"https\"\n >Website</option\n ></select\n >\n {#if fieldError('contactType')}<p id=\"listing-contact-type-error\">\n {fieldError('contactType')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-value\"\n >Public contact details</label\n ><input\n id=\"listing-contact-value\"\n aria-invalid={fieldError('contactValue') ? 'true' : undefined}\n aria-errormessage={fieldError('contactValue')\n ? 'listing-contact-value-error'\n : undefined}\n type=\"text\"\n value={form.contactValue}\n oninput={(event) => {\n form = { ...form, contactValue: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n {#if fieldError('contactValue')}<p\n id=\"listing-contact-value-error\"\n >\n {fieldError('contactValue')?.message}\n </p>{/if}\n </div>\n </div>\n </details>\n </form>\n {#if visible.editable && route.mode !== 'edit'}<button\n type=\"button\"\n onclick={showReview}\n disabled={reviewBusy || closeBusy}\n >{reviewBusy ? 'Preparing review' : 'Review listing'}</button\n >{/if}\n {/if}\n {#if visible.editable && route.mode !== 'edit' && setup}<InboxSetup\n controller={setup}\n inline\n />{/if}\n {#each visible.operations as operation (operation)}<OperationStatus\n publicOperation={operation}\n />{/each}\n {#if visible.editable}<button\n type=\"button\"\n onclick={saveClose}\n disabled={closeBusy || reviewBusy}>Save and close</button\n >{/if}\n {#if navigationFailed}<Notice\n tone=\"warning\"\n text=\"Navigation did not complete. Your saved local data remains in this browser.\"\n />{/if}\n {#if visible.editable}<p role=\"status\">\n {visible.state === 'saved'\n ? 'Saved in this browser.'\n : visible.state === 'saving'\n ? 'Saving in this browser.'\n : visible.state === 'failed'\n ? 'Not saved. Keep your current input here.'\n : 'Not yet saved.'}\n </p>\n {#if visible.failure}<Notice\n tone=\"warning\"\n text=\"Saving did not complete. Keep your current input. Existing local data has not been reset.\"\n />{/if}{/if}\n {/if}\n</div>\n", 69 sha256: '3b1d6248c256ce02a668a2c92654816dd0c2659b7b430d5e1d3aeba6f9326bfa' 70 }, 71 'src/lib/components/ListingReview.svelte': { 72 source: 73 '<script lang="ts">\n import Notice from \'./Notice.svelte\';\n import {\n editorReviewSnapshot,\n type EditorReview\n } from \'../publishing/editor-workflow.ts\';\n let { review, onedit }: { review: EditorReview; onedit: () => void } =\n $props();\n const preview = $derived(editorReviewSnapshot(review));\n function tag(name: string) {\n return (\n preview?.tags\n .find((value) => value[0] === name)\n ?.slice(1)\n .join(\' \') ?? \'\'\n );\n }\n</script>\n\n{#if preview}\n <section class="stack" aria-label="Public listing review">\n <h2 id="listing-review-heading" tabindex="-1">Public review</h2>\n <p>Check the complete public listing before any signing or publication.</p>\n <h3>{tag(\'title\')}</h3>\n <p class="description" id="listing-review-content">{preview.content}</p>\n <dl>\n <dt>Derived summary</dt>\n <dd>{preview.summary}</dd>\n <dt>Public area</dt>\n <dd>{tag(\'location\')}</dd>\n <dt>Price</dt>\n <dd>{tag(\'price\')} per {tag(\'radroots:price_unit\')}</dd>\n {#if tag(\'radroots:quantity\')}<dt>Advertised quantity</dt>\n <dd>{tag(\'radroots:quantity\')}</dd>{/if}\n <dt>Publisher</dt>\n <dd class="key">{preview.owner}</dd>\n <dt>Public destinations</dt>\n <dd>\n <ul>\n {#each preview.targets as target (target)}<li class="key">\n {target}\n </li>{/each}\n </ul>\n </dd>\n </dl>\n <p>Messages: ready to receive replies</p>\n <p>This review has not requested a signature or published the listing.</p>\n <button type="button" onclick={onedit}>Edit details</button>\n </section>\n{:else}\n <Notice\n tone="warning"\n text="This review is no longer current. Return to the current listing values."\n />\n <button type="button" onclick={onedit}>Edit details</button>\n{/if}\n', 74 sha256: 'bf4e6bf0fc76fa12672fabc441e1058d73c1f281a0a560aeafbdaa2aa36f6f90' 75 }, 76 'src/lib/persistence/public-publications.ts': { 77 source: 78 "import type { PublicDraftRecord } from '../contracts/local-records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n createPublicDraftRepository,\n publicDraftRepositoryOwner,\n type PublicDraftRepository\n} from './drafts.ts';\nimport {\n browserDatabaseTransaction,\n type BrowserDatabase\n} from './database.ts';\nimport {\n createPublicQuotaRepository,\n publicQuotaOwner,\n claimPublicDraftOperation,\n type PublicQuotaRepository,\n type PublicQuotaFailure\n} from './quota.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n publicDraftControllerOwnership,\n type PublicDraftController\n} from '../publishing/draft-controller.ts';\nimport { exactLocalFields } from '../contracts/local-records.ts';\n\ndeclare const repositoryBrand: unique symbol;\nexport type PublicPublicationRepository = Readonly<{ [repositoryBrand]: true }>;\ntype Scope = Readonly<{\n database: BrowserDatabase;\n drafts: PublicDraftRepository;\n quota: PublicQuotaRepository;\n owner: string;\n}>;\nconst repositories = new WeakMap<PublicPublicationRepository, Scope>();\nfunction scopeOf(repository: PublicPublicationRepository): Scope | undefined {\n const scope = repositories.get(repository);\n return scope &&\n publicDraftRepositoryOwner(scope.drafts) === scope.owner &&\n publicQuotaOwner(scope.quota) === scope.owner\n ? scope\n : undefined;\n}\nexport function createPublicPublicationRepository(\n database: BrowserDatabase,\n owner: unknown\n): PublicPublicationRepository | undefined {\n const drafts = createPublicDraftRepository(database, owner),\n quota = createPublicQuotaRepository(database, owner);\n const admittedOwner = drafts && publicDraftRepositoryOwner(drafts);\n if (\n !drafts ||\n !quota ||\n !admittedOwner ||\n publicQuotaOwner(quota) !== admittedOwner\n )\n return undefined;\n const handle = Object.freeze({}) as PublicPublicationRepository;\n repositories.set(handle, { database, drafts, quota, owner: admittedOwner });\n return handle;\n}\nexport function publicPublicationDraftRepository(\n repository: PublicPublicationRepository\n): PublicDraftRepository | undefined {\n return scopeOf(repository)?.drafts;\n}\nexport function publicPublicationOwner(\n repository: PublicPublicationRepository\n): string | undefined {\n return scopeOf(repository)?.owner;\n}\n// Original same-database quota custody only; it does not mint an identity,\n// extension approval, lock lease or public network capability.\nexport function publicPublicationQuotaRepository(\n repository: PublicPublicationRepository\n): PublicQuotaRepository | undefined {\n return scopeOf(repository)?.quota;\n}\nexport type PublicListingSave =\n | Readonly<{ status: 'saved' | 'existing'; record: PublicRecordHandle }>\n | Readonly<{ status: PublicQuotaFailure | 'busy' }>;\nexport type PublicListingRead =\n | Readonly<{ status: 'found'; record: PublicRecordHandle }>\n | Readonly<{ status: 'missing' | 'unavailable' | 'corrupt_record' }>;\n// Readback is exact local observation, never global absence or relay receipt.\nexport function readPublicListingIntent(\n repository: PublicPublicationRepository,\n command: unknown\n): Promise<PublicListingRead> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(command);\n if (!scope || !id) return Promise.resolve({ status: 'unavailable' });\n let transaction: IDBTransaction;\n try {\n transaction = browserDatabaseTransaction(\n scope.database,\n ['public_operations'],\n 'readonly'\n );\n } catch {\n return Promise.resolve({ status: 'unavailable' });\n }\n return new Promise((resolve) => {\n let decision: PublicListingRead | undefined;\n transaction.addEventListener('complete', () =>\n resolve(\n scopeOf(repository)\n ? (decision ?? { status: 'unavailable' })\n : { status: 'unavailable' }\n )\n );\n transaction.addEventListener('abort', () =>\n resolve({ status: 'unavailable' })\n );\n try {\n const request = transaction\n .objectStore('public_operations')\n .get([scope.owner, id]);\n request.addEventListener('success', () => {\n const value: unknown = request.result;\n if (value === undefined) {\n decision = { status: 'missing' };\n return;\n }\n if (\n !exactLocalFields(value, ['owner', 'id', 'wire']) ||\n value.owner !== scope.owner ||\n value.id !== id\n ) {\n decision = { status: 'corrupt_record' };\n return;\n }\n const decoded = decodePublicRecord(value.wire, scope.owner, id);\n const row =\n decoded.ok && publicRecordSnapshot(decoded.value, scope.owner, id);\n decision =\n decoded.ok && row && row.family === 'public_operation'\n ? { status: 'found', record: decoded.value }\n : { status: 'corrupt_record' };\n });\n } catch {\n decision = { status: 'unavailable' };\n try {\n transaction.abort();\n } catch {\n resolve({ status: 'unavailable' });\n }\n }\n });\n}\n// Only a short local transaction is held. Extension/relay effects are later\n// checkpoint owners and are absent from this repository.\nexport async function savePublicListingIntent(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n record: PublicRecordHandle,\n expected: PublicDraftRecord,\n editVersion: number,\n command: string,\n current: (this: void) => boolean\n): Promise<PublicListingSave> {\n try {\n const scope = scopeOf(repository),\n custody = publicDraftControllerOwnership(controller);\n const row = scope && publicRecordSnapshot(record, scope.owner, command);\n if (\n !scope ||\n !custody ||\n custody.repository !== scope.drafts ||\n !row ||\n row.family !== 'public_operation' ||\n row.source.type !== 'draft'\n )\n return { status: 'invalid_scope' };\n if (\n !current() ||\n typeof window === 'undefined' ||\n !navigator.locks?.request\n )\n return { status: 'unavailable' };\n return await navigator.locks.request(\n 'harvestcircle:owner:' + scope.owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<PublicListingSave> => {\n if (!lock) return { status: 'busy' };\n const fresh = (): boolean => scopeOf(repository) === scope && current();\n if (!fresh()) return { status: 'unavailable' };\n const claimed = await claimPublicDraftOperation(\n scope.quota,\n row.id,\n record,\n {\n expected,\n current: fresh,\n draftCurrent: () =>\n custody.current(JSON.stringify(expected), editVersion)\n }\n );\n if (!fresh()) return { status: 'unavailable' };\n if (claimed.ok)\n return {\n status: claimed.value.state === 'created' ? 'saved' : 'existing',\n record: claimed.value.record\n };\n if (claimed.reason === 'unknown_completion') {\n const observed = await readPublicListingIntent(repository, row.id);\n const original =\n observed.status === 'found' &&\n publicRecordSnapshot(observed.record, scope.owner, row.id);\n if (!fresh()) return { status: 'unavailable' };\n if (\n observed.status === 'found' &&\n original &&\n original.family === 'public_operation' &&\n JSON.stringify(original.source) === JSON.stringify(row.source) &&\n JSON.stringify(original.capture) === JSON.stringify(row.capture)\n )\n return { status: 'existing', record: observed.record };\n if (original) return { status: 'conflict' };\n }\n return { status: claimed.reason };\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n", 79 sha256: '5a995002cbae1a62ecce9b34770baad102c5c90340da922593e3cc8d9f5c3384' 80 }, 81 'src/lib/persistence/quota.ts': { 82 source: 83 "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport {\n exactLocalFields,\n type PublicRecord,\n type PublicDraftRecord\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';\nimport {\n browserDatabaseState,\n browserDatabaseTransaction,\n type BrowserDatabase\n} from './database.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n publicInventoryRow,\n PUBLIC_CLEANUP_CONSEQUENCES,\n type PublicInventoryRow\n} from './local-inventory.ts';\n\nimport {\n publicTransitionIdentity,\n publicTransitionSnapshot,\n type PublicOperationTransition\n} from './artifact-records.ts';\nimport { decideFrozenTransition } from './operation-transactions.ts';\n\ndeclare const repositoryBrand: unique symbol;\ndeclare const inventoryBrand: unique symbol;\ndeclare const cleanupBrand: unique symbol;\nexport type PublicQuotaRepository = Readonly<{ [repositoryBrand]: true }>;\nexport type PublicInventory = Readonly<{ [inventoryBrand]: true }>;\nexport type PublicCleanup = Readonly<{ [cleanupBrand]: true }>;\nexport type PublicQuotaFailure =\n | 'invalid_scope'\n | 'invalid_record'\n | 'invalid_selection'\n | 'protected'\n | 'conflict'\n | 'capacity'\n | 'corrupt_record'\n | 'unavailable'\n | 'aborted'\n | 'unknown_completion';\nexport type PublicQuotaResult<T> =\n | Readonly<{ ok: true; value: T }>\n | Readonly<{ ok: false; reason: PublicQuotaFailure }>;\ntype Scope = Readonly<{ database: BrowserDatabase; owner: string }>;\ntype Store = 'public_drafts' | 'public_operations' | 'preference_operations';\ntype Row = Readonly<{\n store: Store;\n wire: string;\n record: PublicRecord;\n bytes: number;\n}>;\ntype Inspection = Readonly<{\n repository: PublicQuotaRepository;\n rows: readonly Row[];\n}>;\ntype Cleanup = Readonly<{ inventory: Inspection; selected: readonly string[] }>;\nconst repositories = new WeakMap<PublicQuotaRepository, Scope>();\nconst inventories = new WeakMap<PublicInventory, Inspection>();\nconst cleanups = new WeakMap<PublicCleanup, Cleanup>();\nconst stores: readonly Store[] = [\n 'public_drafts',\n 'public_operations',\n 'preference_operations'\n];\nfunction failed(reason: PublicQuotaFailure): PublicQuotaResult<never> {\n return { ok: false, reason };\n}\nfunction scopeOf(repository: PublicQuotaRepository): Scope | undefined {\n const scope = repositories.get(repository);\n try {\n return scope && browserDatabaseState(scope.database).state === 'ready'\n ? scope\n : undefined;\n } catch {\n return undefined;\n }\n}\n// Metadata only; this does not grant installed-account or effect authority.\nexport function publicQuotaOwner(\n repository: PublicQuotaRepository\n): string | undefined {\n return scopeOf(repository)?.owner;\n}\n// A namespace capability only; installed-account authorization belongs to the\n// account workflow. This repository never acquires any private store.\nexport function createPublicQuotaRepository(\n database: BrowserDatabase,\n expectedOwner: unknown\n): PublicQuotaRepository | undefined {\n const owner = canonicalPublicKey(expectedOwner);\n try {\n if (!owner || browserDatabaseState(database).state !== 'ready')\n return undefined;\n const handle = Object.freeze({}) as PublicQuotaRepository;\n repositories.set(handle, { database, owner });\n return handle;\n } catch {\n return undefined;\n }\n}\nfunction stored(\n value: unknown,\n store: Store,\n owner: string,\n id: string\n): Row | undefined {\n if (\n !exactLocalFields(value, ['owner', 'id', 'wire']) ||\n value.owner !== owner ||\n value.id !== id ||\n typeof value.wire !== 'string'\n )\n return undefined;\n const admitted = decodePublicRecord(value.wire, owner, id);\n if (!admitted.ok) return undefined;\n const record = publicRecordSnapshot(admitted.value, owner, id);\n const family =\n store === 'public_drafts'\n ? 'public_draft'\n : store === 'public_operations'\n ? 'public_operation'\n : 'preference_operation';\n return record?.family === family\n ? {\n store,\n record,\n wire: value.wire,\n bytes: new TextEncoder().encode(value.wire).length\n }\n : undefined;\n}\nfunction transaction<T>(\n scope: Scope,\n mode: 'readonly' | 'readwrite',\n finish: (\n rows: readonly Row[],\n transaction: IDBTransaction,\n refuse: (reason: PublicQuotaFailure) => void\n ) => PublicQuotaResult<T> | undefined\n): Promise<PublicQuotaResult<T>> {\n let active: IDBTransaction;\n try {\n active = browserDatabaseTransaction(scope.database, stores, mode);\n } catch {\n return Promise.resolve(failed('unavailable'));\n }\n return new Promise((resolve) => {\n let result: PublicQuotaResult<T> | undefined;\n let rows = Array.from<Row>([]),\n draftCount = 0,\n operationCount = 0,\n operationBytes = 0;\n function refuse(reason: PublicQuotaFailure) {\n result = failed(reason);\n try {\n active.abort();\n } catch {\n result = failed('unknown_completion');\n }\n }\n active.addEventListener('complete', () =>\n resolve(result ?? failed('unknown_completion'))\n );\n active.addEventListener('abort', () =>\n resolve(result && !result.ok ? result : failed('aborted'))\n );\n function scan(index: number): void {\n try {\n const store = stores[index];\n if (store === undefined) {\n const finished = finish(rows, active, refuse);\n if (finished !== undefined) result = finished;\n return;\n }\n const request = active\n .objectStore(store)\n .index('by_owner')\n .openCursor(IDBKeyRange.only(scope.owner));\n request.addEventListener('success', () => {\n try {\n const cursor = request.result;\n if (!cursor) {\n scan(index + 1);\n return;\n }\n const key = cursor.primaryKey;\n const id =\n Array.isArray(key) && key.length === 2 && key[0] === scope.owner\n ? canonicalLocalId(key[1])\n : undefined;\n const row = id && stored(cursor.value, store, scope.owner, id);\n if (!row) {\n refuse('corrupt_record');\n return;\n }\n if (row.record.family === 'public_draft') draftCount++;\n else {\n operationCount++;\n operationBytes += row.bytes;\n }\n if (\n draftCount > LOCAL_PERSISTENCE_BUDGETS.publicDrafts ||\n operationCount > LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operationBytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n rows = rows.concat(row);\n cursor.continue();\n } catch {\n refuse('aborted');\n }\n });\n } catch {\n refuse('aborted');\n }\n }\n scan(0);\n });\n}\n// Explicit new-row admission only. Artifact/CAS transitions retain HCP050.\n// Logical bytes include the exact stored record wire, not browser disk/heap use.\nexport function admitPublicOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle\n): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n const record = publicRecordSnapshot(handle, scope.owner, id),\n wire = publicRecordWire(handle, scope.owner, id);\n if (\n !record ||\n !wire ||\n record.family === 'public_draft' ||\n record.revision !== 0\n )\n return Promise.resolve(failed('invalid_record'));\n const store: Store =\n record.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const bytes = new TextEncoder().encode(wire).length;\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const previous = rows.find(\n (row) => row.store === store && row.record.id === id\n );\n if (previous)\n return previous.wire === wire\n ? { ok: true, value: { id, revision: 0 } }\n : (refuse('conflict'), undefined);\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n if (\n operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operations.reduce((sum, row) => sum + row.bytes, bytes) >\n LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n active.objectStore(store).put({ owner: scope.owner, id, wire });\n return { ok: true, value: { id, revision: 0 } };\n });\n}\n// Claim under the caller's origin/author Web Lock. A previous capture is never\n// overwritten or automatically signed again, even after a page lost its lock.\n// No extension/network await occurs inside the short transaction.\nexport function claimPublicOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n return claimOperation(repository, expectedId, handle);\n}\ntype DraftAdmission = Readonly<{\n expected: PublicDraftRecord;\n current(this: void): boolean;\n draftCurrent(this: void): boolean;\n}>;\n// Storage-only atomic draft/CAS reservation. Current original account/review\n// ownership is supplied by the public listing command owner, never a UI flag.\n// Existing commands retain their original capture even after future draft edits.\nexport function claimPublicDraftOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle,\n admission: DraftAdmission\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n return claimOperation(repository, expectedId, handle, admission);\n}\nfunction claimOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle,\n draft?: DraftAdmission\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n const record = publicRecordSnapshot(handle, scope.owner, id),\n wire = publicRecordWire(handle, scope.owner, id);\n if (\n !record ||\n !wire ||\n record.family === 'public_draft' ||\n record.revision !== 0 ||\n record.artifact !== null\n )\n return Promise.resolve(failed('invalid_record'));\n const store: Store =\n record.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const bytes = new TextEncoder().encode(wire).length;\n return transaction<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >(scope, 'readwrite', (rows, active, refuse) => {\n if (draft && !draft.current()) {\n refuse('unavailable');\n return;\n }\n const previous = rows.find(\n (row) => row.record.family !== 'public_draft' && row.record.id === id\n );\n if (previous) {\n const original = previous.record;\n if (\n original.family === 'public_draft' ||\n original.family !== record.family ||\n JSON.stringify(original.source) !== JSON.stringify(record.source) ||\n JSON.stringify(original.capture) !== JSON.stringify(record.capture) ||\n ('consent' in original ? original.consent : null) !==\n ('consent' in record ? record.consent : null)\n ) {\n refuse('conflict');\n return;\n }\n const decoded = decodePublicRecord(previous.wire, scope.owner, id);\n if (!decoded.ok) {\n refuse('corrupt_record');\n return;\n }\n return { ok: true, value: { state: 'existing', record: decoded.value } };\n }\n if (draft) {\n const source =\n record.family === 'public_operation' ? record.source : undefined;\n const previousDraft = rows.find(\n (row) =>\n row.record.family === 'public_draft' &&\n row.record.id === draft.expected.id\n );\n if (\n !source ||\n source.type !== 'draft' ||\n draft.expected.owner !== scope.owner ||\n source.id !== draft.expected.id ||\n source.revision !== draft.expected.revision ||\n !previousDraft ||\n JSON.stringify(previousDraft.record) !==\n JSON.stringify(draft.expected) ||\n !draft.draftCurrent()\n ) {\n refuse('conflict');\n return;\n }\n }\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n if (\n operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operations.reduce((sum, row) => sum + row.bytes, bytes) >\n LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n if (draft && (!draft.current() || !draft.draftCurrent())) {\n refuse('conflict');\n return;\n }\n active.objectStore(store).put({ owner: scope.owner, id, wire });\n return { ok: true, value: { state: 'created', record: handle } };\n });\n}\nexport function inspectPublicStorage(\n repository: PublicQuotaRepository\n): Promise<PublicQuotaResult<PublicInventory>> {\n const scope = scopeOf(repository);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n return transaction(scope, 'readonly', (rows) => {\n const handle = Object.freeze({}) as PublicInventory;\n inventories.set(handle, { repository, rows });\n return { ok: true, value: handle };\n });\n}\nexport function publicInventorySnapshot(\n repository: PublicQuotaRepository,\n handle: PublicInventory\n):\n | Readonly<{ rows: readonly PublicInventoryRow[]; consequences: string }>\n | undefined {\n const inventory = inventories.get(handle);\n return scopeOf(repository) && inventory?.repository === repository\n ? {\n rows: inventory.rows.map((row) =>\n publicInventoryRow(row.record, row.bytes)\n ),\n consequences: PUBLIC_CLEANUP_CONSEQUENCES\n }\n : undefined;\n}\nexport function reviewPublicCleanup(\n repository: PublicQuotaRepository,\n handle: PublicInventory,\n selection: unknown\n): PublicQuotaResult<PublicCleanup> {\n const inventory = inventories.get(handle);\n if (!scopeOf(repository) || inventory?.repository !== repository)\n return failed('invalid_scope');\n try {\n if (!Array.isArray(selection)) return failed('invalid_selection');\n const length = selection.length;\n if (\n !Number.isSafeInteger(length) ||\n length <= 0 ||\n length >\n LOCAL_PERSISTENCE_BUDGETS.publicDrafts +\n LOCAL_PERSISTENCE_BUDGETS.publicOperations\n )\n return failed('invalid_selection');\n let selected = Array.from<string>([]);\n for (let index = 0; index < length; index++) {\n const key: unknown = selection[index];\n if (typeof key !== 'string' || selected.includes(key))\n return failed('invalid_selection');\n const row = inventory.rows.find(\n (row) => publicInventoryRow(row.record, row.bytes).key === key\n );\n if (!row) return failed('invalid_selection');\n if (publicInventoryRow(row.record, row.bytes).state !== 'settled')\n return failed('protected');\n selected = selected.concat(key);\n }\n if (!scopeOf(repository)) return failed('invalid_scope');\n const token = Object.freeze({}) as PublicCleanup;\n cleanups.set(token, { inventory, selected });\n return { ok: true, value: token };\n } catch {\n return failed('invalid_selection');\n }\n}\nexport function publicCleanupSnapshot(\n repository: PublicQuotaRepository,\n handle: PublicCleanup\n):\n | Readonly<{\n selected: readonly PublicInventoryRow[];\n logicalBytesRemoved: number;\n consequences: string;\n }>\n | undefined {\n const cleanup = cleanups.get(handle);\n if (!scopeOf(repository) || cleanup?.inventory.repository !== repository)\n return undefined;\n const selected = cleanup.inventory.rows\n .map((row) => publicInventoryRow(row.record, row.bytes))\n .filter((row) => cleanup.selected.includes(row.key));\n return {\n selected,\n logicalBytesRemoved: selected.reduce(\n (sum, row) => sum + row.logicalBytes,\n 0\n ),\n consequences: PUBLIC_CLEANUP_CONSEQUENCES\n };\n}\nexport function commitPublicCleanup(\n repository: PublicQuotaRepository,\n handle: PublicCleanup\n): Promise<PublicQuotaResult<readonly string[]>> {\n const cleanup = cleanups.get(handle),\n scope = scopeOf(repository);\n if (!scope || cleanup?.inventory.repository !== repository)\n return Promise.resolve(failed('invalid_scope'));\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const before = cleanup.inventory.rows;\n if (\n rows.length !== before.length ||\n rows.some(\n (row, i) =>\n row.store !== before[i].store ||\n row.record.id !== before[i].record.id ||\n row.wire !== before[i].wire\n )\n ) {\n refuse('conflict');\n return;\n }\n const selected = rows.filter((row) =>\n cleanup.selected.includes(publicInventoryRow(row.record, row.bytes).key)\n );\n if (\n selected.length !== cleanup.selected.length ||\n selected.some(\n (row) => publicInventoryRow(row.record, row.bytes).state !== 'settled'\n )\n ) {\n refuse('protected');\n return;\n }\n for (const row of selected)\n active.objectStore(row.store).delete([scope.owner, row.record.id]);\n return { ok: true, value: Array.from(cleanup.selected) };\n });\n}\n\n// No signer/network await exists inside this transaction. It consumes only a\n// genuine immutable typed transition captured before storage acquisition.\n// Exact owner-scoped actual stored preference, not a caller's structural row.\n// Read is bounded by the same complete quota/codec scan and transaction ack.\nexport function loadPreferenceOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown\n): Promise<PublicQuotaResult<PublicRecordHandle>> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n return transaction(scope, 'readonly', (rows) => {\n const row = rows.find(\n (row) => row.store === 'preference_operations' && row.record.id === id\n );\n if (!row) return failed('invalid_record');\n const decoded = decodePublicRecord(row.wire, scope.owner, id);\n return decoded.ok ? decoded : failed('corrupt_record');\n });\n}\nexport function commitPublicOperationTransition(\n repository: PublicQuotaRepository,\n handle: PublicOperationTransition\n): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {\n const scope = scopeOf(repository);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n const identity = publicTransitionIdentity(handle);\n const command =\n identity && publicTransitionSnapshot(handle, scope.owner, identity.id);\n if (!command) return Promise.resolve(failed('invalid_record'));\n const store: Store =\n command.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const previous = rows.find(\n (row) => row.store === store && row.record.id === command.id\n );\n const decision = decideFrozenTransition(\n previous?.wire,\n command.baseWire,\n command.nextWire\n );\n if (decision === 'conflict') {\n refuse('conflict');\n return;\n }\n if (decision === 'committed')\n return {\n ok: true,\n value: { id: command.id, revision: command.revision }\n };\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n const bytes =\n operations.reduce((sum, row) => sum + row.bytes, 0) -\n (previous?.bytes ?? 0) +\n new TextEncoder().encode(command.nextWire).length;\n if (bytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes) {\n refuse('capacity');\n return;\n }\n active\n .objectStore(store)\n .put({ owner: scope.owner, id: command.id, wire: command.nextWire });\n return { ok: true, value: { id: command.id, revision: command.revision } };\n });\n}\nexport async function observePublicOperationTransition(\n repository: PublicQuotaRepository,\n handle: PublicOperationTransition\n): Promise<\n | Readonly<{ state: 'committed'; id: string; revision: number }>\n | Readonly<{ state: 'base_observed' | 'conflict' | 'unavailable' }>\n> {\n const scope = scopeOf(repository),\n identity = publicTransitionIdentity(handle);\n const command =\n scope &&\n identity &&\n publicTransitionSnapshot(handle, scope.owner, identity.id);\n if (!scope || !command) return { state: 'unavailable' };\n const store: Store =\n command.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const read = await transaction(scope, 'readonly', (rows) => ({\n ok: true,\n value: decideFrozenTransition(\n rows.find((row) => row.store === store && row.record.id === command.id)\n ?.wire,\n command.baseWire,\n command.nextWire\n )\n }));\n if (!read.ok || !scopeOf(repository)) return { state: 'unavailable' };\n return read.value === 'committed'\n ? { state: 'committed', id: command.id, revision: command.revision }\n : { state: read.value };\n}\n", 84 sha256: '7bff93f40c55d5f0899deb50309d4d69107fb299d1aee10c348fda23e71761bf' 85 }, 86 'src/lib/nostr/listing-publisher.ts': { 87 source: 88 "import type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n listingPublicationOwnership,\n type ListingPublication\n} from '../publishing/sign-listing.ts';\nimport {\n listingResumeOwnership,\n type ListingResumption\n} from '../publishing/resume-listing.ts';\nimport {\n listingRetryOwnership,\n type ListingRetry\n} from '../publishing/retry-listing.ts';\nimport {\n identityMessagingOwnership,\n identityPublicOperationOwnership,\n recheckIdentityOwner,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport { preferencePolicyFingerprint } from './inbox-preference-publication.ts';\nimport { readPublicListingIntent } from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\ndeclare const leaseBrand: unique symbol;\ndeclare const permissionBrand: unique symbol;\nexport type ListingDeliveryLease = Readonly<{ [leaseBrand]: true }>;\nexport type ListingAttemptPermission = Readonly<{ [permissionBrand]: true }>;\ntype Original = NonNullable<\n | ReturnType<typeof listingPublicationOwnership>\n | ReturnType<typeof listingResumeOwnership>\n>;\ntype Owner = Readonly<{\n original: Original;\n policy: RelayPolicy;\n signal?: AbortSignal;\n current(): boolean;\n}>;\ntype Permission = Readonly<{\n owner: Owner;\n origin: string;\n mode: 'publish' | 'readback';\n wire: string;\n}>;\nconst leases = new WeakMap<ListingDeliveryLease, Owner>();\nconst permissions = new WeakMap<ListingAttemptPermission, Permission>();\n// Stop releases this action's wait and author lock. The extension promise may\n// settle later; it cannot resurrect the revoked network lease or a signer.\nasync function recheckDeliveryOwner(\n identity: IdentitySession,\n signal?: AbortSignal\n): Promise<boolean> {\n if (signal?.aborted) return false;\n if (!signal) {\n await recheckIdentityOwner(identity);\n return true;\n }\n let stop = () => {};\n const stopped = new Promise<boolean>((resolve) => {\n stop = () => resolve(false);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n });\n try {\n return await Promise.race([\n recheckIdentityOwner(identity).then(() => true),\n stopped\n ]);\n } finally {\n signal.removeEventListener('abort', stop);\n }\n}\n// Receipt revisions may grow, but the complete original operation payload and\n// verified artifact stay exact. No new command, author or destination is adopted.\nexport async function readRetainedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner) return;\n const original = owner.original;\n const expected = decodePublicRecord(\n original.recordWire,\n original.owner,\n original.command\n );\n if (!expected.ok) return;\n const baseline = publicRecordSnapshot(\n expected.value,\n original.owner,\n original.command\n );\n if (\n baseline?.family !== 'public_operation' ||\n baseline.capture.kind !== 30402 ||\n !baseline.artifact ||\n baseline.revision !== 2\n )\n return;\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n if (read.status !== 'found') return;\n const row = publicRecordSnapshot(\n read.record,\n original.owner,\n original.command\n );\n if (\n row?.family !== 'public_operation' ||\n row.revision < baseline.revision ||\n JSON.stringify({\n ...row,\n revision: baseline.revision,\n receipts: baseline.receipts\n }) !== JSON.stringify(baseline)\n )\n return;\n return read.record;\n}\n// Current authority is mandatory for every new network permission. Retained\n// exact storage observation above remains usable for bookkeeping after Stop.\nexport async function readOwnedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner?.current()) return;\n const read = readRetainedListingDelivery(lease);\n let stop = () => {};\n const stopped =\n owner.signal &&\n new Promise<undefined>((resolve) => {\n stop = () => resolve(undefined);\n owner.signal!.addEventListener('abort', stop, { once: true });\n if (owner.signal!.aborted) stop();\n });\n let record: PublicRecordHandle | undefined;\n try {\n record = await (stopped ? Promise.race([read, stopped]) : read);\n } finally {\n owner.signal?.removeEventListener('abort', stop);\n }\n return owner.current() ? record : undefined;\n}\nexport function listingDeliveryOwnership(lease: ListingDeliveryLease) {\n const owner = leases.get(lease);\n return owner?.current()\n ? {\n repository: owner.original.repository,\n owner: owner.original.owner,\n command: owner.original.command,\n current: owner.current\n }\n : undefined;\n}\nexport type ListingOwnershipResult<T> =\n | Readonly<{ status: 'completed'; value: T }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'busy' | 'stopped' }>;\n// One original author lock spans this finite explicitly requested network\n// action. It never spans a native IDB transaction and cannot mint a signer.\nexport async function withListingDeliveryOwnership<T>(\n publication: ListingPublication | ListingResumption,\n policy: RelayPolicy,\n consent: unknown,\n work: (lease: ListingDeliveryLease) => Promise<T>,\n control?: ListingRetry\n): Promise<ListingOwnershipResult<T>> {\n const signed = listingPublicationOwnership(publication as ListingPublication),\n resumed = listingResumeOwnership(publication as ListingResumption),\n original = signed ?? resumed,\n retry = control && listingRetryOwnership(control);\n if (\n !original ||\n (control\n ? !retry ||\n retry.source !== publication ||\n retry.policy !== policy ||\n retry.consent !== consent\n : !signed || consent !== 'publish_stored_listing') ||\n original.policy !== policy\n )\n return { status: 'invalid' };\n if (retry && !retry.current()) return { status: 'stopped' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n try {\n return await navigator.locks.request(\n 'harvestcircle:owner:' + original.owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<ListingOwnershipResult<T>> => {\n if (!lock) return { status: 'busy' };\n if (!(await recheckDeliveryOwner(original.identity, retry?.signal)))\n return { status: 'stopped' };\n const identity = identityMessagingOwnership(original.identity),\n operation =\n signed &&\n identityPublicOperationOwnership(\n original.identity,\n signed.operation\n );\n if (\n !identity ||\n (signed && !operation) ||\n identity.owner !== original.owner ||\n (operation &&\n (operation.owner !== original.owner ||\n operation.session !== identity.session)) ||\n !original.current() ||\n (retry && !retry.current())\n )\n return { status: 'stopped' };\n let active = true;\n const owner: Owner = {\n original,\n policy,\n signal: retry?.signal,\n current: () =>\n active &&\n original.current() &&\n identity.current() &&\n (!operation || operation.current()) &&\n (!retry || retry.current())\n };\n const lease = Object.freeze({}) as ListingDeliveryLease;\n leases.set(lease, owner);\n try {\n if (!(await readOwnedListingDelivery(lease)))\n return {\n status: retry && !retry.current() ? 'stopped' : 'unavailable'\n };\n return { status: 'completed', value: await work(lease) };\n } finally {\n active = false;\n }\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Each permission comes from actual stored signed bytes, fresh identity and\n// unchanged original policy. Preference/private capabilities cannot enter it.\nexport async function authorizeListingAttempt(\n lease: ListingDeliveryLease,\n origin: string,\n mode: 'publish' | 'readback'\n): Promise<ListingAttemptPermission | undefined> {\n const owner = leases.get(lease);\n if (!owner || !owner.current() || (mode !== 'publish' && mode !== 'readback'))\n return;\n try {\n const record = await readOwnedListingDelivery(lease),\n original = owner.original;\n const row =\n record && publicRecordSnapshot(record, original.owner, original.command);\n const manifest = readRelayPolicy(owner.policy),\n targets = publicRelayTargets(owner.policy, 'write'),\n fingerprint = await preferencePolicyFingerprint(owner.policy);\n if (\n row?.family !== 'public_operation' ||\n !row.artifact ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ||\n !row.capture.targets.includes(origin)\n )\n return;\n if (!(await recheckDeliveryOwner(original.identity, owner.signal))) return;\n if (!owner.current()) return;\n const token = Object.freeze({}) as ListingAttemptPermission;\n permissions.set(token, { owner, origin, mode, wire: row.artifact.wire });\n return token;\n } catch {\n return;\n }\n}\n// Original once-only token: detached metadata, wrong role, policy or origin\n// cannot supply a raw event. SDK effects remain owned by the public pool.\nexport function takeListingPublication(\n token: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n mode: 'publish' | 'readback'\n):\n | Readonly<{ event: NostrEvent; wire: string; current(): boolean }>\n | undefined {\n const saved = permissions.get(token);\n if (!saved) return;\n permissions.delete(token);\n if (\n saved.owner.policy !== policy ||\n saved.origin !== origin ||\n saved.mode !== mode ||\n !saved.owner.current()\n )\n return;\n return {\n event: JSON.parse(saved.wire) as NostrEvent,\n wire: saved.wire,\n current: saved.owner.current\n };\n}\n", 89 sha256: '1c8c3445513329d57fcddc75da63991f0c1c27c28caf87db381d32bba739c872' 90 } 91 }; 92 /** @type {Record<string, {source:string, sha256:string}>} */ 93 const historicalWithdrawalProducerClosure = { 94 'src/lib/publishing/sign-listing.ts': { 95 source: 96 "import {\n listingReviewOwnership,\n type ListingReview\n} from './prepare-listing.ts';\nimport {\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n preparePublicListingSigningTransition,\n preparePublicArtifactTransition,\n publicTransitionSnapshot,\n type CapturedArtifact\n} from '../persistence/artifact-records.ts';\nimport {\n commitPublicOperationTransition,\n observePublicOperationTransition\n} from '../persistence/quota.ts';\nimport {\n captureIdentityPublicOperation,\n identityPublicOperationOwnership,\n identityPublicOperationSnapshot,\n recheckIdentityOwner,\n signIdentityPublicOperation,\n stopIdentityPublicOperation,\n type IdentityPublicOperation\n} from '../runtime/identity-session.ts';\nimport { runCapturedPublicEffect } from '../runtime/effect-ownership.ts';\n\ndeclare const signingBrand: unique symbol;\ndeclare const publicationBrand: unique symbol;\nexport type ListingSigning = Readonly<{ [signingBrand]: true }>;\nexport type ListingPublication = Readonly<{ [publicationBrand]: true }>;\ntype Ownership = NonNullable<ReturnType<typeof listingReviewOwnership>>;\ntype Model = Readonly<{\n original: Ownership;\n getOperation(): IdentityPublicOperation | undefined;\n setOperation(value: IdentityPublicOperation): void;\n getAttempted(): boolean;\n setAttempted(): void;\n getStopped(): boolean;\n stop(): void;\n getSigning(): boolean;\n startSigning(): void;\n finishSigning(): void;\n subscribe(listener: () => void): () => void;\n getMarked(): PublicRecordHandle | undefined;\n setMarked(value: PublicRecordHandle): void;\n getArtifact(): CapturedArtifact | undefined;\n setArtifact(value: CapturedArtifact): void;\n getPublication(): ListingPublication | undefined;\n setPublication(value: ListingPublication): void;\n}>;\nfunction createModel(original: Ownership): Model {\n let operation: IdentityPublicOperation | undefined;\n let signing = false;\n let attempted = false,\n stopped = false;\n let marked: PublicRecordHandle | undefined;\n let artifact: CapturedArtifact | undefined;\n let publication: ListingPublication | undefined;\n const listeners = new Map<symbol, () => void>();\n let notifying = false;\n function notify() {\n if (notifying) return;\n notifying = true;\n try {\n const callbacks = Array.from(listeners.entries());\n for (const [key, listener] of callbacks) {\n if (listeners.get(key) !== listener) continue;\n try {\n listener();\n } catch {\n /* Disclosure observers never control signing. */\n }\n }\n } finally {\n notifying = false;\n }\n }\n return {\n original,\n subscribe(listener) {\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n },\n getOperation: () => operation,\n setOperation: (value) => {\n operation = value;\n },\n getAttempted: () => attempted,\n setAttempted: () => {\n attempted = true;\n },\n getStopped: () => stopped,\n stop: () => {\n if (stopped) return;\n stopped = true;\n notify();\n },\n getSigning: () => signing,\n startSigning: () => {\n if (signing) return;\n signing = true;\n notify();\n },\n finishSigning: () => {\n if (!signing) return;\n signing = false;\n notify();\n },\n getMarked: () => marked,\n setMarked: (value) => {\n marked = value;\n },\n getArtifact: () => artifact,\n setArtifact: (value) => {\n artifact = value;\n },\n getPublication: () => publication,\n setPublication: (value) => {\n publication = value;\n }\n };\n}\ntype Publication = Readonly<{\n model: Model;\n recordWire: string;\n wire: string;\n owner: string;\n command: string;\n hash: string;\n targets: readonly string[];\n policyFingerprint: string;\n}>;\nconst signings = new WeakMap<ListingSigning, Model>();\nconst commands = new WeakMap<ListingReview, ListingSigning>();\nconst pending = new WeakMap<ListingSigning, Promise<ListingSigningResult>>();\nconst publications = new WeakMap<ListingPublication, Publication>();\nexport type ListingSigningResult =\n | Readonly<{ status: 'prepared'; publication: ListingPublication }>\n | Readonly<{\n status:\n 'invalid' | 'unavailable' | 'conflict' | 'unknown' | 'busy' | 'stopped';\n }>;\n\nfunction current(model: Model): boolean {\n const operation = model.getOperation();\n return (\n !model.getStopped() &&\n (model.getSigning()\n ? model.original.readiness.signingCurrent() &&\n !!publicPublicationQuotaRepository(model.original.repository)\n : model.original.current()) &&\n (!operation ||\n !!identityPublicOperationOwnership(\n model.original.readiness.identity,\n operation\n ))\n );\n}\nexport function beginListingSigning(\n review: ListingReview,\n consent: unknown\n): ListingSigning | undefined {\n if (consent !== 'sign_reviewed_listing') return;\n const original = listingReviewOwnership(review);\n if (!original || !publicPublicationQuotaRepository(original.repository))\n return;\n const existing = commands.get(review);\n if (existing) return existing;\n const token = Object.freeze({}) as ListingSigning;\n signings.set(token, createModel(original));\n commands.set(review, token);\n return token;\n}\nexport function listingSigningSnapshot(token: ListingSigning) {\n const model = signings.get(token);\n if (!model) return;\n const original = model.original;\n const row = publicRecordSnapshot(\n original.record,\n original.readiness.owner,\n original.command\n );\n if (!row || row.family !== 'public_operation') return;\n const heldOperation = model.getOperation();\n const operation =\n heldOperation &&\n identityPublicOperationSnapshot(original.readiness.identity, heldOperation);\n return {\n owner: row.owner,\n command: row.id,\n hash: row.capture.hash,\n stopped: model.getStopped(),\n attempted: model.getAttempted(),\n signing: model.getSigning() && current(model),\n lateAvailable: operation?.lateAvailable ?? false\n };\n}\n// Original-token lifecycle observation only; no sign, retry or send authority.\nexport function subscribeListingSigning(\n token: ListingSigning,\n listener: () => void\n): () => void {\n return signings.get(token)?.subscribe(listener) ?? (() => {});\n}\n// Detached disclosure is never a send capability. HCP112 must independently\n// admit the original plan, reread storage and obtain final network ownership.\nexport function listingPublicationSnapshot(token: ListingPublication) {\n const value = publications.get(token);\n if (!value || !current(value.model)) return;\n return {\n owner: value.owner,\n command: value.command,\n hash: value.hash,\n wire: value.wire,\n targets: value.targets.slice(),\n policyFingerprint: value.policyFingerprint\n };\n}\n// Original custody only. This port grants no raw event or network effect; the\n// typed publisher must obtain its own current lock and reread durable storage.\nexport function listingPublicationOwnership(token: ListingPublication) {\n const value = publications.get(token);\n if (!value || !current(value.model)) return;\n const operation = value.model.getOperation();\n if (!operation) return;\n return {\n repository: value.model.original.repository,\n identity: value.model.original.readiness.identity,\n policy: value.model.original.readiness.policy,\n operation,\n owner: value.owner,\n command: value.command,\n recordWire: value.recordWire,\n current: () => current(value.model)\n };\n}\nasync function exactStored(\n model: Model,\n expected: PublicRecordHandle\n): Promise<boolean> {\n const original = model.original,\n owner = original.readiness.owner;\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n return (\n current(model) &&\n read.status === 'found' &&\n publicRecordWire(read.record, owner, original.command) ===\n publicRecordWire(expected, owner, original.command)\n );\n}\nasync function persist(model: Model): Promise<ListingSigningResult> {\n const original = model.original,\n owner = original.readiness.owner;\n const quota = publicPublicationQuotaRepository(original.repository);\n const marked = model.getMarked(),\n artifact = model.getArtifact();\n if (!quota || !marked || !artifact || !current(model))\n return { status: 'unavailable' };\n const transition = preparePublicArtifactTransition(\n marked,\n owner,\n original.command,\n artifact\n );\n if (!transition.ok) return { status: 'conflict' };\n const proposed = publicTransitionSnapshot(\n transition.value,\n owner,\n original.command\n );\n if (!proposed) return { status: 'invalid' };\n const decoded = decodePublicRecord(\n proposed.nextWire,\n owner,\n original.command\n );\n if (!decoded.ok) return { status: 'invalid' };\n if (!current(model)) return { status: 'stopped' };\n const saved = await commitPublicOperationTransition(quota, transition.value);\n if (!current(model)) return { status: 'unknown' };\n if (!saved.ok) {\n if (saved.reason !== 'unknown_completion')\n return {\n status: saved.reason === 'conflict' ? 'conflict' : 'unavailable'\n };\n const observed = await observePublicOperationTransition(\n quota,\n transition.value\n );\n if (observed.state !== 'committed' || !current(model))\n return { status: observed.state === 'conflict' ? 'conflict' : 'unknown' };\n }\n if (!(await exactStored(model, decoded.value))) return { status: 'unknown' };\n const row = publicRecordSnapshot(decoded.value, owner, original.command);\n if (!row || row.family !== 'public_operation' || !row.artifact)\n return { status: 'invalid' };\n const token = Object.freeze({}) as ListingPublication;\n publications.set(token, {\n model,\n recordWire: proposed.nextWire,\n wire: row.artifact.wire,\n owner,\n command: row.id,\n hash: row.artifact.eventId,\n targets: row.capture.targets.slice(),\n policyFingerprint: row.capture.policyFingerprint\n });\n model.setPublication(token);\n return { status: 'prepared', publication: token };\n}\nasync function execute(model: Model): Promise<ListingSigningResult> {\n try {\n const original = model.original,\n identity = original.readiness.identity,\n owner = original.readiness.owner;\n const quota = publicPublicationQuotaRepository(original.repository);\n if (\n !quota ||\n !current(model) ||\n typeof window === 'undefined' ||\n !navigator.locks?.request\n )\n return { status: 'unavailable' };\n const publication = model.getPublication();\n if (publication) {\n const value = publications.get(publication);\n if (!value) return { status: 'invalid' };\n const rechecked = await recheckIdentityOwner(identity);\n if (!current(model) || rechecked.state === 'guest')\n return { status: 'unavailable' };\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n if (\n !current(model) ||\n read.status !== 'found' ||\n publicRecordWire(read.record, owner, original.command) !==\n value.recordWire\n )\n return { status: 'conflict' };\n return { status: 'prepared', publication };\n }\n if (model.getArtifact()) {\n await recheckIdentityOwner(identity);\n if (!current(model)) return { status: 'unavailable' };\n // Retained exact verified artifact retry is storage-only; never a prompt.\n return await navigator.locks.request(\n 'harvestcircle:owner:' + owner,\n { mode: 'exclusive', ifAvailable: true },\n (lock) =>\n lock ? persist(model) : Promise.resolve({ status: 'busy' as const })\n );\n }\n if (model.getAttempted()) return { status: 'unknown' };\n if (!(await exactStored(model, original.record)))\n return { status: 'conflict' };\n const operation = captureIdentityPublicOperation(\n identity,\n original.record,\n original.command,\n 'reviewed_captured_operation'\n );\n if (!operation) return { status: 'unavailable' };\n model.setOperation(operation);\n const ownership = identityPublicOperationOwnership(identity, operation);\n if (!ownership || !current(model)) return { status: 'unavailable' };\n const result = await runCapturedPublicEffect(\n quota,\n original.record,\n original.command,\n { ...ownership, current: () => current(model) && ownership.current() },\n 'reviewed_prepared_listing_operation',\n async (lease): Promise<ListingSigningResult> => {\n const marker = preparePublicListingSigningTransition(\n original.record,\n owner,\n original.command\n );\n if (!marker.ok || !current(model)) return { status: 'invalid' };\n const next = publicTransitionSnapshot(\n marker.value,\n owner,\n original.command\n );\n if (!next) return { status: 'invalid' };\n model.setAttempted();\n const saved = await commitPublicOperationTransition(\n quota,\n marker.value\n );\n if (!saved.ok || !current(model))\n return {\n status:\n saved.ok || saved.reason === 'unknown_completion'\n ? 'unknown'\n : 'unavailable'\n };\n const decoded = decodePublicRecord(\n next.nextWire,\n owner,\n original.command\n );\n if (!decoded.ok || !(await exactStored(model, decoded.value)))\n return { status: 'unknown' };\n model.setMarked(decoded.value);\n model.startSigning();\n let signed;\n try {\n signed = await signIdentityPublicOperation(\n identity,\n operation,\n lease\n );\n } finally {\n model.finishSigning();\n }\n if (signed.status !== 'signed' || !current(model))\n return {\n status:\n signed.status === 'unknown' || !current(model)\n ? 'unknown'\n : 'invalid'\n };\n model.setArtifact(signed.artifact);\n return await persist(model);\n }\n );\n return result.status === 'completed'\n ? result.value\n : {\n status:\n result.status === 'busy'\n ? 'busy'\n : result.status === 'unknown' || result.status === 'retained'\n ? 'unknown'\n : 'unavailable'\n };\n } catch {\n return { status: 'unknown' };\n }\n}\nexport function runListingSigning(\n token: ListingSigning,\n consent: unknown\n): Promise<ListingSigningResult> {\n const model = signings.get(token);\n if (!model || consent !== 'sign_reviewed_listing')\n return Promise.resolve({ status: 'invalid' });\n const active = pending.get(token);\n if (active) return active;\n const work = execute(model).finally(() => {\n if (pending.get(token) === work) pending.delete(token);\n });\n pending.set(token, work);\n return work;\n}\nexport function stopListingSigning(token: ListingSigning): void {\n const model = signings.get(token);\n if (!model) return;\n model.stop();\n const operation = model.getOperation();\n if (operation)\n stopIdentityPublicOperation(model.original.readiness.identity, operation);\n}\n", 97 sha256: '5051a2e0eb3353b9f099cb92dcbd3162003a9a32cebac6035b979ae3a9400bfe' 98 }, 99 'src/lib/persistence/artifact-records.ts': { 100 source: 101 "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n exactLocalFields,\n type PublicOperationRecord,\n type PreferenceOperationRecord,\n type PublicTargetReceipt\n} from '../contracts/local-records.ts';\nimport { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';\nimport { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\n\ndeclare const artifactBrand: unique symbol;\ndeclare const transitionBrand: unique symbol;\nexport type CapturedArtifact = Readonly<{ [artifactBrand]: true }>;\nexport type PublicOperationTransition = Readonly<{ [transitionBrand]: true }>;\nexport type ArtifactFailure =\n 'invalid_artifact' | 'invalid_record' | 'conflict' | 'revision_exhausted';\ntype Result<T> =\n | Readonly<{ ok: true; value: T }>\n | Readonly<{ ok: false; reason: ArtifactFailure }>;\ntype Artifact = Readonly<{\n author: string;\n kind: 30402 | 5 | 10050 | 1059;\n hash: string;\n wire: string;\n}>;\ntype Operation = PublicOperationRecord | PreferenceOperationRecord;\ntype Transition = Readonly<{\n owner: string;\n id: string;\n family: Operation['family'];\n kind: 30402 | 5 | 10050;\n expectedRevision: number;\n revision: number;\n baseWire: string;\n nextWire: string;\n}>;\nconst artifacts = new WeakMap<CapturedArtifact, Artifact>();\nconst transitions = new WeakMap<PublicOperationTransition, Transition>();\nfunction failed(reason: ArtifactFailure): Result<never> {\n return { ok: false, reason };\n}\n// SDK-verified exact envelope binding only. A1059 token proves an outer\n// signature/hash, not nested Message authenticity, routing or durable storage.\n// Private typed repositories own those later checks. No plaintext14/13 token.\nexport function bindCapturedArtifact(\n rawWire: unknown,\n expectedAuthor: unknown,\n expectedKind: unknown,\n expectedHash: unknown\n): Result<CapturedArtifact> {\n const author = canonicalPublicKey(expectedAuthor);\n if (\n !author ||\n (expectedKind !== 30402 &&\n expectedKind !== 5 &&\n expectedKind !== 10050 &&\n expectedKind !== 1059) ||\n typeof expectedHash !== 'string' ||\n !/^[0-9a-f]{64}$/.test(expectedHash) ||\n typeof rawWire !== 'string'\n )\n return failed('invalid_artifact');\n const proof = verifyEnvelope(rawWire);\n if (!proof.ok) return failed('invalid_artifact');\n const event = verifiedEnvelopeSnapshot(proof.value);\n if (\n !event ||\n !exactLocalFields(event, [\n 'id',\n 'pubkey',\n 'kind',\n 'created_at',\n 'tags',\n 'content',\n 'sig'\n ]) ||\n event.pubkey !== author ||\n event.kind !== expectedKind ||\n event.id !== expectedHash\n )\n return failed('invalid_artifact');\n const token = Object.freeze({}) as CapturedArtifact;\n artifacts.set(token, {\n author,\n kind: expectedKind,\n hash: expectedHash,\n wire: rawWire\n });\n return { ok: true, value: token };\n}\nexport function capturedArtifactSnapshot(\n handle: CapturedArtifact\n): Artifact | undefined {\n const saved = artifacts.get(handle);\n return saved ? { ...saved } : undefined;\n}\nfunction baseOf(\n handle: PublicRecordHandle,\n owner: unknown,\n id: unknown\n): Readonly<{ row: Operation; wire: string }> | undefined {\n const row = publicRecordSnapshot(handle, owner, id),\n wire = publicRecordWire(handle, owner, id);\n return row && row.family !== 'public_draft' && wire\n ? { row, wire }\n : undefined;\n}\nfunction retain(\n base: Readonly<{ row: Operation; wire: string }>,\n next: Operation\n): Result<PublicOperationTransition> {\n const nextWire = JSON.stringify(next);\n const decoded = decodePublicRecord(nextWire, base.row.owner, base.row.id);\n if (!decoded.ok) return failed('invalid_record');\n const token = Object.freeze({}) as PublicOperationTransition;\n transitions.set(token, {\n owner: base.row.owner,\n id: base.row.id,\n family: base.row.family,\n kind: base.row.capture.kind,\n expectedRevision: base.row.revision,\n revision: next.revision,\n baseWire: base.wire,\n nextWire\n });\n return { ok: true, value: token };\n}\n// A durable one-attempt marker, not a known refusal or a retry permission.\n// Lost unsigned revision1 remains uncertain; it can never be reset by this API.\nexport function preparePreferenceSigningTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id);\n if (\n !base ||\n base.row.family !== 'preference_operation' ||\n base.row.capture.kind !== 10050 ||\n base.row.revision !== 0 ||\n base.row.artifact !== null ||\n base.row.receipts.length !== 0\n )\n return failed('invalid_record');\n return retain(base, { ...base.row, revision: 1 });\n}\n// The acknowledged unsigned revision1 records an original listing attempt.\n// It cannot be reset into permission to prompt again after page/ack loss.\nexport function preparePublicListingSigningTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id);\n if (\n !base ||\n base.row.family !== 'public_operation' ||\n base.row.source.type !== 'draft' ||\n base.row.capture.kind !== 30402 ||\n base.row.revision !== 0 ||\n base.row.artifact !== null ||\n base.row.receipts.length !== 0\n )\n return failed('invalid_record');\n return retain(base, { ...base.row, revision: 1 });\n}\nexport function preparePublicArtifactTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown,\n artifact: CapturedArtifact\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id),\n signed = artifacts.get(artifact);\n if (!base) return failed('invalid_record');\n if (\n !signed ||\n signed.author !== base.row.owner ||\n signed.kind !== base.row.capture.kind ||\n signed.hash !== base.row.capture.hash\n )\n return failed('invalid_artifact');\n if (base.row.artifact !== null)\n return base.row.artifact.wire === signed.wire\n ? retain(base, base.row)\n : failed('conflict');\n if (base.row.revision === Number.MAX_SAFE_INTEGER)\n return failed('revision_exhausted');\n return retain(base, {\n ...base.row,\n revision: base.row.revision + 1,\n artifact: { eventId: signed.hash, wire: signed.wire }\n });\n}\nfunction sameFact(a: PublicTargetReceipt, b: PublicTargetReceipt): boolean {\n return (\n a.actionId === b.actionId &&\n a.origin === b.origin &&\n a.readbackOrigin === b.readbackOrigin &&\n a.role === b.role &&\n a.attempt === b.attempt &&\n a.eventId === b.eventId &&\n a.status === b.status &&\n a.observedAtMilliseconds === b.observedAtMilliseconds\n );\n}\n// Only canonical primitive wire is acquired; defensive record decoding validates\n// every receipt field, target, role, event and exact readback signature. Distinct\n// status/time observations remain distinct. No EventStore seen metadata is used.\nexport function preparePublicReceiptTransition(\n record: PublicRecordHandle,\n owner: unknown,\n id: unknown,\n receiptWire: unknown\n): Result<PublicOperationTransition> {\n const base = baseOf(record, owner, id);\n if (\n !base ||\n !base.row.artifact ||\n typeof receiptWire !== 'string' ||\n !boundedUtf8(receiptWire, LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes)\n )\n return failed('invalid_record');\n try {\n const fact: unknown = JSON.parse(receiptWire);\n if (\n JSON.stringify(fact) !== receiptWire ||\n !(\n exactLocalFields(fact, [\n 'actionId',\n 'origin',\n 'role',\n 'attempt',\n 'eventId',\n 'status',\n 'observedAtMilliseconds',\n 'readbackWire'\n ]) ||\n (base.row.family === 'preference_operation' &&\n exactLocalFields(fact, [\n 'actionId',\n 'origin',\n 'role',\n 'attempt',\n 'eventId',\n 'status',\n 'observedAtMilliseconds',\n 'readbackWire',\n 'readbackOrigin'\n ]))\n )\n )\n return failed('invalid_record');\n // Validate the proposed fact through the existing complete typed codec before\n // comparing keys; the parsed object contains only detached JSON data.\n const checked = decodePublicRecord(\n JSON.stringify({ ...base.row, receipts: [fact] }),\n base.row.owner,\n base.row.id\n );\n if (!checked.ok) return failed('invalid_record');\n const admitted = publicRecordSnapshot(\n checked.value,\n base.row.owner,\n base.row.id\n );\n if (!admitted || admitted.family === 'public_draft')\n return failed('invalid_record');\n const nextFact = admitted.receipts[0];\n const existing = base.row.receipts.find((row) => sameFact(row, nextFact));\n if (existing)\n return JSON.stringify(existing) === JSON.stringify(nextFact)\n ? retain(base, base.row)\n : failed('conflict');\n if (base.row.revision === Number.MAX_SAFE_INTEGER)\n return failed('revision_exhausted');\n return retain(base, {\n ...base.row,\n revision: base.row.revision + 1,\n receipts: [...base.row.receipts, nextFact]\n });\n } catch {\n return failed('invalid_record');\n }\n}\n// Internal repository input: a detached snapshot of a genuine frozen command,\n// never a signing/network capability. Scope and full-wire CAS remain in IDB.\nexport function publicTransitionSnapshot(\n handle: PublicOperationTransition,\n owner: unknown,\n id: unknown\n): Transition | undefined {\n const saved = transitions.get(handle);\n return saved &&\n saved.owner === canonicalPublicKey(owner) &&\n saved.id === canonicalLocalId(id)\n ? { ...saved }\n : undefined;\n}\n// Metadata-only scope admission avoids accepting caller-owned record objects.\nexport function publicTransitionIdentity(\n handle: PublicOperationTransition\n): Readonly<{ owner: string; id: string }> | undefined {\n const saved = transitions.get(handle);\n return saved ? { owner: saved.owner, id: saved.id } : undefined;\n}\n", 102 sha256: '2ea4ccd624ec25890f009f29960a4d266d4dcae7d15e078759e7b4c70c65e9f3' 103 }, 104 'src/lib/publishing/listing-operation-view.ts': { 105 source: 106 "import { canonicalLocalId } from '../private-handles.ts';\nimport {\n publicPublicationOwner,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from '../persistence/public-publications.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport {\n identitySessionSnapshot,\n subscribeIdentityInvalidation,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n listingSigningSnapshot,\n subscribeListingSigning,\n type ListingSigning\n} from './sign-listing.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport { projectFoodParts } from '../contracts/food-availability-v1/read.ts';\nimport type { PublicTargetReceipt } from '../contracts/local-records.ts';\nimport type { StatusCopy } from '../presentation/status-copy.ts';\n\ndeclare const viewBrand: unique symbol;\nexport type ListingOperationView = Readonly<{ [viewBrand]: true }>;\nexport type ListingOperationSnapshot = Readonly<{\n owner: string;\n command: string;\n revision: number;\n eventId: string;\n artifact: 'unsigned' | 'signed';\n state:\n | 'prepared'\n | 'signing'\n | 'partial'\n | 'accepted'\n | 'readback'\n | 'unknown'\n | 'needs-action';\n acceptanceCount: number;\n readbackCount: number;\n needsAction: boolean;\n localSource: 'retained-prototype' | 'read-only';\n summary: StatusCopy;\n targets: readonly Readonly<{\n origin: string;\n eventId: string;\n accepted: boolean;\n readback: 'confirmed' | 'not-observed';\n latestOutcome: PublicTargetReceipt['status'] | 'unattempted';\n receipts: readonly PublicTargetReceipt[];\n }>[];\n}>;\ntype View = Readonly<{\n wire: string;\n current(): boolean;\n retire(): void;\n subscribe(listener: () => void): () => void;\n}>;\nconst views = new WeakMap<ListingOperationView, View>();\nconst active = new WeakMap<\n PublicPublicationRepository,\n Map<string, Readonly<{ stamp: symbol; retire(): void }>>\n>();\n\n// This is account-local presentation only. Reading a retained operation grants\n// no sign, send, edit, current-head or relay qualification capability.\nexport async function readListingOperationView(\n repository: PublicPublicationRepository,\n identity: IdentitySession,\n command: unknown,\n signing?: ListingSigning\n): Promise<\n | Readonly<{ status: 'found'; view: ListingOperationView }>\n | Readonly<{ status: 'unavailable' }>\n> {\n const owner = publicPublicationOwner(repository),\n id = canonicalLocalId(command);\n const identityOwner = () => {\n const snapshot = identitySessionSnapshot(identity);\n return 'publicKey' in snapshot ? snapshot.publicKey : undefined;\n };\n if (!owner || !id || identityOwner() !== owner)\n return { status: 'unavailable' };\n const cache =\n active.get(repository) ??\n new Map<string, Readonly<{ stamp: symbol; retire(): void }>>();\n active.set(repository, cache);\n cache.get(id)?.retire();\n const stamp = Symbol(),\n listeners = new Map<symbol, () => void>();\n let alive = true,\n unsubscribe = () => {},\n unsubscribeSigning = () => {},\n observesSigning = false;\n function retire() {\n if (!alive) return;\n alive = false;\n unsubscribe();\n unsubscribeSigning();\n if (cache.get(id!)?.stamp === stamp) cache.delete(id!);\n for (const listener of listeners.values()) {\n try {\n listener();\n } catch {\n /* Presentation callbacks cannot retain original custody. */\n }\n }\n listeners.clear();\n }\n function current() {\n const live =\n observesSigning && signing ? listingSigningSnapshot(signing) : undefined;\n const originalSigningCurrent =\n !observesSigning ||\n !!(\n live &&\n live.signing &&\n !live.stopped &&\n live.owner === owner &&\n live.command === id\n );\n return (\n originalSigningCurrent &&\n alive &&\n cache.get(id!)?.stamp === stamp &&\n publicPublicationOwner(repository) === owner &&\n identityOwner() === owner\n );\n }\n cache.set(id, { stamp, retire });\n unsubscribe = subscribeIdentityInvalidation(identity, retire);\n try {\n const read = await readPublicListingIntent(repository, id);\n const row =\n read.status === 'found' && publicRecordSnapshot(read.record, owner, id);\n if (\n !current() ||\n !row ||\n row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n row.capture.targets.length === 0 ||\n (!row.artifact && (row.revision > 1 || row.receipts.length !== 0)) ||\n (row.artifact && row.revision < 2)\n ) {\n retire();\n return { status: 'unavailable' };\n }\n const template = inspectLocalTemplate(row.capture.wire, owner, 30402);\n if (!template || projectFoodParts(template).outcome !== 'focused') {\n retire();\n return { status: 'unavailable' };\n }\n const targets = row.capture.targets.map((origin) => {\n const receipts = row.receipts.filter(\n (receipt) =>\n receipt.origin === origin && receipt.eventId === row.capture.hash\n );\n return {\n origin,\n eventId: row.capture.hash,\n accepted: receipts.some((receipt) => receipt.status === 'accepted'),\n readback: receipts.some((receipt) => receipt.readbackWire !== null)\n ? ('confirmed' as const)\n : ('not-observed' as const),\n latestOutcome: receipts.at(-1)?.status ?? ('unattempted' as const),\n receipts\n };\n });\n const acceptanceCount = targets.filter((target) => target.accepted).length,\n readbackCount = targets.filter(\n (target) => target.readback === 'confirmed'\n ).length;\n const needsAction = targets.some((target) =>\n ['refused', 'timed_out', 'unknown', 'stopped'].includes(\n target.latestOutcome\n )\n );\n const live = signing && listingSigningSnapshot(signing);\n const genuinelySigning =\n live &&\n live.owner === owner &&\n live.command === id &&\n live.hash === row.capture.hash &&\n live.signing &&\n !live.stopped;\n const state: ListingOperationSnapshot['state'] = !row.artifact\n ? row.revision === 0\n ? 'prepared'\n : genuinelySigning\n ? 'signing'\n : 'unknown'\n : readbackCount === targets.length\n ? 'readback'\n : acceptanceCount === targets.length\n ? 'accepted'\n : acceptanceCount > 0 || readbackCount > 0\n ? 'partial'\n : targets.some(\n (target) =>\n target.latestOutcome === 'refused' ||\n target.latestOutcome === 'stopped'\n )\n ? 'needs-action'\n : row.receipts.length > 0\n ? 'unknown'\n : 'prepared';\n observesSigning = state === 'signing';\n if (observesSigning && signing)\n unsubscribeSigning = subscribeListingSigning(signing, retire);\n const text =\n state === 'signing'\n ? 'Waiting for your extension to sign the retained listing.'\n : state === 'unknown'\n ? 'The outcome is unknown. Keep the original listing operation for reconciliation.'\n : state === 'needs-action'\n ? 'Needs action. Keep the original listing operation and its recorded target outcomes.'\n : state === 'partial'\n ? 'Publication evidence is partial. Check the individual target outcomes.'\n : state === 'readback'\n ? 'Exact listing read-back is recorded for each frozen target.'\n : state === 'accepted'\n ? 'Each frozen target accepted this listing event. Exact read-back is recorded separately.'\n : row.artifact\n ? 'Signed listing saved in this browser. No relay acceptance is recorded.'\n : 'Saved in this browser. The retained listing has not been signed.';\n const snapshot: ListingOperationSnapshot = {\n owner,\n command: id,\n revision: row.revision,\n eventId: row.capture.hash,\n artifact: row.artifact ? 'signed' : 'unsigned',\n state,\n acceptanceCount,\n readbackCount,\n needsAction,\n localSource:\n row.artifact && row.source.type === 'draft'\n ? 'retained-prototype'\n : 'read-only',\n summary: {\n tone:\n needsAction || state === 'unknown' || state === 'partial'\n ? 'warning'\n : 'info',\n text\n },\n targets\n };\n if (!current()) {\n retire();\n return { status: 'unavailable' };\n }\n const view = Object.freeze({}) as ListingOperationView;\n views.set(view, {\n wire: JSON.stringify(snapshot),\n current,\n retire,\n subscribe(listener) {\n if (!current()) return () => {};\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n }\n });\n return { status: 'found', view };\n } catch {\n retire();\n return { status: 'unavailable' };\n }\n}\nexport function listingOperationSnapshot(\n token: ListingOperationView\n): ListingOperationSnapshot | undefined {\n const value = views.get(token);\n if (!value) return;\n if (!value.current()) {\n value.retire();\n return;\n }\n return JSON.parse(value.wire) as ListingOperationSnapshot;\n}\nexport function closeListingOperationView(token: ListingOperationView): void {\n views.get(token)?.retire();\n}\nexport function subscribeListingOperationView(\n token: ListingOperationView,\n listener: () => void\n): () => void {\n const value = views.get(token);\n if (!value?.current()) return () => {};\n return value.subscribe(listener);\n}\n", 107 sha256: '5f48bfb7056b56bd29357e605e20ef1375c559973fcc31f38d564a3b9eb07094' 108 }, 109 'src/lib/components/OperationStatus.svelte': { 110 source: 111 "<script lang=\"ts\">\n import Notice from './Notice.svelte';\n import {\n listingOperationSnapshot,\n subscribeListingOperationView,\n type ListingOperationView\n } from '../publishing/listing-operation-view.ts';\n import {\n statusCopy,\n receiptCopy,\n type OperationFact,\n type TargetReceipt\n } from '../presentation/status-copy';\n let {\n fact = 'unknown',\n receipts = [],\n publicOperation\n }: {\n fact?: OperationFact;\n receipts?: readonly TargetReceipt[];\n publicOperation?: ListingOperationView;\n } = $props();\n let retired = $state(false);\n const publicSnapshot = $derived(\n publicOperation && !retired\n ? listingOperationSnapshot(publicOperation)\n : undefined\n );\n const summary = $derived(\n publicOperation\n ? (publicSnapshot?.summary ?? statusCopy('unknown'))\n : statusCopy(fact)\n );\n $effect(() => {\n retired = false;\n if (!publicOperation) return;\n return subscribeListingOperationView(publicOperation, () => {\n retired = true;\n });\n });\n</script>\n\n<div class=\"stack stack--tight\">\n <Notice tone={summary.tone} text={summary.text} />\n {#if publicSnapshot}\n <p>\n Relay acceptance recorded for {publicSnapshot.acceptanceCount} of {publicSnapshot\n .targets.length} targets.\n </p>\n <p>\n Exact read-back recorded for {publicSnapshot.readbackCount} of {publicSnapshot\n .targets.length} targets.\n </p>\n <p>\n {publicSnapshot.localSource === 'retained-prototype'\n ? 'Retained prototype source is available in this browser. Editing requires a separate current-head check.'\n : 'No supported retained prototype source is available for editing. Keep this listing read-only.'}\n </p>\n {#if publicSnapshot.needsAction}\n <Notice\n tone=\"warning\"\n text=\"Needs action. Earlier acceptance and exact read-back facts are preserved.\"\n />\n {/if}\n {#each publicSnapshot.targets as target (target.origin)}\n <div class=\"stack stack--tight\">\n <p class=\"key\">Event: {target.eventId} \u00b7 Target: {target.origin}</p>\n <p>\n {target.accepted\n ? 'Acceptance recorded for this event and target.'\n : 'No acceptance recorded for this event and target.'}\n </p>\n <p>\n {target.readback === 'confirmed'\n ? 'Exact read-back is confirmed for this event and target.'\n : 'Exact read-back was not observed for this event and target.'}\n </p>\n {#each target.receipts as receipt, index (index)}\n <p>\n Attempt {receipt.attempt} \u00b7 Recorded outcome: {receipt.status ===\n 'timed_out'\n ? 'timed out'\n : receipt.status}.\n </p>\n {/each}\n </div>\n {/each}\n {:else if !publicOperation}\n {#each receipts as receipt, index (index)}\n {@const copy = receiptCopy(receipt)}\n <div class=\"stack stack--tight\">\n <p class=\"key\">\n Event: {receipt.eventId} \u00b7 Target: {receipt.destination}\n </p>\n <Notice tone={copy.tone} text={copy.text} />\n <p>{copy.readback}</p>\n </div>\n {/each}\n {/if}\n</div>\n", 112 sha256: 'c6a1d741d16b577783e80b8f447cb959d5bf8b2d711cd5abcdc396be430a7472' 113 }, 114 'src/lib/runtime/effect-ownership.ts': { 115 source: 116 "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n claimPublicOperation,\n loadPreferenceOperation,\n publicQuotaOwner,\n type PublicQuotaRepository,\n type PublicQuotaFailure\n} from '../persistence/quota.ts';\n\ndeclare const leaseBrand: unique symbol;\nexport type PublicEffectLease = Readonly<{ [leaseBrand]: true }>;\nexport type PublicEffectCapture = Readonly<{\n owner: string;\n session: symbol;\n current(): boolean;\n}>;\nexport type PublicEffectResult<T> =\n | Readonly<{ status: 'completed'; value: T }>\n | Readonly<{ status: 'unknown' | 'retained'; record: PublicRecordHandle }>\n | Readonly<{\n status:\n 'invalid' | 'unavailable' | 'busy' | 'stopped' | PublicQuotaFailure;\n }>;\ntype Authority = Readonly<{\n owner: string;\n id: string;\n recordWire: string;\n session: symbol;\n}>;\ntype State = 'active' | 'unknown' | 'stopped' | 'closed';\ntype JobResult<T> =\n | Readonly<{ status: 'settled'; value: T; current: boolean }>\n | Readonly<{ status: 'invalid' | 'busy' | 'stopped' | 'unknown' }>;\ntype Controller = {\n current(authority: Authority): boolean;\n call<T>(authority: Authority, work: () => Promise<T>): Promise<JobResult<T>>;\n mark(): boolean;\n stop(): void;\n snapshot(): Readonly<{\n state: State;\n pending: boolean;\n owner: string;\n id: string;\n hash: string;\n revision: number;\n }>;\n};\nconst leases = new WeakMap<PublicEffectLease, Controller>();\n\n// Lazy browser-only origin/author ownership. It coordinates this client, never\n// independent Nostr clients. Only transaction completion acknowledges a plan.\nexport async function runCapturedPublicEffect<T>(\n repository: PublicQuotaRepository,\n handle: PublicRecordHandle,\n expectedId: unknown,\n input: PublicEffectCapture,\n review: unknown,\n work: (lease: PublicEffectLease, stored: PublicRecordHandle) => Promise<T>\n): Promise<PublicEffectResult<T>> {\n try {\n const owner = canonicalPublicKey(input?.owner),\n id = canonicalLocalId(expectedId);\n const session = input?.session,\n fresh = input?.current;\n const row =\n owner && id ? publicRecordSnapshot(handle, owner, id) : undefined;\n const recordWire =\n owner && id ? publicRecordWire(handle, owner, id) : undefined;\n if (\n (review !== 'reviewed_captured_operation' &&\n review !== 'reviewed_prepared_listing_operation' &&\n review !== 'reviewed_prepared_preference_operation' &&\n review !== 'reviewed_stored_preference_retry') ||\n !owner ||\n !id ||\n !row ||\n !recordWire ||\n row.family === 'public_draft' ||\n row.revision !== 0 ||\n row.artifact !== null ||\n typeof session !== 'symbol' ||\n typeof fresh !== 'function' ||\n typeof work !== 'function'\n )\n return { status: 'invalid' };\n const listingMode = review === 'reviewed_prepared_listing_operation';\n const preferenceMode =\n review !== 'reviewed_captured_operation' && !listingMode;\n const storedRetry = review === 'reviewed_stored_preference_retry';\n if (\n listingMode &&\n (row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n row.source.type !== 'draft')\n )\n return { status: 'invalid' };\n if (\n preferenceMode &&\n (row.family !== 'preference_operation' || row.capture.kind !== 10050)\n )\n return { status: 'invalid' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n if (publicQuotaOwner(repository) !== owner)\n return { status: 'invalid_scope' };\n return await navigator.locks.request(\n 'harvestcircle:owner:' + owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<PublicEffectResult<T>> => {\n if (!lock) return { status: 'busy' };\n if (!fresh()) return { status: 'stopped' };\n async function claimOriginal() {\n if (!storedRetry)\n return await claimPublicOperation(repository, id, handle);\n const loaded = await loadPreferenceOperation(repository, id);\n if (!loaded.ok) return loaded;\n const stored = publicRecordSnapshot(loaded.value, owner, id);\n if (\n stored?.family !== 'preference_operation' ||\n row?.family !== 'preference_operation' ||\n JSON.stringify(stored.capture) !== JSON.stringify(row.capture) ||\n JSON.stringify(stored.source) !== JSON.stringify(row.source) ||\n stored.consent !== row.consent\n )\n return { ok: false as const, reason: 'conflict' as const };\n return {\n ok: true as const,\n value: { state: 'existing' as const, record: loaded.value }\n };\n }\n const claimed = await claimOriginal();\n if (!claimed.ok)\n return claimed.reason === 'unknown_completion'\n ? { status: 'unknown', record: handle }\n : { status: claimed.reason };\n const original = claimed.value.record;\n if (storedRetry && claimed.value.state !== 'existing')\n return { status: 'unknown', record: original };\n if (claimed.value.state === 'existing') {\n const stored = publicRecordSnapshot(original, owner, id);\n const prepared =\n !storedRetry &&\n ((preferenceMode && stored?.family === 'preference_operation') ||\n (listingMode &&\n stored?.family === 'public_operation' &&\n stored.capture.kind === 30402 &&\n stored.source.type === 'draft')) &&\n stored.revision === 0 &&\n stored.artifact === null;\n const retry =\n storedRetry &&\n stored?.family === 'preference_operation' &&\n stored.revision >= 2 &&\n stored.artifact !== null;\n if (!prepared && !retry)\n return {\n status:\n stored &&\n stored.family !== 'public_draft' &&\n stored.artifact !== null\n ? 'retained'\n : 'unknown',\n record: original\n };\n }\n let phase: State = 'active',\n closed = false,\n accepting = true,\n started = false;\n let settlement: Promise<void> | null = null;\n function outstanding(): Promise<void> | null {\n return settlement;\n }\n function stop() {\n if (!closed) phase = started ? 'unknown' : 'stopped';\n }\n function current() {\n if (closed || phase !== 'active') return false;\n let valid = false;\n try {\n valid = publicQuotaOwner(repository) === owner && fresh() === true;\n } catch {\n /* finite stale result */\n }\n if (!valid) stop();\n return valid && !closed && phase === 'active';\n }\n function matches(authority: Authority) {\n return (\n authority.owner === owner &&\n authority.id === id &&\n authority.recordWire === recordWire &&\n authority.session === session\n );\n }\n const lease = Object.freeze({}) as PublicEffectLease;\n async function call<V>(\n authority: Authority,\n invoke: () => Promise<V>\n ): Promise<JobResult<V>> {\n if (\n storedRetry ||\n !matches(authority) ||\n typeof invoke !== 'function'\n )\n return { status: 'invalid' };\n if (!accepting || !current())\n return { status: phase === 'unknown' ? 'unknown' : 'stopped' };\n if (outstanding()) return { status: 'busy' };\n if (started) return { status: 'stopped' };\n // Reserve the whole SDK job before invoking even its synchronous prefix.\n // Callback return cannot release a forgotten/unsettled permission wait.\n let release = () => {};\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n settlement = held;\n try {\n const value = await invoke();\n return { status: 'settled', value, current: current() };\n } catch {\n stop();\n return { status: phase === 'unknown' ? 'unknown' : 'stopped' };\n } finally {\n settlement = null;\n release();\n }\n }\n leases.set(lease, {\n current: (authority) => matches(authority) && current(),\n call,\n stop,\n mark() {\n if (storedRetry || started || !outstanding() || !current())\n return false;\n started = true;\n return true;\n },\n snapshot: () => ({\n state: phase,\n pending: outstanding() !== null,\n owner,\n id,\n hash: row.capture.hash,\n revision: row.revision\n })\n });\n try {\n if (!current()) return { status: 'stopped' };\n let value: T;\n try {\n value = await work(lease, original);\n } catch {\n stop();\n return {\n status: 'unknown',\n record: original\n };\n }\n accepting = false;\n const waiting = outstanding();\n if (waiting) {\n // An orphaned job may settle, but cannot acquire more SDK effects\n // or expose an artifact after the operation callback has returned.\n phase = 'unknown';\n await waiting;\n }\n if (!current())\n return phase === 'unknown'\n ? { status: 'unknown', record: original }\n : { status: 'stopped' };\n return { status: 'completed', value };\n } finally {\n accepting = false;\n const waiting = outstanding();\n if (waiting) await waiting;\n closed = true;\n if (phase === 'active') phase = 'closed';\n }\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// These internal mechanical ports expose neither a signer nor a raw template.\n// The adapter supplies its actual private session and genuine approval wire.\nexport function publicEffectLeaseCurrent(\n lease: PublicEffectLease,\n authority: Authority\n): boolean {\n return leases.get(lease)?.current(authority) ?? false;\n}\nexport function callOwnedExtension<T>(\n lease: PublicEffectLease,\n authority: Authority,\n work: () => Promise<T>\n): Promise<JobResult<T>> {\n return (\n leases.get(lease)?.call(authority, work) ??\n Promise.resolve({ status: 'invalid' })\n );\n}\nexport function markOwnedSignaturePending(lease: PublicEffectLease): boolean {\n return leases.get(lease)?.mark() ?? false;\n}\nexport function stopPublicEffect(lease: PublicEffectLease): void {\n leases.get(lease)?.stop();\n}\nexport function publicEffectSnapshot(lease: PublicEffectLease) {\n return leases.get(lease)?.snapshot();\n}\n", 117 sha256: '28e09d9f8143c1bc1e66e1f2531acd64bd786a6f35ead1d10ac646b0356f7a1f' 118 }, 119 'src/lib/nostr/public-pool.ts': { 120 source: 121 "import { createScopedRelayPool } from './pool-factory.ts';\nimport { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport type { PublicFilter, PublicPoolMessage } from './exports.ts';\nimport { requireNip50Source } from './search-sources.ts';\nimport {\n takePreferencePublication,\n type PreferencePublication\n} from './inbox-preference-publication.ts';\nimport {\n takeListingPublication,\n type ListingAttemptPermission\n} from './listing-publisher.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from './verified-envelope.ts';\nexport type ListingReadbackResult =\n | Readonly<{ status: 'found'; wire: string }>\n | Readonly<{ status: 'missing' | 'unknown' | 'stopped' }>;\nexport type PreferenceAttemptResult = Readonly<{\n status: 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped';\n}>;\n\ndeclare const ownedPool: unique symbol;\nexport type PublicPool = Readonly<{ readonly [ownedPool]: true }>;\ninterface Owner {\n readonly policy: RelayPolicy;\n readonly token: PublicPool;\n readonly origins: readonly string[];\n readonly closed: () => boolean;\n readonly subscribe: (\n filters: readonly PublicFilter[],\n onMessage: (message: PublicPoolMessage) => void,\n sampleSource?: string\n ) => () => void;\n readonly close: () => void;\n readonly preference: (\n permission: PreferencePublication,\n origin: string,\n signal: AbortSignal,\n remaining: number\n ) => Promise<PreferenceAttemptResult>;\n readonly listing: (\n permission: ListingAttemptPermission,\n origin: string,\n signal: AbortSignal,\n remaining: number\n ) => Promise<PreferenceAttemptResult>;\n readonly readListing: (\n permission: ListingAttemptPermission,\n origin: string,\n signal: AbortSignal,\n remaining: number\n ) => Promise<ListingReadbackResult>;\n}\nconst owners = new WeakMap<PublicPool, Owner>();\nlet lifetime: Owner | undefined;\n\n// Anonymous state exists only after browser acquisition. No socket, information\n// fetch, identity or extension operation occurs during import or SSR.\nexport function getPublicPool(\n policy: RelayPolicy = deploymentRelayPolicy\n): PublicPool | undefined {\n if (typeof window === 'undefined') return undefined;\n readRelayPolicy(policy);\n if (lifetime) {\n if (lifetime.closed()) throw new Error('public_pool_closed');\n if (lifetime.policy !== policy)\n throw new Error('public_pool_policy_changed');\n return lifetime.token;\n }\n const token = Object.freeze({}) as PublicPool;\n const origins = publicRelayTargets(policy, 'read');\n const sdk = createScopedRelayPool();\n const active = new Map<() => void, true>();\n let closed = false;\n let cleanupComplete = false;\n let publicationCleanupRequired = false;\n const owner: Owner = {\n policy,\n token,\n origins,\n closed: () => closed,\n async preference(permission, origin, signal, remaining) {\n const admitted = takePreferencePublication(permission, policy, origin);\n if (\n closed ||\n publicationCleanupRequired ||\n !admitted ||\n signal.aborted ||\n !Number.isFinite(remaining) ||\n remaining <= 0 ||\n remaining > 45000\n )\n return { status: 'stopped' };\n return await new Promise<PreferenceAttemptResult>((resolve) => {\n let ended = false;\n let release = () => {};\n let fenceTimer: ReturnType<typeof setTimeout> | undefined;\n function finish(status: PreferenceAttemptResult['status']) {\n if (ended) return;\n ended = true;\n clearTimeout(timer);\n if (fenceTimer !== undefined) clearTimeout(fenceTimer);\n signal.removeEventListener('abort', stopped);\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n status = 'unknown';\n }\n resolve({ status });\n }\n function stopped() {\n if (ended) {\n release();\n return;\n }\n finish('stopped');\n }\n function fence() {\n if (ended) return;\n if (closed || signal.aborted || !admitted!.current()) {\n finish('stopped');\n return;\n }\n fenceTimer = setTimeout(() => fence(), 50);\n }\n signal.addEventListener('abort', stopped, { once: true });\n // Arm our finite deadline before subscribing. The SDK uses the same\n // response shape for its timer and a relay refusal saying \"Timeout\";\n // only this owned deadline supplies retryable timeout evidence.\n const relay = sdk.relay(origin);\n const timeout =\n Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0\n ? Math.min(remaining, relay.eventTimeout)\n : remaining;\n const timer = setTimeout(() => finish('timed_out'), timeout);\n try {\n if (!admitted.current() || signal.aborted) {\n finish('stopped');\n return;\n }\n // This SDK invocation is an attempted effect. Stop cannot reverse an\n // already emitted/buffered EVENT, but teardown schedules no new one.\n const subscription = relay.event(admitted.event, 'EVENT').subscribe({\n next(response) {\n if (ended) return;\n if (\n (response.from !== origin && response.from !== origin + '/') ||\n typeof response.ok !== 'boolean'\n ) {\n finish('unknown');\n return;\n }\n if (response.ok) finish('accepted');\n else if (response.message === 'Timeout') finish('unknown');\n else if (\n typeof response.message === 'string' &&\n response.message.startsWith('auth-required:')\n )\n finish('unknown');\n else finish('refused');\n },\n error: () => finish('unknown'),\n complete: () => {\n if (!ended) finish('unknown');\n }\n });\n const stop = () => {\n subscription.unsubscribe();\n active.delete(stop);\n };\n release = () => {\n stop();\n active.delete(stopped);\n };\n active.set(stopped, true);\n if (ended) {\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n }\n } else {\n fence();\n }\n } catch {\n finish('unknown');\n }\n });\n },\n async listing(permission, origin, signal, remaining) {\n const admitted = takeListingPublication(\n permission,\n policy,\n origin,\n 'publish'\n );\n if (\n closed ||\n publicationCleanupRequired ||\n !admitted ||\n signal.aborted ||\n !Number.isFinite(remaining) ||\n remaining <= 0 ||\n remaining > 45000\n )\n return { status: 'stopped' };\n return await new Promise<PreferenceAttemptResult>((resolve) => {\n let ended = false;\n let release = () => {};\n let fenceTimer: ReturnType<typeof setTimeout> | undefined;\n function finish(status: PreferenceAttemptResult['status']) {\n if (ended) return;\n ended = true;\n clearTimeout(timer);\n if (fenceTimer !== undefined) clearTimeout(fenceTimer);\n signal.removeEventListener('abort', stopped);\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n status = 'unknown';\n }\n resolve({ status });\n }\n function stopped() {\n if (ended) {\n release();\n return;\n }\n finish('stopped');\n }\n function fence() {\n if (ended) return;\n if (closed || signal.aborted || !admitted!.current()) {\n finish('stopped');\n return;\n }\n fenceTimer = setTimeout(() => fence(), 50);\n }\n signal.addEventListener('abort', stopped, { once: true });\n // Arm our finite deadline before subscribing. The SDK uses the same\n // response shape for its timer and a relay refusal saying \"Timeout\";\n // only this owned deadline supplies retryable timeout evidence.\n const relay = sdk.relay(origin);\n const timeout =\n Number.isFinite(relay.eventTimeout) && relay.eventTimeout > 0\n ? Math.min(remaining, relay.eventTimeout)\n : remaining;\n const timer = setTimeout(() => finish('timed_out'), timeout);\n try {\n if (!admitted.current() || signal.aborted) {\n finish('stopped');\n return;\n }\n // This SDK invocation is an attempted effect. Stop cannot reverse an\n // already emitted/buffered EVENT, but teardown schedules no new one.\n const subscription = relay.event(admitted.event, 'EVENT').subscribe({\n next(response) {\n if (ended) return;\n if (\n (response.from !== origin && response.from !== origin + '/') ||\n typeof response.ok !== 'boolean'\n ) {\n finish('unknown');\n return;\n }\n if (response.ok) finish('accepted');\n else if (response.message === 'Timeout') finish('unknown');\n else if (\n typeof response.message === 'string' &&\n response.message.startsWith('auth-required:')\n )\n finish('unknown');\n else finish('refused');\n },\n error: () => finish('unknown'),\n complete: () => {\n if (!ended) finish('unknown');\n }\n });\n const stop = () => {\n subscription.unsubscribe();\n active.delete(stop);\n };\n release = () => {\n stop();\n active.delete(stopped);\n };\n active.set(stopped, true);\n if (ended) {\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n }\n } else {\n fence();\n }\n } catch {\n finish('unknown');\n }\n });\n },\n async readListing(permission, origin, signal, remaining) {\n const admitted = takeListingPublication(\n permission,\n policy,\n origin,\n 'readback'\n );\n if (\n closed ||\n publicationCleanupRequired ||\n !admitted ||\n signal.aborted ||\n !Number.isFinite(remaining) ||\n remaining <= 0 ||\n remaining > 45000\n )\n return { status: 'stopped' };\n return await new Promise<ListingReadbackResult>((resolve) => {\n let ended = false,\n release = () => {};\n let fenceTimer: ReturnType<typeof setTimeout> | undefined;\n function finish(result: ListingReadbackResult) {\n if (ended) return;\n ended = true;\n clearTimeout(timer);\n if (fenceTimer !== undefined) clearTimeout(fenceTimer);\n signal.removeEventListener('abort', stopped);\n try {\n release();\n } catch {\n publicationCleanupRequired = true;\n result = { status: 'unknown' };\n }\n resolve(result);\n }\n function stopped() {\n finish({ status: 'stopped' });\n }\n function fence() {\n if (ended) return;\n if (closed || signal.aborted || !admitted!.current()) {\n stopped();\n return;\n }\n fenceTimer = setTimeout(fence, 50);\n }\n const timer = setTimeout(\n () => finish({ status: 'unknown' }),\n remaining\n );\n signal.addEventListener('abort', stopped, { once: true });\n try {\n if (!admitted.current() || signal.aborted) {\n stopped();\n return;\n }\n const expected = admitted.event;\n // Exact frozen target and ID only. No generic filter/relay/request API.\n const subscription = sdk\n .req(\n [origin],\n [\n {\n ids: [expected.id],\n authors: [expected.pubkey],\n kinds: [30402],\n limit: 1\n }\n ],\n { waitForAuth: false, reconnect: false, resubscribe: false }\n )\n .subscribe({\n next(message) {\n if (\n ended ||\n (message.from !== origin && message.from !== origin + '/')\n )\n return;\n if (message.type === 'EOSE') {\n finish({ status: 'missing' });\n return;\n }\n if (message.type !== 'EVENT' || !admitted.current()) return;\n const checked = verifyEnvelope(JSON.stringify(message.event));\n const observed =\n checked.ok && verifiedEnvelopeSnapshot(checked.value);\n const fields = (event: typeof expected) =>\n JSON.stringify([\n event.id,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n event.sig\n ]);\n if (observed && fields(observed) === fields(expected))\n // SDK object ingress is independently verified signed fields,\n // not a claim to preserve the relay's original JSON encoding.\n finish({ status: 'found', wire: admitted.wire });\n },\n error: () => finish({ status: 'unknown' }),\n complete: () => {\n if (!ended) finish({ status: 'missing' });\n }\n });\n release = () => {\n subscription.unsubscribe();\n active.delete(stopped);\n };\n active.set(stopped, true);\n if (ended) release();\n else fence();\n } catch {\n finish({ status: 'unknown' });\n }\n });\n },\n subscribe(filters, onMessage, sampleSource) {\n if (closed) throw new Error('public_pool_closed');\n let release = () => {};\n const subscription = sdk\n .req(\n sampleSource === undefined\n ? [...origins]\n : [requireNip50Source(policy, sampleSource)],\n [...filters],\n {\n waitForAuth: false,\n reconnect: false,\n resubscribe: false\n }\n )\n .subscribe({\n next: (message) => {\n if (!closed) onMessage(message);\n },\n complete: () => release(),\n error: () => release()\n });\n const stop = () => {\n try {\n subscription.unsubscribe();\n } finally {\n active.delete(stop);\n }\n };\n release = stop;\n if (closed) stop();\n else if (!subscription.closed) active.set(stop, true);\n return stop;\n },\n close() {\n if (cleanupComplete) return;\n closed = true;\n let failed = false;\n for (const stop of active.keys()) {\n try {\n stop();\n } catch {\n failed = true;\n }\n }\n try {\n sdk.close();\n } catch {\n failed = true;\n }\n cleanupComplete = !failed && active.size === 0;\n if (!cleanupComplete) throw new Error('public_pool_close_failed');\n }\n };\n owners.set(token, owner);\n lifetime = owner;\n return token;\n}\n\nfunction ownerOf(token: PublicPool): Owner {\n const owner = owners.get(token);\n if (!owner) throw new Error('public_pool_invalid');\n return owner;\n}\nexport function publicPoolOrigins(token: PublicPool): readonly string[] {\n return [...ownerOf(token).origins];\n}\n\n// Filter construction and event verification/work budgets have separate owners.\n// Accept no SDK filter callback (which would expose a raw relay), arbitrary\n// destination, AUTH method, information fetch or retry option through this API.\nexport function subscribePublicPool(\n token: PublicPool,\n filters: readonly PublicFilter[],\n onMessage: (message: PublicPoolMessage) => void,\n sampleSource?: string\n): () => void {\n const owner = ownerOf(token);\n if (owner.closed()) throw new Error('public_pool_closed');\n if (\n !Array.isArray(filters) ||\n filters.length === 0 ||\n filters.some(\n (filter) => !filter || typeof filter !== 'object' || Array.isArray(filter)\n )\n )\n throw new Error('public_pool_filters_invalid');\n if (sampleSource !== undefined)\n requireNip50Source(owner.policy, sampleSource);\n if (\n sampleSource === undefined &&\n filters.some((filter) => 'search' in filter)\n )\n throw new Error('public_pool_search_requires_source');\n return owner.subscribe(filters, onMessage, sampleSource);\n}\n\n// Terminal browser-lifetime shutdown: cancel request controls before closing the\n// SDK sockets and its keepalive/reconnect watchers. Routes cannot recreate it.\nexport function closePublicPool(token: PublicPool): void {\n ownerOf(token).close();\n}\n// Narrow once-only preference capability; no raw event, arbitrary SDK options,\n// AUTH or general UI publisher. Pool remains the anonymous lifetime owner.\nexport function publishPublicPreferenceAttempt(\n token: PublicPool,\n permission: PreferencePublication,\n policy: RelayPolicy,\n origin: string,\n signal: AbortSignal,\n remaining: number\n): Promise<PreferenceAttemptResult> {\n try {\n const owner = ownerOf(token);\n if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });\n return owner.preference(permission, origin, signal, remaining);\n } catch {\n return Promise.resolve({ status: 'unknown' });\n }\n}\n// Listing and preference permissions stay separate despite the shared SDK owner.\nexport function publishPublicListingAttempt(\n token: PublicPool,\n permission: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n signal: AbortSignal,\n remaining: number\n): Promise<PreferenceAttemptResult> {\n try {\n const owner = ownerOf(token);\n if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });\n return owner.listing(permission, origin, signal, remaining);\n } catch {\n return Promise.resolve({ status: 'unknown' });\n }\n}\nexport function readPublicListingExactAttempt(\n token: PublicPool,\n permission: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n signal: AbortSignal,\n remaining: number\n): Promise<ListingReadbackResult> {\n try {\n const owner = ownerOf(token);\n if (owner.policy !== policy) return Promise.resolve({ status: 'stopped' });\n return owner.readListing(permission, origin, signal, remaining);\n } catch {\n return Promise.resolve({ status: 'unknown' });\n }\n}\n", 122 sha256: 'd08c2c16936125e75a8195cfdc600f8c592cb942e1802d934823ee221c1c132b' 123 }, 124 'src/lib/persistence/public-receipts.ts': { 125 source: 126 "import {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n preparePublicReceiptTransition,\n publicTransitionSnapshot\n} from './artifact-records.ts';\nimport {\n publicPublicationOwner,\n publicPublicationQuotaRepository,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from './public-publications.ts';\nimport {\n commitPublicOperationTransition,\n observePublicOperationTransition\n} from './quota.ts';\nexport type PublicListingReceiptResult =\n | Readonly<{ status: 'saved'; record: PublicRecordHandle }>\n | Readonly<{ status: 'invalid' | 'conflict' | 'unknown' | 'unavailable' }>;\n// Exact full-wire CAS append. A request success or detached cached observation\n// cannot acknowledge a receipt. Unknown native commits retain original payload.\nexport async function commitPublicListingReceipt(\n repository: PublicPublicationRepository,\n record: PublicRecordHandle,\n command: string,\n receiptWire: string\n): Promise<PublicListingReceiptResult> {\n try {\n const owner = publicPublicationOwner(repository),\n quota = publicPublicationQuotaRepository(repository);\n const row = owner\n ? publicRecordSnapshot(record, owner, command)\n : undefined;\n if (\n !owner ||\n !quota ||\n row?.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n !row.artifact\n )\n return { status: 'invalid' };\n const transition = preparePublicReceiptTransition(\n record,\n owner,\n command,\n receiptWire\n );\n if (!transition.ok) return { status: 'invalid' };\n const expected = publicTransitionSnapshot(transition.value, owner, command);\n if (!expected) return { status: 'invalid' };\n const saved = await commitPublicOperationTransition(\n quota,\n transition.value\n );\n if (!saved.ok) {\n if (saved.reason !== 'unknown_completion')\n return {\n status: saved.reason === 'conflict' ? 'conflict' : 'unavailable'\n };\n const observed = await observePublicOperationTransition(\n quota,\n transition.value\n );\n if (observed.state !== 'committed')\n return {\n status: observed.state === 'conflict' ? 'conflict' : 'unknown'\n };\n }\n const read = await readPublicListingIntent(repository, command);\n if (read.status !== 'found') return { status: 'unknown' };\n if (publicRecordWire(read.record, owner, command) !== expected.nextWire)\n return { status: 'conflict' };\n return { status: 'saved', record: read.record };\n } catch {\n return { status: 'unknown' };\n }\n}\n", 127 sha256: '0b88e68b963e2052f29df9013378af56e8a0013415e52619dfbf36f7daa593c7' 128 } 129 }; 130 /** @param {string} web */ 131 async function restoreHistoricalPublicProducers(web) { 132 for (const [name, value] of Object.entries({ 133 ...{ 134 'src/lib/components/AppShell.svelte': { 135 source: 136 "<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import { internalHref } from '../navigation-url';\n import Button from './primitives/Button.svelte';\n import CapabilityGate from './CapabilityGate.svelte';\n import type { IdentityViewActionResult } from '../runtime/view-context.ts';\n import type { IdentitySnapshot } from '../runtime/identity-session.ts';\n import Disclosure from './primitives/Disclosure.svelte';\n\n type ShellRoute =\n '/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy';\n type Identity =\n | {\n kind: 'guest';\n onconnect?: () => Promise<IdentityViewActionResult> | void;\n }\n | { kind: 'connected'; publicKey: string; ondisconnect?: () => void };\n let {\n children,\n currentPath = '/',\n availableRoutes = [],\n identity = { kind: 'guest' },\n capability,\n ondisconnect\n }: {\n children: Snippet;\n currentPath?: string;\n availableRoutes?: readonly ShellRoute[];\n identity?: Identity;\n capability?: IdentitySnapshot;\n ondisconnect?: () => void;\n } = $props();\n\n const observed = $derived(\n capability ??\n (identity.kind === 'guest'\n ? { state: 'guest' as const, reason: 'disconnected' as const }\n : {\n state: 'connected' as const,\n publicKey: identity.publicKey,\n messaging: 'not_probed' as const\n })\n );\n const unavailable = $derived(\n !availableRoutes.includes('/search') ||\n !availableRoutes.includes('/about') ||\n !availableRoutes.includes('/privacy') ||\n (identity.kind === 'guest'\n ? !availableRoutes.includes('/sell') || !identity.onconnect\n : !availableRoutes.includes('/selling') ||\n !availableRoutes.includes('/messages') ||\n !identity.ondisconnect)\n );\n\n function available(href: string) {\n return (\n href === '/' ||\n availableRoutes.some((route) => route === href.split('#')[0])\n );\n }\n</script>\n\n{#snippet navigation(label: string, href: string, brand = false)}\n {#if available(href) && internalHref(href)}\n <a\n href={internalHref(href)}\n class=\"shell-link\"\n class:brand\n aria-current={currentPath === href ? 'page' : undefined}>{label}</a\n >\n {:else}\n <span\n class=\"shell-link text-muted\"\n aria-disabled=\"true\"\n aria-describedby=\"shell-availability\"\n aria-current={currentPath === href ? 'page' : undefined}>{label}</span\n >\n {/if}\n{/snippet}\n\n<a href={internalHref('#main-content')} class=\"skip-link visually-hidden\"\n >Skip to main content</a\n>\n<header class=\"navbar\">\n <nav aria-label=\"Primary\" class=\"page navbar__inner\">\n <div class=\"cluster\">\n {@render navigation('HarvestCircle', '/', true)}\n {@render navigation('Search', '/search')}\n {#if identity.kind === 'guest'}\n {@render navigation('List food', '/sell')}\n {@render navigation('Messages', '/messages')}\n {:else}\n {@render navigation('Messages', '/messages')}\n {@render navigation('Selling', '/selling')}\n <Disclosure summary=\"Identity\">\n <p class=\"key\">{identity.publicKey}</p>\n <Button\n label=\"Disconnect\"\n disabled={!identity.ondisconnect}\n onclick={identity.ondisconnect}\n />\n </Disclosure>\n {/if}\n <CapabilityGate\n focusTarget=\"navbar\"\n {ondisconnect}\n identity={observed}\n compact\n focusScope={currentPath}\n onconnect={identity.kind === 'guest' ? identity.onconnect : undefined}\n />\n </div>\n {#if unavailable}\n <p id=\"shell-availability\" class=\"text-small text-muted\">\n Unavailable during development: disabled navigation and actions.\n </p>\n {/if}\n </nav>\n</header>\n<main id=\"main-content\" tabindex=\"-1\" class=\"page\">\n {@render children()}\n</main>\n<footer class=\"footer\">\n <nav aria-label=\"Footer\" class=\"page cluster\">\n {@render navigation('About', '/about')}\n {@render navigation('Privacy', '/privacy')}\n {@render navigation('Help / report', '/about#help')}\n </nav>\n</footer>\n", 137 sha256: 138 'a13f0c08f61cfe8ef0635263503c7d87c0946ae8b0300eeccf66602fb44de83e' 139 }, 140 'src/lib/components/ListingEditor.svelte': { 141 source: 142 "<script lang=\"ts\">\n /* global document, setInterval, clearInterval */\n import { getContext, onMount, tick } from 'svelte';\n import ListingReview from './ListingReview.svelte';\n import ConflictNotice from './ConflictNotice.svelte';\n import ConfirmPanel from './ConfirmPanel.svelte';\n import InboxSetup from './InboxSetup.svelte';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n type PublicRuntimeContext,\n type PublicRuntime\n } from '../runtime/public-runtime.ts';\n import {\n createRuntimeInboxSetupView,\n inboxSetupViewSnapshot,\n subscribeInboxSetupView,\n closeInboxSetupView,\n type InboxSetupView\n } from '../messaging/inbox-setup-view.ts';\n import {\n openEditorReview,\n editorReviewSnapshot,\n closeEditorReview,\n publishEditorRevision,\n stopEditorAction,\n editorPublicationOperation,\n type EditorReview,\n type EditorFormError\n } from '../publishing/editor-workflow.ts';\n import type { ListingOperationView } from '../publishing/listing-operation-view.ts';\n import CapabilityGate from './CapabilityGate.svelte';\n import Notice from './Notice.svelte';\n import OperationStatus from './OperationStatus.svelte';\n import { foodUnits } from '../contracts/food-availability-v1/values.ts';\n import type { PublicDraftForm } from '../contracts/local-records.ts';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n type IdentityViewContext\n } from '../runtime/view-context.ts';\n import {\n openListingEditor,\n listingEditorSnapshot,\n editListingEditor,\n saveAndCloseListingEditor,\n closeListingEditor,\n subscribeListingEditor,\n listingEditorEditSource,\n observeListingEditor,\n type ListingEditor as Editor,\n type ListingEditorRoute,\n type ListingEditorSnapshot\n } from '../publishing/listing-editor.ts';\n import { internalHref } from '../navigation-url.ts';\n let {\n route,\n onfirstsave,\n onsavedclose,\n inboxController\n }: {\n route: ListingEditorRoute;\n onfirstsave?: (draftId: string, current: () => boolean) => Promise<void>;\n onsavedclose?: () => Promise<void>;\n inboxController?: InboxSetupView;\n } = $props();\n const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);\n const publicContext = getContext<PublicRuntimeContext>(\n PUBLIC_RUNTIME_CONTEXT\n );\n let runtime = $state.raw<PublicRuntime | undefined>(),\n setup = $state.raw<InboxSetupView | undefined>();\n let setupState = $state(inboxSetupViewSnapshot(undefined));\n let review = $state.raw<EditorReview | undefined>(),\n reviewBusy = $state(false);\n let soldConfirm = $state(false),\n withdrawalConfirm = $state(false),\n publishBusy = $state(false);\n let publicationOperation = $state.raw<ListingOperationView | undefined>();\n let errors = $state<readonly EditorFormError[]>([]),\n reviewMessage = $state('');\n let identity = $state(identityViewSnapshot(context)),\n mounted = $state(false),\n editor = $state.raw<Editor | undefined>(),\n snapshot = $state<ListingEditorSnapshot>(),\n unavailable = $state(false);\n let closeBusy = $state(false),\n navigationFailed = $state(false);\n let firstNavigation: Promise<void> | undefined;\n let firstOwner: Editor | undefined;\n type Form = {\n -readonly [Key in keyof PublicDraftForm]: PublicDraftForm[Key];\n };\n const blankForm = (): Form => ({\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n });\n let form = $state<Form>(blankForm());\n const admittedAuthor = $derived(\n identity.identity.state !== 'guest' && identity.identity.state !== 'pending'\n ? identity.identity.publicKey\n : undefined\n );\n const active = $derived(mounted && identity.mounted);\n const visible = $derived(\n snapshot &&\n editor &&\n identity.mounted &&\n identity.identity.state !== 'guest' &&\n identity.identity.state !== 'pending' &&\n identity.identity.publicKey === snapshot.owner &&\n listingEditorSnapshot(editor)\n );\n const editable = $derived(\n !!(visible && visible.editable && !publicationOperation && !publishBusy)\n );\n onMount(() => {\n mounted = true;\n const off = subscribeIdentityView(context, (next) => {\n identity = next;\n });\n if (publicContext)\n void publicRuntimeReady(publicContext)\n .then((value) => {\n if (mounted) runtime = value;\n })\n .catch(() => {\n /* Draft saving does not depend on inbox setup. */\n });\n return () => {\n mounted = false;\n off();\n };\n });\n $effect(() => {\n const author = admittedAuthor,\n available = active,\n source = runtime,\n supplied = inboxController;\n if (!available || !author) {\n setup = undefined;\n setupState = inboxSetupViewSnapshot(undefined);\n return;\n }\n const owned =\n supplied ?? (source && createRuntimeInboxSetupView(context, source));\n setup = owned;\n const off = owned\n ? subscribeInboxSetupView(owned, (next) => {\n setupState = next;\n })\n : () => {};\n return () => {\n off();\n if (owned) closeInboxSetupView(owned);\n };\n });\n const visibleReview = $derived.by(() => {\n if (\n (!setupState.owner && route.mode !== 'edit') ||\n !snapshot ||\n !visible ||\n !review\n )\n return;\n return editorReviewSnapshot(review) ? review : undefined;\n });\n $effect(() => {\n const resource = route,\n author = admittedAuthor,\n editRuntime = route.mode === 'edit' ? runtime : undefined;\n if (!active || !author) {\n editor = undefined;\n snapshot = undefined;\n form = blankForm();\n unavailable = false;\n return;\n }\n const cancellation = new AbortController();\n let alive = true,\n owned: Editor | undefined,\n off = () => {};\n const observer =\n resource.mode === 'edit'\n ? setInterval(() => {\n if (owned) observeListingEditor(owned);\n }, 250)\n : undefined;\n editor = undefined;\n snapshot = undefined;\n review = undefined;\n publicationOperation = undefined;\n soldConfirm = false;\n withdrawalConfirm = false;\n errors = [];\n reviewMessage = '';\n form = blankForm();\n unavailable = false;\n void openListingEditor(\n context,\n resource,\n cancellation.signal,\n editRuntime\n ).then((result) => {\n if (!alive) {\n if (result.status === 'ready') closeListingEditor(result.editor);\n return;\n }\n if (result.status !== 'ready') {\n unavailable = true;\n return;\n }\n owned = result.editor;\n editor = owned;\n const next = listingEditorSnapshot(owned);\n if (!next) {\n unavailable = true;\n return;\n }\n snapshot = next;\n form = { ...next.form };\n off = subscribeListingEditor(owned, () => {\n snapshot = owned && listingEditorSnapshot(owned);\n if (\n snapshot?.state === 'saved' &&\n snapshot.draftId &&\n resource.mode === 'new' &&\n owned &&\n firstOwner !== owned &&\n !closeBusy &&\n onfirstsave\n ) {\n firstOwner = owned;\n firstNavigation = onfirstsave(\n snapshot.draftId,\n () =>\n alive &&\n mounted &&\n editor === owned &&\n !!owned &&\n !!listingEditorSnapshot(owned)\n ).catch(() => {\n if (alive) navigationFailed = true;\n });\n }\n if (!snapshot) {\n unavailable = true;\n form = blankForm();\n }\n });\n });\n return () => {\n alive = false;\n if (observer !== undefined) clearInterval(observer);\n cancellation.abort();\n off();\n if (owned) closeListingEditor(owned);\n if (editor === owned && review) closeEditorReview(review);\n form = blankForm();\n };\n });\n function changed() {\n const original = editor;\n if (!original || !listingEditorSnapshot(original)?.editable) return;\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n soldConfirm = false;\n withdrawalConfirm = false;\n void editListingEditor(original, { ...form });\n }\n async function showReview(\n status: 'active' | 'sold' | 'withdrawal' = 'active'\n ) {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (\n reviewBusy ||\n closeBusy ||\n publishBusy ||\n publicationOperation ||\n !original ||\n !listingEditorSnapshot(original)?.editable\n )\n return;\n reviewBusy = true;\n try {\n const result = await openEditorReview(\n original,\n setup,\n { ...form },\n status\n );\n if (\n !mounted ||\n editor !== original ||\n route !== resource ||\n admittedAuthor !== author ||\n !listingEditorSnapshot(original)\n ) {\n if (result.status === 'review') closeEditorReview(result.review);\n return;\n }\n if (result.status === 'blocked') {\n errors = result.errors;\n reviewMessage = result.message;\n await tick();\n document.querySelector<HTMLElement>('#listing-review-errors')?.focus();\n return;\n }\n if (review) closeEditorReview(review);\n review = result.review;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor === original && editorReviewSnapshot(result.review))\n document.querySelector<HTMLElement>('#listing-review-heading')?.focus();\n } finally {\n reviewBusy = false;\n }\n }\n async function editDetails() {\n if (review) closeEditorReview(review);\n review = undefined;\n errors = [];\n reviewMessage = '';\n await tick();\n if (mounted && editor && listingEditorSnapshot(editor)?.editable)\n document.querySelector<HTMLInputElement>('#listing-title')?.focus();\n }\n async function publishChanges() {\n const original = review,\n resource = route,\n author = admittedAuthor;\n if (\n !original ||\n publishBusy ||\n publicationOperation ||\n route.mode !== 'edit'\n )\n return;\n publishBusy = true;\n try {\n const result = await publishEditorRevision(\n original,\n editorReviewSnapshot(original)?.withdrawal\n ? 'publish_reviewed_withdrawal'\n : 'publish_reviewed_revision'\n );\n if (\n !mounted ||\n review !== original ||\n route !== resource ||\n admittedAuthor !== author\n )\n return;\n publicationOperation = editorPublicationOperation(original);\n if (result.status !== 'completed')\n reviewMessage =\n 'The update did not complete. Your proposed draft remains here. Check any retained operation before another attempt.';\n } finally {\n publishBusy = false;\n }\n }\n function fieldError(field: keyof PublicDraftForm) {\n return errors.find((value) => value.field === field);\n }\n function fieldId(field: keyof PublicDraftForm) {\n return (\n 'listing-' +\n (field === 'contactType'\n ? 'contact-type'\n : field === 'contactValue'\n ? 'contact-value'\n : field)\n );\n }\n function connect() {\n return connectIdentityView(context);\n }\n async function saveClose() {\n const original = editor,\n resource = route,\n author = admittedAuthor;\n if (\n closeBusy ||\n publishBusy ||\n publicationOperation ||\n !original ||\n !listingEditorSnapshot(original)?.editable\n )\n return;\n closeBusy = true;\n try {\n const saved = await saveAndCloseListingEditor(original);\n await firstNavigation;\n if (\n !saved ||\n !mounted ||\n editor !== original ||\n route !== resource ||\n !author ||\n admittedAuthor !== author\n )\n return;\n await onsavedclose?.();\n } catch {\n if (mounted) navigationFailed = true;\n } finally {\n closeBusy = false;\n }\n }\n function disconnect() {\n disconnectIdentityView(context);\n }\n const title = $derived(\n route.mode === 'new'\n ? 'New listing'\n : route.mode === 'draft'\n ? 'Continue draft'\n : 'Edit listing'\n );\n</script>\n\n<svelte:head\n ><title>{title} \u00b7 HarvestCircle</title><meta\n name=\"robots\"\n content=\"noindex\"\n /></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a\n href={internalHref(\n route.mode === 'edit' ? `/products/${route.naddr}` : '/selling'\n )}>{route.mode === 'edit' ? 'Back to listing' : 'Back to Selling'}</a\n >\n <h1>{title}</h1>\n {#if !visible}\n <CapabilityGate\n identity={identity.identity}\n required=\"connection\"\n focusTarget=\"protected\"\n onconnect={mounted ? connect : undefined}\n ondisconnect={disconnect}\n />\n {#if unavailable}<Notice\n tone=\"warning\"\n text={route.mode === 'draft'\n ? 'This draft is not available here.'\n : route.mode === 'edit'\n ? 'Supported local listing values are not available for editing. Keep this listing read-only.'\n : 'Browser storage is unavailable. Your existing local data has not been reset.'}\n />{:else if identity.identity.state !== 'guest' && identity.identity.state !== 'pending'}<p\n role=\"status\"\n >\n Loading local values.\n </p>{/if}\n {:else}\n {#if route.mode === 'edit' && editor && listingEditorEditSource(editor)}\n <ConflictNotice\n source={listingEditorEditSource(editor)!}\n proposed={form}\n />\n {#if editable}<Notice\n tone=\"info\"\n text=\"Changes stay local until you review and publish them.\"\n />{/if}\n {/if}\n {#if !editable}<Notice\n tone=\"info\"\n text={route.mode === 'draft'\n ? 'This draft has a retained listing operation. Keep its original outcome for reconciliation.'\n : 'These retained local values are read-only until the current listing is checked.'}\n />{:else}<p>\n Changes are saved in this browser. Browser storage is not a backup.\n </p>{/if}\n {#if reviewMessage}<Notice tone=\"warning\" text={reviewMessage} />{/if}\n {#if soldConfirm && editable}<ConfirmPanel\n title=\"Confirm sold update\"\n text=\"Marking this listing as sold is a public availability update, not a payment or stock reservation receipt. Review the exact update before publishing.\"\n confirmLabel=\"Review sold update\"\n onconfirm={() => {\n soldConfirm = false;\n void showReview('sold');\n }}\n oncancel={() => {\n soldConfirm = false;\n }}\n />{/if}\n {#if withdrawalConfirm && editable}<ConfirmPanel\n title=\"Confirm removal request\"\n text=\"This public request asks clients to stop displaying the listing. It cannot erase all other copies. Review the exact target before publishing.\"\n confirmLabel=\"Review removal request\"\n onconfirm={() => {\n withdrawalConfirm = false;\n void showReview('withdrawal');\n }}\n oncancel={() => {\n withdrawalConfirm = false;\n }}\n />{/if}\n {#if visibleReview}<ListingReview\n review={visibleReview}\n onedit={editDetails}\n onpublish={route.mode === 'edit'\n ? () => {\n void publishChanges();\n }\n : undefined}\n publishing={publishBusy}\n captured={!!publicationOperation}\n />{:else}\n {#if errors.length}<div\n id=\"listing-review-errors\"\n tabindex=\"-1\"\n role=\"alert\"\n >\n <p>Check these listing fields. Your input remains here.</p>\n <ul>\n {#each errors as error (error.field)}<li>\n <a href={internalHref('#' + fieldId(error.field))}\n >{error.message}</a\n >\n </li>{/each}\n </ul>\n </div>{/if}\n <form\n class=\"stack\"\n onsubmit={(event) => event.preventDefault()}\n novalidate\n >\n <div class=\"field\">\n <label class=\"label\" for=\"listing-title\">Product name</label><input\n id=\"listing-title\"\n aria-invalid={fieldError('title') ? 'true' : undefined}\n aria-errormessage={fieldError('title')\n ? 'listing-title-error'\n : undefined}\n type=\"text\"\n value={form.title}\n oninput={(event) => {\n form = { ...form, title: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('title')}<p id=\"listing-title-error\">\n {fieldError('title')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-description\">Description</label\n ><textarea\n id=\"listing-description\"\n aria-invalid={fieldError('description') ? 'true' : undefined}\n aria-errormessage={fieldError('description')\n ? 'listing-description-error'\n : undefined}\n rows=\"6\"\n value={form.description}\n oninput={(event) => {\n form = { ...form, description: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}></textarea>\n {#if fieldError('description')}<p id=\"listing-description-error\">\n {fieldError('description')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-location\">Public area</label>\n <p id=\"listing-location-hint\" class=\"text-small\">\n A town or collection area is enough.\n </p>\n <input\n id=\"listing-location\"\n aria-invalid={fieldError('location') ? 'true' : undefined}\n aria-errormessage={fieldError('location')\n ? 'listing-location-error'\n : undefined}\n type=\"text\"\n aria-describedby=\"listing-location-hint\"\n value={form.location}\n oninput={(event) => {\n form = { ...form, location: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('location')}<p id=\"listing-location-error\">\n {fieldError('location')?.message}\n </p>{/if}\n </div>\n <div class=\"cluster\">\n <div class=\"field\">\n <label class=\"label\" for=\"listing-amount\">Price</label><input\n id=\"listing-amount\"\n aria-invalid={fieldError('amount') ? 'true' : undefined}\n aria-errormessage={fieldError('amount')\n ? 'listing-amount-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n value={form.amount}\n oninput={(event) => {\n form = { ...form, amount: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('amount')}<p id=\"listing-amount-error\">\n {fieldError('amount')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-currency\">Currency</label><input\n id=\"listing-currency\"\n aria-invalid={fieldError('currency') ? 'true' : undefined}\n aria-errormessage={fieldError('currency')\n ? 'listing-currency-error'\n : undefined}\n type=\"text\"\n maxlength=\"3\"\n value={form.currency}\n oninput={(event) => {\n form = { ...form, currency: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('currency')}<p id=\"listing-currency-error\">\n {fieldError('currency')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-unit\">Per</label><select\n id=\"listing-unit\"\n aria-invalid={fieldError('unit') ? 'true' : undefined}\n aria-errormessage={fieldError('unit')\n ? 'listing-unit-error'\n : undefined}\n value={form.unit}\n onchange={(event) => {\n form = { ...form, unit: event.currentTarget.value };\n changed();\n }}\n disabled={!editable}\n ><option value=\"\">Choose a unit</option\n >{#each foodUnits as unit (unit)}<option value={unit}\n >{unit}</option\n >{/each}</select\n >\n {#if fieldError('unit')}<p id=\"listing-unit-error\">\n {fieldError('unit')?.message}\n </p>{/if}\n </div>\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-quantity\"\n >Advertised quantity (optional)</label\n >\n <p id=\"listing-quantity-unit\">\n {form.unit || 'Uses the selected price unit'}\n </p>\n <input\n id=\"listing-quantity\"\n aria-invalid={fieldError('quantity') ? 'true' : undefined}\n aria-errormessage={fieldError('quantity')\n ? 'listing-quantity-error'\n : undefined}\n type=\"text\"\n inputmode=\"decimal\"\n aria-describedby=\"listing-quantity-unit\"\n value={form.quantity}\n oninput={(event) => {\n form = { ...form, quantity: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('quantity')}<p id=\"listing-quantity-error\">\n {fieldError('quantity')?.message}\n </p>{/if}\n </div>\n <details>\n <summary>Add public contact details (optional)</summary>\n <div class=\"stack\">\n <p>Only add contact details you want to include publicly.</p>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-type\"\n >Public contact type</label\n ><select\n id=\"listing-contact-type\"\n aria-invalid={fieldError('contactType') ? 'true' : undefined}\n aria-errormessage={fieldError('contactType')\n ? 'listing-contact-type-error'\n : undefined}\n value={form.contactType}\n onchange={(event) => {\n const value = event.currentTarget.value;\n if (\n value === '' ||\n value === 'email' ||\n value === 'phone' ||\n value === 'https'\n ) {\n form = { ...form, contactType: value };\n changed();\n }\n }}\n disabled={!editable}\n ><option value=\"\">No public contact</option><option\n value=\"email\">Email</option\n ><option value=\"phone\">Phone</option><option value=\"https\"\n >Website</option\n ></select\n >\n {#if fieldError('contactType')}<p id=\"listing-contact-type-error\">\n {fieldError('contactType')?.message}\n </p>{/if}\n </div>\n <div class=\"field\">\n <label class=\"label\" for=\"listing-contact-value\"\n >Public contact details</label\n ><input\n id=\"listing-contact-value\"\n aria-invalid={fieldError('contactValue') ? 'true' : undefined}\n aria-errormessage={fieldError('contactValue')\n ? 'listing-contact-value-error'\n : undefined}\n type=\"text\"\n value={form.contactValue}\n oninput={(event) => {\n form = { ...form, contactValue: event.currentTarget.value };\n changed();\n }}\n readonly={!editable}\n />\n {#if fieldError('contactValue')}<p\n id=\"listing-contact-value-error\"\n >\n {fieldError('contactValue')?.message}\n </p>{/if}\n </div>\n </div>\n </details>\n </form>\n {#if editable}<button\n type=\"button\"\n onclick={() => {\n void showReview();\n }}\n disabled={reviewBusy || closeBusy}\n >{reviewBusy\n ? 'Preparing review'\n : route.mode === 'edit'\n ? 'Review changes'\n : 'Review listing'}</button\n >{/if}\n {/if}\n {#if editable && route.mode === 'edit' && !visibleReview}<details>\n <summary>Other listing actions</summary>\n <button\n type=\"button\"\n onclick={() => {\n soldConfirm = true;\n }}\n disabled={reviewBusy || closeBusy}>Mark as sold</button\n >\n <button\n type=\"button\"\n onclick={() => {\n withdrawalConfirm = true;\n }}\n disabled={reviewBusy || closeBusy}>Request removal</button\n >\n </details>{/if}\n {#if publishBusy && review && editorReviewSnapshot(review)?.withdrawal}\n <p>\n Stop stops further attempts; it cannot retract requests already sent or\n whose outcome is unknown.\n </p>\n <button\n type=\"button\"\n onclick={() => {\n if (review) stopEditorAction(review);\n }}>Stop current action</button\n >\n {/if}\n {#if publicationOperation}<OperationStatus\n publicOperation={publicationOperation}\n />{/if}\n {#if editable && route.mode !== 'edit' && setup}<InboxSetup\n controller={setup}\n inline\n />{/if}\n {#each visible.operations as operation (operation)}<OperationStatus\n publicOperation={operation}\n />{/each}\n {#if editable}<button\n type=\"button\"\n onclick={saveClose}\n disabled={closeBusy || reviewBusy}>Save and close</button\n >{/if}\n {#if navigationFailed}<Notice\n tone=\"warning\"\n text=\"Navigation did not complete. Your saved local data remains in this browser.\"\n />{/if}\n {#if editable}<p role=\"status\">\n {visible.state === 'saved'\n ? 'Saved in this browser.'\n : visible.state === 'saving'\n ? 'Saving in this browser.'\n : visible.state === 'failed'\n ? 'Not saved. Keep your current input here.'\n : 'Not yet saved.'}\n </p>\n {#if visible.failure}<Notice\n tone=\"warning\"\n text=\"Saving did not complete. Keep your current input. Existing local data has not been reset.\"\n />{/if}{/if}\n {/if}\n</div>\n", 143 sha256: 144 '060f4863f6f4f2a4fb1471bb0d5eeedf31ab13b5c83d894f47757cf5a68099e6' 145 }, 146 'src/lib/components/MessageComposer.svelte': { 147 source: 148 "<script lang=\"ts\">\n /* global document, setInterval, clearInterval */\n import { onMount, tick } from 'svelte';\n import { beforeNavigate, goto } from '$app/navigation';\n import { internalHref } from '../navigation-url.ts';\n import {\n productRequestSnapshot,\n productRequestText,\n updateProductRequestText,\n sendProductRequest,\n requestProductRequestNavigation,\n keepProductRequestEditing,\n discardProductRequestNavigation,\n productRequestBeforeUnload,\n closeProductRequestController,\n type ProductRequestController\n } from '../messaging/product-request-controller.ts';\n import {\n replySnapshot,\n replyText,\n updateReplyText,\n sendReply,\n requestReplyNavigation,\n keepReplyEditing,\n discardReplyNavigation,\n replyBeforeUnload,\n closeReplyController,\n type ReplyController\n } from '../messaging/reply-controller.ts';\n let {\n controller,\n request,\n oncancel,\n ondiscard,\n focusScope = 'enquiry'\n }: {\n controller?: ReplyController;\n request?: ProductRequestController;\n oncancel?: () => void;\n ondiscard?: () => void;\n focusScope?: 'conversation' | 'enquiry';\n } = $props();\n let model = $state<\n | ReturnType<typeof replySnapshot>\n | ReturnType<typeof productRequestSnapshot>\n >(),\n text = $state('');\n let destination: string | undefined,\n disposed = false;\n const fieldId = $derived(\n focusScope === 'conversation' ? 'conversation-reply' : 'enquiry-reply'\n );\n function focusEditor() {\n if (disposed) return;\n if (focusScope === 'conversation')\n document.getElementById('conversation-reply')?.focus();\n else document.getElementById('enquiry-reply')?.focus();\n }\n function focusKeep() {\n if (disposed) return;\n if (focusScope === 'conversation')\n document.getElementById('conversation-keep-reply')?.focus();\n else document.getElementById('enquiry-keep-reply')?.focus();\n }\n function refresh() {\n if (disposed) return;\n model = request\n ? productRequestSnapshot(request)\n : controller && replySnapshot(controller);\n text =\n (request\n ? productRequestText(request)\n : controller && replyText(controller)) ?? '';\n }\n function askNavigation() {\n return request\n ? requestProductRequestNavigation(request)\n : controller\n ? requestReplyNavigation(controller)\n : 'invalid';\n }\n beforeNavigate((event) => {\n if (disposed || askNavigation() !== 'confirmation_required') return;\n event.cancel();\n const url = event.to?.url;\n destination =\n url && !event.willUnload\n ? internalHref(url.pathname + url.search + url.hash)\n : undefined;\n refresh();\n void tick().then(focusKeep);\n });\n onMount(() => {\n refresh();\n const timer = setInterval(refresh, 200);\n return () => {\n disposed = true;\n clearInterval(timer);\n if (request) closeProductRequestController(request);\n else if (controller) closeReplyController(controller);\n text = '';\n model = undefined;\n destination = undefined;\n };\n });\n async function send() {\n const work = request\n ? sendProductRequest(request, 'reviewed_product_request_send')\n : controller && sendReply(controller, 'reviewed_reply_send');\n refresh();\n await work;\n refresh();\n }\n function warnUnload(event: BeforeUnloadEvent) {\n if (request) productRequestBeforeUnload(request, event);\n else if (controller) replyBeforeUnload(controller, event);\n }\n</script>\n\n<svelte:window onbeforeunload={warnUnload} />\n\n{#if model}\n <div class=\"stack\">\n <label for={fieldId}>{request ? 'Your message' : 'Reply'}</label>\n <textarea\n id={fieldId}\n value={text}\n disabled={model.busy || model.state === 'completed'}\n aria-describedby={fieldId + '-save'}\n oninput={(event) => {\n if (request)\n updateProductRequestText(\n request,\n event.currentTarget.value,\n 'reviewed_private_text'\n );\n else if (controller)\n updateReplyText(\n controller,\n event.currentTarget.value,\n 'reviewed_private_text'\n );\n refresh();\n }}></textarea>\n <p id={fieldId + '-save'}>\n {model.saveCopy} Unsent text is lost when this page closes.\n </p>\n <p>{model.pairCopy}</p>\n {#if !request}<p>\n Replying moves this conversation to your inbox in this view. It does not\n accept an order.\n </p>{/if}\n <p>Messages do not reserve products or record payment.</p>\n <button\n type=\"button\"\n class=\"button button--primary\"\n disabled={model.busy ||\n model.state === 'completed' ||\n !text.trim() ||\n (!!request && !productRequestSnapshot(request)?.readyToSend)}\n onclick={() => {\n void send();\n }}>{request ? 'Send request' : 'Send reply'}</button\n >\n <p role=\"status\" aria-live=\"polite\">{model.copy}</p>\n {#if request}<button\n type=\"button\"\n class=\"button button--secondary\"\n onclick={() => {\n oncancel?.();\n destination = undefined;\n if (askNavigation() === 'allowed') ondiscard?.();\n refresh();\n void tick().then(focusKeep);\n }}>Cancel</button\n >{/if}\n {#if model.navigation === 'confirmation_required'}\n <div class=\"notice stack\" role=\"group\" aria-label=\"Unsaved private reply\">\n <p>\n Discard unsaved private text? Keep editing to preserve it. An\n outstanding extension call remains pending until it settles.\n </p>\n <div class=\"cluster\">\n <button\n type=\"button\"\n class=\"button button--secondary\"\n id={focusScope === 'conversation'\n ? 'conversation-keep-reply'\n : 'enquiry-keep-reply'}\n onclick={() => {\n if (request) keepProductRequestEditing(request);\n else if (controller) keepReplyEditing(controller);\n destination = undefined;\n refresh();\n void tick().then(focusEditor);\n }}>Keep editing</button\n >\n <button\n type=\"button\"\n class=\"button button--secondary\"\n onclick={() => {\n const target = internalHref(destination);\n const result = request\n ? discardProductRequestNavigation(\n request,\n 'reviewed_discard_private_text'\n )\n : controller\n ? discardReplyNavigation(\n controller,\n 'reviewed_discard_private_text'\n )\n : 'invalid';\n destination = undefined;\n refresh();\n if (result === 'allowed') {\n ondiscard?.();\n if (target) void goto(target);\n } else void tick().then(focusEditor);\n }}>Discard draft</button\n >\n </div>\n </div>\n {/if}\n </div>\n{/if}\n", 149 sha256: 150 'bc8ac0e2123b60957f1c289acbb2b8740e171097029f640f657cd79f5aa8423b' 151 }, 152 'src/lib/publishing/prepare-listing.ts': { 153 source: 154 "import { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport type {\n PublicDraftRecord,\n PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId, newLocalId } from '../private-handles.ts';\nimport { readRelayPolicy, publicRelayTargets } from '../config/relays.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport {\n decodePublicRecord,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n publicPublicationOwner,\n publicPublicationDraftRepository,\n savePublicListingIntent,\n type PublicPublicationRepository,\n type PublicListingSave\n} from '../persistence/public-publications.ts';\nimport {\n publicDraftControllerOwnership,\n publicDraftControllerSnapshot,\n flushPublicDraft,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n newListingReadinessOwnership,\n captureOwnedListingReadiness,\n closeNewListingReadiness,\n type NewListingReadiness\n} from './new-listing-readiness.ts';\nimport {\n authorizeOwnedEditSource,\n type OwnedEditSource\n} from './edit-source.ts';\nimport {\n assessFutureTimestamp,\n wallClockAvailable\n} from '../catalog/clock-policy.ts';\n\ndeclare const reviewBrand: unique symbol;\nexport type ListingReview = Readonly<{ [reviewBrand]: true }>;\nexport type ListingPreview = Readonly<{\n owner: string;\n command: string;\n draftId: string;\n draftRevision: number;\n identifier: string;\n createdAtSeconds: number;\n form: PublicDraftForm;\n summary: string;\n templateWire: string;\n expectedHash: string;\n targets: readonly string[];\n policyFingerprint: string;\n withdrawal?: Readonly<{ coordinate: string; eventId: string }>;\n revision?: Readonly<{\n coordinate: string;\n publishedAtSeconds: number;\n status: 'active' | 'sold';\n }>;\n}>;\ntype Review = Readonly<{\n repository: PublicPublicationRepository;\n controller: PublicDraftController;\n expected: PublicDraftRecord;\n editVersion: number;\n command: string;\n readiness: NewListingReadiness;\n source?: OwnedEditSource;\n status?: 'active' | 'sold' | 'withdrawal';\n record: PublicRecordHandle;\n revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>;\n previewWire: string;\n current(this: void): boolean;\n}>;\nconst reviews = new WeakMap<ListingReview, Review>();\nconst commands = new WeakMap<\n PublicPublicationRepository,\n Map<string, ListingReview>\n>();\nconst activeReservations = new WeakMap<\n ListingReview,\n Promise<ListingReservation>\n>();\nexport type ListingReviewResult =\n | Readonly<{ status: 'review'; review: ListingReview }>\n | Readonly<{\n status: 'blocked';\n reason:\n | 'invalid_scope'\n | 'invalid_command'\n | 'unavailable'\n | 'invalid_form'\n | 'conflict';\n }>;\nexport type ListingReservation =\n PublicListingSave | Readonly<{ status: 'invalid' }>;\n// Review flushes local draft state and prepares an exact immutable template;\n// it neither reserves a publication nor asks the extension to sign.\nexport async function reviewNewListing(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n readiness: NewListingReadiness,\n command: unknown,\n consent: unknown\n): Promise<ListingReviewResult> {\n return reviewListing(repository, controller, readiness, command, consent);\n}\n// Pure declared clock policy; production supplies actual Date.now below.\nexport function ownedRevisionTimestamp(\n head: number,\n now: number\n): number | undefined {\n if (\n !Number.isSafeInteger(head) ||\n head < 0 ||\n head >= Number.MAX_SAFE_INTEGER ||\n !wallClockAvailable(now)\n )\n return;\n const next = Math.max(head + 1, Math.floor(now));\n return assessFutureTimestamp(next, now) === 'within_policy'\n ? next\n : undefined;\n}\nexport async function reviewOwnedListing(\n source: OwnedEditSource,\n controller: PublicDraftController,\n command: unknown,\n status: 'active' | 'sold' | 'withdrawal',\n consent: unknown\n): Promise<ListingReviewResult> {\n const original = authorizeOwnedEditSource(source);\n if (!original) return { status: 'blocked', reason: 'invalid_scope' };\n return reviewListing(\n original.repository,\n controller,\n undefined,\n command,\n consent,\n { source, status }\n );\n}\nasync function reviewListing(\n repository: PublicPublicationRepository,\n controller: PublicDraftController,\n readiness: NewListingReadiness | undefined,\n command: unknown,\n consent: unknown,\n revision?: Readonly<{\n source: OwnedEditSource;\n status: 'active' | 'sold' | 'withdrawal';\n }>\n): Promise<ListingReviewResult> {\n try {\n const custody = publicDraftControllerOwnership(controller),\n owner = publicPublicationOwner(repository);\n if (\n !custody ||\n !owner ||\n custody.repository !== publicPublicationDraftRepository(repository)\n )\n return { status: 'blocked', reason: 'invalid_scope' };\n const id = canonicalLocalId(command);\n if (!id) return { status: 'blocked', reason: 'invalid_command' };\n const retained = revision && authorizeOwnedEditSource(revision.source);\n const ready = revision ? retained : newListingReadinessOwnership(readiness);\n if (\n !ready ||\n ready.owner !== owner ||\n !ready.current() ||\n consent !==\n (revision\n ? revision.status === 'withdrawal'\n ? 'reviewed_owned_withdrawal'\n : revision.status === 'sold'\n ? 'reviewed_sold_availability'\n : 'reviewed_owned_revision'\n : 'reviewed_new_listing')\n )\n return { status: 'blocked', reason: 'unavailable' };\n if (!(await flushPublicDraft(controller)))\n return { status: 'blocked', reason: 'unavailable' };\n const snapshot = publicDraftControllerSnapshot(controller),\n expected = snapshot?.draft;\n if (\n !snapshot ||\n !expected ||\n expected.owner !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n const cached = commands.get(repository)?.get(id);\n if (cached) {\n const original = reviews.get(cached);\n if (\n original &&\n original.controller === controller &&\n (revision\n ? original.source === revision.source &&\n original.status === revision.status\n : original.readiness === readiness) &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n ) {\n return { status: 'review', review: cached };\n }\n return { status: 'blocked', reason: 'conflict' };\n }\n const baseProof = retained && verifyEnvelope(retained.baseWire);\n const base = baseProof?.ok\n ? verifiedEnvelopeSnapshot(baseProof.value)\n : undefined;\n const identifier = revision\n ? base?.tags.find((tag) => tag[0] === 'd')?.[1]\n : newLocalId();\n const now = Math.floor(Date.now() / 1000);\n const createdAtSeconds = revision\n ? base && ownedRevisionTimestamp(base.created_at, now)\n : now;\n if (!identifier || createdAtSeconds === undefined)\n return {\n status: 'blocked',\n reason: revision ? 'conflict' : 'unavailable'\n };\n const form = expected.form;\n const withdrawal = revision?.status === 'withdrawal';\n if (!withdrawal && form.contactType === '' && form.contactValue !== '')\n return { status: 'blocked', reason: 'invalid_form' };\n const contact =\n form.contactType === ''\n ? undefined\n : {\n type: form.contactType,\n value: form.contactValue,\n public: true as const\n };\n const built = buildFoodTemplate({\n identifier,\n title: form.title,\n description: form.description,\n location: form.location,\n amount: form.amount,\n currency: form.currency,\n unit: form.unit,\n ...(form.quantity === '' ? {} : { quantity: form.quantity }),\n created_at: createdAtSeconds,\n published_at: retained ? retained.publishedAtSeconds : createdAtSeconds,\n status: revision?.status === 'sold' ? 'sold' : 'active',\n ...(contact ? { contact } : {})\n });\n if (!withdrawal && !built.ok)\n return { status: 'blocked', reason: 'invalid_form' };\n const manifest = readRelayPolicy(ready.policy),\n targets = publicRelayTargets(ready.policy, 'write');\n const templateWire = JSON.stringify({\n pubkey: owner,\n kind: withdrawal ? 5 : 30402,\n created_at: createdAtSeconds,\n tags:\n withdrawal && base\n ? [\n ['e', base.id],\n ['a', `30402:${owner}:${identifier}`],\n ['k', '30402']\n ]\n : built.ok\n ? built.wire_parts.tags\n : [],\n content: withdrawal ? '' : built.ok ? built.wire_parts.content : ''\n });\n const template = inspectLocalTemplate(\n templateWire,\n owner,\n withdrawal ? 5 : 30402\n );\n if (!template || !manifest.postingEnabled || targets.length === 0)\n return { status: 'blocked', reason: 'unavailable' };\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(manifest))\n );\n const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>\n value.toString(16).padStart(2, '0')\n ).join('');\n // Hashing is outside any IDB transaction; recheck original mutable owners.\n if (\n !ready.current() ||\n publicPublicationOwner(repository) !== owner ||\n !custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'blocked', reason: 'conflict' };\n // Another review may have completed while this one awaited hashing. The\n // first retained command owns its ID/time/template; never replace it.\n const racing = commands.get(repository)?.get(id);\n if (racing) {\n const original = reviews.get(racing);\n if (\n original &&\n original.controller === controller &&\n (revision\n ? original.source === revision.source &&\n original.status === revision.status\n : original.readiness === readiness) &&\n JSON.stringify(original.expected) === JSON.stringify(expected) &&\n original.current() &&\n custody.current(JSON.stringify(expected), snapshot.editVersion)\n )\n return { status: 'review', review: racing };\n return { status: 'blocked', reason: 'conflict' };\n }\n const admitted = decodePublicRecord(\n JSON.stringify({\n schema: 1,\n family: 'public_operation',\n owner,\n id,\n revision: 0,\n source:\n withdrawal && retained\n ? { type: 'public_head', wire: retained.baseWire }\n : { type: 'draft', id: expected.id, revision: expected.revision },\n capture: {\n kind: withdrawal ? 5 : 30402,\n wire: templateWire,\n hash: template.hash,\n targets,\n policyFingerprint\n },\n artifact: null,\n receipts: []\n }),\n owner,\n id\n );\n if (!admitted.ok) return { status: 'blocked', reason: 'invalid_form' };\n const proof = revision\n ? captureOwnedListingReadiness(\n revision.source,\n template.hash,\n withdrawal ? 'reviewed_owned_withdrawal' : 'reviewed_owned_listing'\n )\n : readiness;\n const finalReady = newListingReadinessOwnership(proof);\n if (!proof || !finalReady || !finalReady.current())\n return { status: 'blocked', reason: 'conflict' };\n const review = Object.freeze({}) as ListingReview;\n reviews.set(review, {\n repository,\n controller,\n expected,\n editVersion: snapshot.editVersion,\n command: id,\n readiness: proof,\n ...(revision ? { source: revision.source, status: revision.status } : {}),\n record: admitted.value,\n ...(retained\n ? {\n revisionBase: {\n command: retained.sourceCommand,\n record: retained.sourceRecord\n }\n }\n : {}),\n previewWire: JSON.stringify({\n owner,\n command: id,\n draftId: expected.id,\n draftRevision: expected.revision,\n identifier,\n createdAtSeconds,\n form,\n summary: withdrawal ? 'Removal request' : built.ok ? built.summary : '',\n templateWire,\n expectedHash: template.hash,\n targets,\n policyFingerprint,\n ...(withdrawal && retained && base\n ? {\n withdrawal: { coordinate: retained.coordinate, eventId: base.id }\n }\n : {}),\n ...(retained && revision && !withdrawal\n ? {\n revision: {\n coordinate: retained.coordinate,\n publishedAtSeconds: retained.publishedAtSeconds,\n status: revision.status\n }\n }\n : {})\n }),\n current: () =>\n finalReady.current() &&\n publicPublicationOwner(repository) === owner &&\n (!revision ||\n assessFutureTimestamp(\n createdAtSeconds,\n Math.floor(Date.now() / 1000)\n ) === 'within_policy')\n });\n const cache = commands.get(repository) ?? new Map<string, ListingReview>();\n cache.set(id, review);\n commands.set(repository, cache);\n return { status: 'review', review };\n } catch {\n return { status: 'blocked', reason: 'unavailable' };\n }\n}\nexport function listingReviewSnapshot(\n review: ListingReview\n): ListingPreview | undefined {\n const value = reviews.get(review);\n return value ? (JSON.parse(value.previewWire) as ListingPreview) : undefined;\n}\nexport function closeListingReview(review: ListingReview): void {\n const original = reviews.get(review);\n if (original) closeNewListingReadiness(original.readiness);\n}\n// Internal original custody, not a signing or transport permission. The later\n// controller must reread the persisted intent and obtain its own effect lease.\nexport function listingReviewOwnership(review: ListingReview) {\n const original = reviews.get(review);\n const ready = original && newListingReadinessOwnership(original.readiness);\n return original && ready && original.current()\n ? {\n repository: original.repository,\n record: original.record,\n command: original.command,\n readiness: ready,\n current: original.current\n }\n : undefined;\n}\n// One original review deduplicates simultaneous clicks. Failed/uncertain work\n// remains the same capture for later explicit retry; no fresh ID/time/template.\nexport function reserveNewListing(\n review: ListingReview,\n consent: unknown\n): Promise<ListingReservation> {\n const value = reviews.get(review);\n if (!value || consent !== 'publish_reviewed_listing')\n return Promise.resolve({ status: 'invalid' });\n const active = activeReservations.get(review);\n if (active) return active;\n const work = savePublicListingIntent(\n value.repository,\n value.controller,\n value.record,\n value.expected,\n value.editVersion,\n value.command,\n value.current,\n value.revisionBase\n ).finally(() => {\n if (activeReservations.get(review) === work)\n activeReservations.delete(review);\n });\n activeReservations.set(review, work);\n return work;\n}\n", 155 sha256: 156 '00b922e8b0bfc73cf5ac59857472e8dd627c8df62d28f1c646c5d7c76ce5ede9' 157 }, 158 'src/lib/nostr/listing-publisher.ts': { 159 source: 160 "import type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n listingPublicationOwnership,\n type ListingPublication\n} from '../publishing/sign-listing.ts';\nimport {\n listingResumeOwnership,\n type ListingResumption\n} from '../publishing/resume-listing.ts';\nimport {\n listingRetryOwnership,\n type ListingRetry\n} from '../publishing/retry-listing.ts';\nimport {\n identityMessagingOwnership,\n identityPublicOperationOwnership,\n recheckIdentityOwner,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport { preferencePolicyFingerprint } from './inbox-preference-publication.ts';\nimport { readPublicListingIntent } from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\ndeclare const leaseBrand: unique symbol;\ndeclare const permissionBrand: unique symbol;\nexport type ListingDeliveryLease = Readonly<{ [leaseBrand]: true }>;\nexport type ListingAttemptPermission = Readonly<{ [permissionBrand]: true }>;\ntype Original = NonNullable<\n | ReturnType<typeof listingPublicationOwnership>\n | ReturnType<typeof listingResumeOwnership>\n>;\ntype Owner = Readonly<{\n original: Original;\n policy: RelayPolicy;\n signal?: AbortSignal;\n current(): boolean;\n}>;\ntype Permission = Readonly<{\n owner: Owner;\n origin: string;\n mode: 'publish' | 'readback';\n wire: string;\n}>;\nconst leases = new WeakMap<ListingDeliveryLease, Owner>();\nconst permissions = new WeakMap<ListingAttemptPermission, Permission>();\n// Stop releases this action's wait and author lock. The extension promise may\n// settle later; it cannot resurrect the revoked network lease or a signer.\nasync function recheckDeliveryOwner(\n identity: IdentitySession,\n signal?: AbortSignal\n): Promise<boolean> {\n if (signal?.aborted) return false;\n if (!signal) {\n await recheckIdentityOwner(identity);\n return true;\n }\n let stop = () => {};\n const stopped = new Promise<boolean>((resolve) => {\n stop = () => resolve(false);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n });\n try {\n return await Promise.race([\n recheckIdentityOwner(identity).then(() => true),\n stopped\n ]);\n } finally {\n signal.removeEventListener('abort', stop);\n }\n}\n// Receipt revisions may grow, but the complete original operation payload and\n// verified artifact stay exact. No new command, author or destination is adopted.\nexport async function readRetainedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner) return;\n const original = owner.original;\n const expected = decodePublicRecord(\n original.recordWire,\n original.owner,\n original.command\n );\n if (!expected.ok) return;\n const baseline = publicRecordSnapshot(\n expected.value,\n original.owner,\n original.command\n );\n if (\n baseline?.family !== 'public_operation' ||\n !(\n baseline.capture.kind === 30402 ||\n (baseline.capture.kind === 5 && baseline.source.type === 'public_head')\n ) ||\n !baseline.artifact ||\n baseline.revision !== 2\n )\n return;\n const read = await readPublicListingIntent(\n original.repository,\n original.command\n );\n if (read.status !== 'found') return;\n const row = publicRecordSnapshot(\n read.record,\n original.owner,\n original.command\n );\n if (\n row?.family !== 'public_operation' ||\n row.revision < baseline.revision ||\n JSON.stringify({\n ...row,\n revision: baseline.revision,\n receipts: baseline.receipts\n }) !== JSON.stringify(baseline)\n )\n return;\n return read.record;\n}\n// Current authority is mandatory for every new network permission. Retained\n// exact storage observation above remains usable for bookkeeping after Stop.\nexport async function readOwnedListingDelivery(\n lease: ListingDeliveryLease\n): Promise<PublicRecordHandle | undefined> {\n const owner = leases.get(lease);\n if (!owner?.current()) return;\n const read = readRetainedListingDelivery(lease);\n let stop = () => {};\n const stopped =\n owner.signal &&\n new Promise<undefined>((resolve) => {\n stop = () => resolve(undefined);\n owner.signal!.addEventListener('abort', stop, { once: true });\n if (owner.signal!.aborted) stop();\n });\n let record: PublicRecordHandle | undefined;\n try {\n record = await (stopped ? Promise.race([read, stopped]) : read);\n } finally {\n owner.signal?.removeEventListener('abort', stop);\n }\n return owner.current() ? record : undefined;\n}\nexport function listingDeliveryOwnership(lease: ListingDeliveryLease) {\n const owner = leases.get(lease);\n return owner?.current()\n ? {\n repository: owner.original.repository,\n owner: owner.original.owner,\n command: owner.original.command,\n current: owner.current\n }\n : undefined;\n}\nexport type ListingOwnershipResult<T> =\n | Readonly<{ status: 'completed'; value: T }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'busy' | 'stopped' }>;\n// One original author lock spans this finite explicitly requested network\n// action. It never spans a native IDB transaction and cannot mint a signer.\nexport async function withListingDeliveryOwnership<T>(\n publication: ListingPublication | ListingResumption,\n policy: RelayPolicy,\n consent: unknown,\n work: (lease: ListingDeliveryLease) => Promise<T>,\n control?: ListingRetry\n): Promise<ListingOwnershipResult<T>> {\n const signed = listingPublicationOwnership(publication as ListingPublication),\n resumed = listingResumeOwnership(publication as ListingResumption),\n original = signed ?? resumed,\n retry = control && listingRetryOwnership(control);\n if (\n !original ||\n (control\n ? !retry ||\n retry.source !== publication ||\n retry.policy !== policy ||\n retry.consent !== consent\n : !signed || consent !== 'publish_stored_listing') ||\n original.policy !== policy\n )\n return { status: 'invalid' };\n if (retry && !retry.current()) return { status: 'stopped' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n try {\n return await navigator.locks.request(\n 'harvestcircle:owner:' + original.owner,\n { mode: 'exclusive', ifAvailable: true },\n async (lock): Promise<ListingOwnershipResult<T>> => {\n if (!lock) return { status: 'busy' };\n if (!(await recheckDeliveryOwner(original.identity, retry?.signal)))\n return { status: 'stopped' };\n const operation =\n signed &&\n identityPublicOperationOwnership(\n original.identity,\n signed.operation\n ),\n // A signed public update retains its original public operation.\n // New-listing inbox readiness stays in original.current(); edits\n // do not require a messaging probe. Resumptions keep their gate.\n identity = signed\n ? operation\n : identityMessagingOwnership(original.identity);\n if (\n !identity ||\n (signed && !operation) ||\n identity.owner !== original.owner ||\n (operation &&\n (operation.owner !== original.owner ||\n operation.session !== identity.session)) ||\n !original.current() ||\n (retry && !retry.current())\n )\n return { status: 'stopped' };\n let active = true;\n const owner: Owner = {\n original,\n policy,\n signal: retry?.signal,\n current: () =>\n active &&\n original.current() &&\n identity.current() &&\n (!operation || operation.current()) &&\n (!retry || retry.current())\n };\n const lease = Object.freeze({}) as ListingDeliveryLease;\n leases.set(lease, owner);\n try {\n if (!(await readOwnedListingDelivery(lease)))\n return {\n status: retry && !retry.current() ? 'stopped' : 'unavailable'\n };\n return { status: 'completed', value: await work(lease) };\n } finally {\n active = false;\n }\n }\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Each permission comes from actual stored signed bytes, fresh identity and\n// unchanged original policy. Preference/private capabilities cannot enter it.\nexport async function authorizeListingAttempt(\n lease: ListingDeliveryLease,\n origin: string,\n mode: 'publish' | 'readback'\n): Promise<ListingAttemptPermission | undefined> {\n const owner = leases.get(lease);\n if (!owner || !owner.current() || (mode !== 'publish' && mode !== 'readback'))\n return;\n try {\n const record = await readOwnedListingDelivery(lease),\n original = owner.original;\n const row =\n record && publicRecordSnapshot(record, original.owner, original.command);\n const manifest = readRelayPolicy(owner.policy),\n targets = publicRelayTargets(owner.policy, 'write'),\n fingerprint = await preferencePolicyFingerprint(owner.policy);\n if (\n row?.family !== 'public_operation' ||\n !row.artifact ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets) ||\n !row.capture.targets.includes(origin)\n )\n return;\n if (!(await recheckDeliveryOwner(original.identity, owner.signal))) return;\n if (!owner.current()) return;\n const token = Object.freeze({}) as ListingAttemptPermission;\n permissions.set(token, { owner, origin, mode, wire: row.artifact.wire });\n return token;\n } catch {\n return;\n }\n}\n// Original once-only token: detached metadata, wrong role, policy or origin\n// cannot supply a raw event. SDK effects remain owned by the public pool.\nexport function takeListingPublication(\n token: ListingAttemptPermission,\n policy: RelayPolicy,\n origin: string,\n mode: 'publish' | 'readback'\n):\n | Readonly<{ event: NostrEvent; wire: string; current(): boolean }>\n | undefined {\n const saved = permissions.get(token);\n if (!saved) return;\n permissions.delete(token);\n if (\n saved.owner.policy !== policy ||\n saved.origin !== origin ||\n saved.mode !== mode ||\n !saved.owner.current()\n )\n return;\n return {\n event: JSON.parse(saved.wire) as NostrEvent,\n wire: saved.wire,\n current: saved.owner.current\n };\n}\n", 161 sha256: 162 '10032c32482a766158d8a69027056e6a822a16b5f68ab9754b0f1cf42d0608f9' 163 }, 164 'src/lib/publishing/resume-listing.ts': { 165 source: 166 "import {\n publicPublicationOwner,\n readPublicListingIntent,\n type PublicPublicationRepository\n} from '../persistence/public-publications.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot\n} from '../persistence/records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n identityMessagingOwnership,\n recheckIdentityOwner,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport { preferencePolicyFingerprint } from '../nostr/inbox-preference-publication.ts';\nimport type { PublicPool } from '../nostr/public-pool.ts';\nimport { beginListingRetry } from './retry-listing.ts';\n\ndeclare const resumeBrand: unique symbol;\nexport type ListingResumption = Readonly<{ [resumeBrand]: true }>;\ntype Ownership = Readonly<{\n repository: PublicPublicationRepository;\n identity: IdentitySession;\n policy: RelayPolicy;\n owner: string;\n command: string;\n recordWire: string;\n current(): boolean;\n}>;\nconst resumptions = new WeakMap<ListingResumption, Ownership>();\nexport function listingResumeOwnership(token: ListingResumption) {\n const original = resumptions.get(token);\n return original?.current() ? original : undefined;\n}\nexport function listingResumeSnapshot(token: ListingResumption) {\n const original = listingResumeOwnership(token);\n if (!original) return;\n const decoded = decodePublicRecord(\n original.recordWire,\n original.owner,\n original.command\n );\n const row =\n decoded.ok &&\n publicRecordSnapshot(decoded.value, original.owner, original.command);\n if (!row || row.family !== 'public_operation' || !row.artifact) return;\n return {\n owner: row.owner,\n command: row.id,\n hash: row.artifact.eventId,\n wire: row.artifact.wire,\n targets: row.capture.targets.slice(),\n policyFingerprint: row.capture.policyFingerprint\n };\n}\nexport async function prepareListingResume(\n repository: PublicPublicationRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n command: unknown,\n consent: unknown\n): Promise<\n | Readonly<{ status: 'ready'; resume: ListingResumption }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'needs_action' }>\n> {\n const owner = publicPublicationOwner(repository),\n id = canonicalLocalId(command);\n if (\n !owner ||\n !id ||\n !identityMessagingOwnership(identity) ||\n consent !== 'reviewed_stored_listing_resume'\n )\n return { status: 'invalid' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable' };\n try {\n await recheckIdentityOwner(identity);\n const capture = identityMessagingOwnership(identity);\n if (!capture || capture.owner !== owner) return { status: 'needs_action' };\n const current = () =>\n capture.current() && publicPublicationOwner(repository) === owner;\n const read = await readPublicListingIntent(repository, id);\n const row =\n read.status === 'found' && publicRecordSnapshot(read.record, owner, id);\n const manifest = readRelayPolicy(policy),\n targets = publicRelayTargets(policy, 'write'),\n fingerprint = await preferencePolicyFingerprint(policy);\n if (\n !current() ||\n !row ||\n row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n !row.artifact ||\n row.revision < 2 ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets)\n )\n return { status: 'needs_action' };\n // Normalize receipt bookkeeping only. Every original capture field and the\n // independently verified stored signature remain exact; no signer is minted.\n const recordWire = JSON.stringify({ ...row, revision: 2, receipts: [] });\n if (!decodePublicRecord(recordWire, owner, id).ok || !current())\n return { status: 'needs_action' };\n const resume = Object.freeze({}) as ListingResumption;\n resumptions.set(resume, {\n repository,\n identity,\n policy,\n owner,\n command: id,\n recordWire,\n current\n });\n return { status: 'ready', resume };\n } catch {\n return { status: 'needs_action' };\n }\n}\nexport function resumeListing(\n token: ListingResumption,\n pool: PublicPool,\n consent: unknown\n) {\n const original = listingResumeOwnership(token);\n if (!original || consent !== 'resume_stored_listing') return;\n return beginListingRetry(token, pool, original.policy, consent);\n}\n", 167 sha256: 168 '42cd0404f1e543e03350e6c8c92fce5a1c4f8eb02f9540831fc6c7cf84bba9a9' 169 }, 170 'src/lib/messaging/inbox-setup.ts': { 171 source: 172 "import { exactLocalFields } from '../contracts/local-records.ts';\nimport { boundedUtf8 } from '../contracts/food-availability-v1/text.ts';\nimport { safeUnsignedInteger } from '../nostr/envelope-bounds.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n inboxPreferenceSnapshot,\n inboxPreferenceWire\n} from '../nostr/inbox-preferences.ts';\nimport {\n canonicalRelayOrigin,\n readRelayPolicy,\n publicRelayTargets,\n inboxRelayTargets,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n identityMessagingOwnership,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n inboxResolutionSnapshot,\n inboxResolverCurrentAfterSample,\n type InboxResolver\n} from './resolve-inbox.ts';\n\ndeclare const reviewBrand: unique symbol;\nexport type InboxSetupReview = Readonly<{ [reviewBrand]: true }>;\ntype Preview = {\n author: string;\n originalWire: string | null;\n baseId: string | null;\n wire: string;\n hash: string;\n policyFingerprint: string;\n selectedInboxes: string[];\n destinations: string[];\n removedTagIndices: number[];\n removedExtraFields: string[];\n globalEffect: string;\n};\ntype Saved = Readonly<{\n identity: IdentitySession;\n session: symbol;\n policy: RelayPolicy;\n previewWire: string;\n}>;\nconst reviews = new WeakMap<InboxSetupReview, Saved>();\nconst globalEffect =\n 'This replaces your public inbox preference for other clients. Relay acceptance and readback are still required; this review does not publish.';\nfunction base(resolver: InboxResolver, policy: RelayPolicy, owner: string) {\n const resolution = inboxResolutionSnapshot(resolver),\n discovery = publicRelayTargets(policy, 'read');\n if (\n resolution.author !== owner ||\n resolution.coverage !== 'bounded-eose' ||\n resolution.status === 'inconclusive' ||\n discovery.length === 0 ||\n discovery.length !== resolution.sources.length ||\n !discovery.every((origin) =>\n resolution.sources.some(\n (row) => row.source === origin && row.state === 'eose'\n )\n )\n )\n return undefined;\n if (resolution.status === 'missing')\n return !resolution.head && !resolution.knownBase\n ? { wire: null, id: null, createdAt: undefined }\n : undefined;\n const head = resolution.head && inboxPreferenceSnapshot(resolution.head),\n wire = resolution.head && inboxPreferenceWire(resolution.head);\n return head &&\n wire &&\n head.author === owner &&\n head.id === resolution.knownBase?.id\n ? { wire, id: head.id, createdAt: head.createdAt }\n : undefined;\n}\n// Explicit source review only. The clock is an internal observation port like\n// the resolver clock; production uses actual wall time, tests control it. No\n// caller event extras enter the canonical signing contract implicitly.\nexport async function reviewInboxSetup(\n identity: IdentitySession,\n resolver: InboxResolver,\n policy: RelayPolicy,\n raw: unknown,\n observeNow: () => number = () => Math.floor(Date.now() / 1000)\n): Promise<\n | Readonly<{ status: 'review'; review: InboxSetupReview }>\n | Readonly<{ status: 'blocked'; reason: string }>\n> {\n try {\n const capture = identityMessagingOwnership(identity),\n manifest = readRelayPolicy(policy);\n if (\n !capture ||\n !capture.current() ||\n !manifest.messagingEnabled ||\n !manifest.postingEnabled\n )\n return { status: 'blocked', reason: 'unavailable' };\n const previous = base(resolver, policy, capture.owner);\n if (!previous || typeof raw !== 'string' || !boundedUtf8(raw, 65536))\n return { status: 'blocked', reason: 'unavailable' };\n const input: unknown = JSON.parse(raw);\n if (\n !exactLocalFields(input, [\n 'selectedInboxes',\n 'removeTagIndices',\n 'removeExtraFields',\n 'createdAt'\n ]) ||\n !Array.isArray(input.selectedInboxes) ||\n input.selectedInboxes.length < 1 ||\n input.selectedInboxes.length > 3 ||\n !Array.isArray(input.removeTagIndices) ||\n !Array.isArray(input.removeExtraFields)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n const time = safeUnsignedInteger(input.createdAt),\n now = safeUnsignedInteger(observeNow());\n if (\n time === undefined ||\n now !== time ||\n (previous.createdAt !== undefined && time <= previous.createdAt)\n )\n return { status: 'blocked', reason: 'clock_conflict' };\n const selected: string[] = [];\n function appendSelected(value: string) {\n selected.push(value);\n }\n for (const value of input.selectedInboxes as unknown[]) {\n if (\n typeof value !== 'string' ||\n selected.includes(value) ||\n !inboxRelayTargets(policy, [value], 'read').includes(value) ||\n !inboxRelayTargets(policy, [value], 'write').includes(value)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n appendSelected(value);\n }\n const old =\n previous.wire === null\n ? undefined\n : (JSON.parse(previous.wire) as { tags: string[][]; content: string });\n const tags = old?.tags ?? [];\n const removeTags: number[] = [],\n removeFields: string[] = [];\n function appendTagIndex(value: number) {\n removeTags.push(value);\n }\n function appendField(value: string) {\n removeFields.push(value);\n }\n if (\n input.removeTagIndices.length > tags.length ||\n input.removeExtraFields.length > 64\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n for (const index of input.removeTagIndices as unknown[]) {\n if (\n typeof index !== 'number' ||\n safeUnsignedInteger(index) === undefined ||\n index >= tags.length ||\n removeTags.includes(index)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n appendTagIndex(index);\n }\n const standard = [\n 'id',\n 'sig',\n 'pubkey',\n 'kind',\n 'created_at',\n 'tags',\n 'content'\n ];\n const extras: string[] = [];\n function appendExtra(value: string) {\n extras.push(value);\n }\n if (old)\n for (const key in old) if (!standard.includes(key)) appendExtra(key);\n for (const key of input.removeExtraFields as unknown[]) {\n if (\n typeof key !== 'string' ||\n !extras.includes(key) ||\n removeFields.includes(key)\n )\n return { status: 'blocked', reason: 'invalid_selection' };\n appendField(key);\n }\n // Unsigned extra fields cannot survive the existing exact five-field signer.\n // Block until the owner chooses every removal; retaining only the old source\n // would not constitute preservation in the outgoing replacement.\n if (extras.some((key) => !removeFields.includes(key)))\n return { status: 'blocked', reason: 'unsupported_extra_fields' };\n let nextTags = tags.filter((_tag, index) => !removeTags.includes(index));\n for (const origin of selected)\n if (\n !nextTags.some(\n (tag) => tag.length === 2 && tag[0] === 'relay' && tag[1] === origin\n )\n )\n nextTags = nextTags.concat([['relay', origin]]);\n // Reuse the public preference grammar without signing a synthetic event:\n // every retained relay tag must remain a canonical advertised origin. Other\n // tags/content/order/duplicates survive unchanged, including >3 advertisements.\n if (\n nextTags.some(\n (tag) =>\n tag[0] === 'relay' &&\n (tag.length !== 2 || !canonicalRelayOrigin(tag[1]))\n )\n )\n return { status: 'blocked', reason: 'unsupported_profile' };\n const wire = JSON.stringify({\n pubkey: capture.owner,\n kind: 10050,\n created_at: time,\n tags: nextTags,\n content: old?.content ?? ''\n });\n const template = inspectLocalTemplate(wire, capture.owner, 10050),\n destinations = publicRelayTargets(policy, 'write');\n if (!template || destinations.length === 0)\n return { status: 'blocked', reason: 'unsupported_profile' };\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(manifest))\n );\n const policyFingerprint = Array.from(new Uint8Array(digest), (value) =>\n value.toString(16).padStart(2, '0')\n ).join('');\n if (!capture.current() || !inboxResolverCurrentAfterSample(resolver))\n return { status: 'blocked', reason: 'unavailable' };\n const preview: Preview = {\n author: capture.owner,\n originalWire: previous.wire,\n baseId: previous.id,\n wire,\n hash: template.hash,\n policyFingerprint,\n selectedInboxes: selected,\n destinations: destinations.slice(),\n removedTagIndices: removeTags,\n removedExtraFields: removeFields,\n globalEffect\n };\n const review = Object.freeze({}) as InboxSetupReview;\n reviews.set(review, {\n identity,\n session: capture.session,\n policy,\n previewWire: JSON.stringify(preview)\n });\n return { status: 'review', review };\n } catch {\n return { status: 'blocked', reason: 'unavailable' };\n }\n}\nexport function inboxSetupPreview(\n review: InboxSetupReview\n): Preview | undefined {\n const saved = reviews.get(review);\n return saved ? (JSON.parse(saved.previewWire) as Preview) : undefined;\n}\nexport type InboxSetupCapture =\n | Readonly<{ status: 'captured'; record: PublicRecordHandle; owner: string }>\n | Readonly<{ status: 'invalid' | 'conflict' | 'unavailable' }>;\n// No effect permission: this exact reviewed record must be durably admitted\n// before later signing/publication. Fresh lookup is bounded knowledge, never CAS.\nexport function captureInboxSetup(\n review: InboxSetupReview,\n resolver: InboxResolver,\n command: unknown,\n consent: unknown\n): InboxSetupCapture {\n try {\n const saved = reviews.get(review),\n id = canonicalLocalId(command);\n if (!saved || !id || consent !== 'reviewed_global_inbox_replacement')\n return { status: 'invalid' };\n const preview = JSON.parse(saved.previewWire) as Preview,\n capture = identityMessagingOwnership(saved.identity);\n if (\n !capture ||\n capture.owner !== preview.author ||\n capture.session !== saved.session\n )\n return { status: 'unavailable' };\n const current = base(resolver, saved.policy, preview.author);\n if (!current) return { status: 'unavailable' };\n if (current.id !== preview.baseId || current.wire !== preview.originalWire)\n return { status: 'conflict' };\n const record = decodePublicRecord(\n JSON.stringify({\n schema: 1,\n family: 'preference_operation',\n owner: preview.author,\n id,\n revision: 0,\n source: { type: 'inbox_head', wire: preview.originalWire },\n consent: 'explicit_review',\n capture: {\n kind: 10050,\n wire: preview.wire,\n hash: preview.hash,\n targets: preview.destinations,\n policyFingerprint: preview.policyFingerprint\n },\n artifact: null,\n receipts: []\n }),\n preview.author,\n id\n );\n if (\n !record.ok ||\n !capture.current() ||\n !inboxResolverCurrentAfterSample(resolver)\n )\n return { status: 'unavailable' };\n return { status: 'captured', record: record.value, owner: preview.author };\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Informational known-base fence only, never a signing or network capability.\n// Exact already-published artifact is an allowed observation on explicit resume;\n// competing/partial observations still block. This is not a global CAS.\nexport function inboxSetupRecordCurrent(\n record: PublicRecordHandle,\n owner: string,\n id: string,\n resolver: InboxResolver,\n policy: RelayPolicy\n): boolean {\n try {\n const row = publicRecordSnapshot(record, owner, id),\n observed = base(resolver, policy, owner);\n if (!row || row.family !== 'preference_operation' || !observed)\n return false;\n const matches =\n observed.wire === row.source.wire ||\n (row.artifact !== null &&\n observed.id === row.artifact.eventId &&\n observed.wire === row.artifact.wire);\n return matches && inboxResolverCurrentAfterSample(resolver);\n } catch {\n return false;\n }\n}\n", 173 sha256: 174 'e7c9861facd0897c2e19ab84370be9d8ac5c27295d4a450e6511c30dd7218323' 175 }, 176 'src/lib/messaging/inbox-setup-operation.ts': { 177 source: 178 "import {\n captureInboxSetup,\n inboxSetupRecordCurrent,\n type InboxSetupReview\n} from './inbox-setup.ts';\nimport type { InboxResolver } from './resolve-inbox.ts';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport {\n identityMessagingOwnership,\n captureIdentityPublicOperation,\n identityPublicOperationOwnership,\n signIdentityPublicOperation,\n stopIdentityPublicOperation,\n recheckIdentityOwner,\n subscribeIdentityInvalidation,\n type IdentitySession,\n type IdentityPublicOperation\n} from '../runtime/identity-session.ts';\nimport {\n runCapturedPublicEffect,\n type PublicEffectLease\n} from '../runtime/effect-ownership.ts';\nimport {\n publicRecordSnapshot,\n decodePublicRecord,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n loadPreferenceOperation,\n commitPublicOperationTransition,\n observePublicOperationTransition,\n publicQuotaOwner,\n type PublicQuotaRepository\n} from '../persistence/quota.ts';\nimport {\n preparePreferenceSigningTransition,\n preparePublicArtifactTransition,\n type PublicOperationTransition\n} from '../persistence/artifact-records.ts';\nimport { getPublicPool } from '../nostr/public-pool.ts';\nimport {\n authorizeStoredInboxPreference,\n preferencePolicyFingerprint\n} from '../nostr/inbox-preference-publication.ts';\nimport {\n publishInboxPreference,\n type PreferencePublicationResult\n} from '../nostr/inbox-preference-publisher.ts';\ndeclare const actionBrand: unique symbol;\nexport type InboxPreferenceAction = Readonly<{ [actionBrand]: true }>;\ntype Lookup = () => Promise<InboxResolver>;\ntype Saved = Readonly<{\n repository: PublicQuotaRepository;\n identity: IdentitySession;\n policy: RelayPolicy;\n original: PublicRecordHandle;\n operation: IdentityPublicOperation;\n id: string;\n actionId: string;\n lookup: Lookup;\n retry: boolean;\n control: AbortController;\n running(): boolean;\n markRunning(): void;\n}>;\nconst actions = new WeakMap<InboxPreferenceAction, Saved>();\ntype Prepared =\n | Readonly<{ status: 'prepared'; action: InboxPreferenceAction }>\n | Readonly<{ status: 'invalid' | 'unavailable' | 'conflict' | 'unknown' }>;\nfunction retain(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n original: PublicRecordHandle,\n id: string,\n lookup: Lookup,\n retry: boolean\n): Prepared {\n const operation = captureIdentityPublicOperation(\n identity,\n original,\n id,\n 'reviewed_captured_operation'\n );\n if (!operation || typeof lookup !== 'function')\n return { status: 'unavailable' };\n let used = false;\n const action = Object.freeze({}) as InboxPreferenceAction;\n actions.set(action, {\n repository,\n identity,\n policy,\n original,\n operation,\n id,\n actionId: crypto.randomUUID(),\n lookup,\n retry,\n control: new AbortController(),\n running: () => used,\n markRunning: () => {\n used = true;\n }\n });\n return { status: 'prepared', action };\n}\n// Original opaque065 review only. This does not auto-run after connect/setup.\nexport async function beginInboxPreferenceOperation(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n review: InboxSetupReview,\n command: unknown,\n lookup: Lookup,\n consent: unknown\n): Promise<Prepared> {\n try {\n const id = canonicalLocalId(command),\n owner = identityMessagingOwnership(identity);\n if (!id || !owner || publicQuotaOwner(repository) !== owner.owner)\n return { status: 'unavailable' };\n const resolver = await lookup(),\n captured = captureInboxSetup(review, resolver, id, consent);\n if (captured.status !== 'captured') return captured;\n if (captured.owner !== owner.owner || !owner.current())\n return { status: 'unavailable' };\n return retain(\n repository,\n identity,\n policy,\n captured.record,\n id,\n lookup,\n false\n );\n } catch {\n return { status: 'unavailable' };\n }\n}\n// Explicit reload review of the actual stored signed operation, with full\n// original capture retained. Unsigned uncertainty cannot become a fresh plan.\nexport async function resumeInboxPreferenceOperation(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n policy: RelayPolicy,\n command: unknown,\n lookup: Lookup,\n consent: unknown\n): Promise<Prepared> {\n try {\n if (consent !== 'reviewed_stored_inbox_preference')\n return { status: 'invalid' };\n const id = canonicalLocalId(command);\n await recheckIdentityOwner(identity);\n const owner = identityMessagingOwnership(identity);\n if (!id || !owner || publicQuotaOwner(repository) !== owner.owner)\n return { status: 'unavailable' };\n const read = await loadPreferenceOperation(repository, id);\n if (!read.ok) return { status: 'unavailable' };\n const row = publicRecordSnapshot(read.value, owner.owner, id);\n if (row?.family !== 'preference_operation') return { status: 'invalid' };\n if (row.revision < 2 || !row.artifact) return { status: 'unknown' };\n const manifest = readRelayPolicy(policy),\n fingerprint = await preferencePolicyFingerprint(policy),\n resolver = await lookup();\n if (\n !manifest.messagingEnabled ||\n !manifest.postingEnabled ||\n row.capture.policyFingerprint !== fingerprint ||\n JSON.stringify(row.capture.targets) !==\n JSON.stringify(publicRelayTargets(policy, 'write')) ||\n !inboxSetupRecordCurrent(read.value, owner.owner, id, resolver, policy) ||\n !owner.current()\n )\n return { status: 'conflict' };\n // Historical original signing wire for lease matching only; never written\n // back, never a reset. The effect runner uses the actual stored artifact.\n const original = decodePublicRecord(\n JSON.stringify({ ...row, revision: 0, artifact: null, receipts: [] }),\n owner.owner,\n id\n );\n return original.ok\n ? retain(repository, identity, policy, original.value, id, lookup, true)\n : { status: 'invalid' };\n } catch {\n return { status: 'unavailable' };\n }\n}\nasync function acknowledged(\n repository: PublicQuotaRepository,\n transition: PublicOperationTransition\n): Promise<boolean> {\n const result = await commitPublicOperationTransition(repository, transition);\n return (\n result.ok &&\n (await observePublicOperationTransition(repository, transition)).state ===\n 'committed'\n );\n}\nasync function knownBase(saved: Saved): Promise<(() => boolean) | undefined> {\n const owner = identityMessagingOwnership(saved.identity);\n const operation = identityPublicOperationOwnership(\n saved.identity,\n saved.operation\n );\n if (!owner || !operation || saved.control.signal.aborted) return undefined;\n const stored = await loadPreferenceOperation(saved.repository, saved.id);\n if (!stored.ok) return undefined;\n const resolver = await saved.lookup();\n const current = () =>\n !saved.control.signal.aborted &&\n operation.current() &&\n owner.current() &&\n inboxSetupRecordCurrent(\n stored.value,\n owner.owner,\n saved.id,\n resolver,\n saved.policy\n );\n return current() ? current : undefined;\n}\nexport async function runInboxPreferenceOperation(\n action: InboxPreferenceAction\n): Promise<PreferencePublicationResult> {\n const saved = actions.get(action);\n if (!saved) return { status: 'invalid' };\n if (saved.running() || saved.control.signal.aborted)\n return { status: 'stopped' };\n saved.markRunning();\n const capture = identityPublicOperationOwnership(\n saved.identity,\n saved.operation\n );\n if (!capture) return { status: 'stopped' };\n const messagingOwner = identityMessagingOwnership(saved.identity);\n if (\n !messagingOwner ||\n messagingOwner.owner !== capture.owner ||\n messagingOwner.session !== capture.session\n )\n return { status: 'stopped' };\n if (!capture.current() || saved.control.signal.aborted)\n return { status: 'stopped' };\n const invalidate = subscribeIdentityInvalidation(saved.identity, () => {\n // Notifications also describe pending/completed observations. Only actual\n // owner/capability/generation loss cancels this original explicit action.\n if (!capture.current() || !messagingOwner.current()) saved.control.abort();\n });\n try {\n const result = await runCapturedPublicEffect<PreferencePublicationResult>(\n saved.repository,\n saved.original,\n saved.id,\n {\n ...capture,\n current: () => capture.current() && !saved.control.signal.aborted\n },\n saved.retry\n ? 'reviewed_stored_preference_retry'\n : 'reviewed_prepared_preference_operation',\n async (lease: PublicEffectLease, claimed: PublicRecordHandle) => {\n if (!(await knownBase(saved))) return { status: 'stopped' };\n const row = publicRecordSnapshot(claimed, capture.owner, saved.id);\n if (row?.family !== 'preference_operation')\n return { status: 'invalid' };\n const manifest = readRelayPolicy(saved.policy);\n if (\n !manifest.messagingEnabled ||\n !manifest.postingEnabled ||\n row.capture.policyFingerprint !==\n (await preferencePolicyFingerprint(saved.policy)) ||\n JSON.stringify(row.capture.targets) !==\n JSON.stringify(publicRelayTargets(saved.policy, 'write'))\n )\n return { status: 'stopped' };\n if (!capture.current() || saved.control.signal.aborted)\n return { status: 'stopped' };\n if (!row.artifact) {\n const marker = preparePreferenceSigningTransition(\n claimed,\n capture.owner,\n saved.id\n );\n if (\n !marker.ok ||\n !(await acknowledged(saved.repository, marker.value))\n )\n return { status: 'storage_failed' };\n if (!(await knownBase(saved))) return { status: 'stopped' };\n const signed = await signIdentityPublicOperation(\n saved.identity,\n saved.operation,\n lease\n );\n if (signed.status !== 'signed') return { status: 'stopped' };\n const pending = await loadPreferenceOperation(\n saved.repository,\n saved.id\n );\n if (!pending.ok) return { status: 'storage_failed' };\n if (!capture.current() || saved.control.signal.aborted)\n return { status: 'stopped' };\n const transition = preparePublicArtifactTransition(\n pending.value,\n capture.owner,\n saved.id,\n signed.artifact\n );\n if (\n !transition.ok ||\n !(await acknowledged(saved.repository, transition.value))\n )\n return { status: 'storage_failed' };\n }\n if (saved.control.signal.aborted || !capture.current())\n return { status: 'stopped' };\n const pool = getPublicPool(saved.policy);\n if (!pool) return { status: 'stopped' };\n return await publishInboxPreference(\n saved.repository,\n capture.owner,\n saved.id,\n saved.actionId,\n pool,\n saved.policy,\n saved.control.signal,\n () =>\n authorizeStoredInboxPreference(\n saved.repository,\n saved.identity,\n saved.operation,\n lease,\n saved.original,\n saved.id,\n saved.policy,\n () => knownBase(saved)\n )\n );\n }\n );\n return result.status === 'completed' ? result.value : { status: 'stopped' };\n } catch {\n return { status: 'stopped' };\n } finally {\n invalidate();\n }\n}\nexport function stopInboxPreferenceOperation(\n action: InboxPreferenceAction\n): void {\n const saved = actions.get(action);\n if (!saved) return;\n saved.control.abort();\n stopIdentityPublicOperation(saved.identity, saved.operation);\n}\n", 179 sha256: 180 'f9deefbd5c58234c720fd2196edf1d242ee16fcdf4e32082c0456662fbe15122' 181 }, 182 'src/lib/messaging/inbox-setup-view.ts': { 183 source: 184 "import {\n readRelayPolicy,\n inboxRelayTargets,\n type RelayPolicy\n} from '../config/relays.ts';\nimport { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport {\n identityMessagingOwnership,\n subscribeIdentityInvalidation,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n createPrivateSession,\n closePrivateSession,\n type PrivateSession\n} from '../runtime/private-session.ts';\nimport {\n identityViewSession,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n resolveInboxPreference,\n settleInboxResolver,\n inboxResolutionSnapshot,\n closeInboxResolver,\n type InboxResolver\n} from './resolve-inbox.ts';\nimport {\n inboxPreferenceSnapshot,\n inboxPreferenceWire\n} from '../nostr/inbox-preferences.ts';\nimport {\n reviewInboxSetup,\n inboxSetupPreview,\n type InboxSetupReview\n} from './inbox-setup.ts';\nimport {\n beginInboxPreferenceOperation,\n runInboxPreferenceOperation,\n stopInboxPreferenceOperation,\n type InboxPreferenceAction\n} from './inbox-setup-operation.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicQuotaRepository,\n loadPreferenceOperation,\n type PublicQuotaRepository\n} from '../persistence/quota.ts';\nimport {\n publicRecordSnapshot,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n resolveInboxReadback,\n inboxReadbackSnapshot,\n closeInboxReadback,\n type InboxReadback\n} from '../nostr/inbox-readback.ts';\nimport {\n existingInboxSetupSnapshot,\n verifyInboxSetupOperation\n} from './inbox-setup-verification.ts';\nimport type { ObserveInboxAccess } from './readiness.ts';\ndeclare const viewBrand: unique symbol;\nexport type InboxSetupView = Readonly<{ [viewBrand]: true }>;\nexport type InboxSetupViewSnapshot = Readonly<{\n status: string;\n busy: boolean;\n owner?: string;\n currentWire: string | null;\n existingInboxes: string[];\n availableInboxes: string[];\n preview?: NonNullable<ReturnType<typeof inboxSetupPreview>>;\n accepted: string[];\n readback: string[];\n setupComplete: boolean;\n}>;\n// Internal trusted orchestration ports require real opaque discovery/readback\n// owners. Neither displayed facts nor caller booleans admit a preference effect.\ntype Inputs = Readonly<{\n identity: IdentitySession;\n policy: RelayPolicy;\n lookup(current?: () => boolean): Promise<InboxResolver>;\n readback?(\n record: PublicRecordHandle,\n owner: string,\n id: string\n ): InboxReadback | undefined;\n observeAccess?: ObserveInboxAccess;\n now?(): number;\n close?(): void;\n}>;\ntype Controller = {\n ownership():\n | Readonly<{\n identity: IdentitySession;\n policy: RelayPolicy;\n session: PrivateSession | undefined;\n resolver: InboxResolver | undefined;\n observeAccess: ObserveInboxAccess | undefined;\n current(): boolean;\n }>\n | undefined;\n observe(): void;\n snapshot(): InboxSetupViewSnapshot;\n subscribe(listener: (state: InboxSetupViewSnapshot) => void): () => void;\n check(): Promise<void>;\n review(\n selected: string[],\n removeTags: number[],\n removeFields: string[]\n ): Promise<void>;\n enable(): Promise<void>;\n unlock(): Promise<void>;\n readback(): Promise<void>;\n stop(): void;\n close(): void;\n};\nconst views = new WeakMap<InboxSetupView, Controller>();\nconst unavailable = (): InboxSetupViewSnapshot => ({\n status: 'unavailable',\n busy: false,\n currentWire: null,\n existingInboxes: [],\n availableInboxes: [],\n accepted: [],\n readback: [],\n setupComplete: false\n});\nexport function createInboxSetupView(\n input: Inputs\n): InboxSetupView | undefined {\n if (typeof window === 'undefined') return undefined;\n const initial = identityMessagingOwnership(input.identity);\n if (!initial || !initial.current()) return undefined;\n const capture = initial;\n const manifest = readRelayPolicy(input.policy);\n const available = manifest.inbox\n .filter(\n ({ read, write, origin }) =>\n read && write && !manifest.operatorDenylist.includes(origin)\n )\n .map((row) => row.origin);\n const token = Object.freeze({}) as InboxSetupView;\n let state = {\n ...unavailable(),\n status: 'not_checked',\n owner: capture.owner,\n availableInboxes: available\n },\n epoch = 0,\n closed = false;\n let pendingClose: (() => void)[] | undefined;\n let resolver: InboxResolver | undefined,\n review: InboxSetupReview | undefined,\n action: InboxPreferenceAction | undefined,\n database: BrowserDatabase | undefined,\n repository: PublicQuotaRepository | undefined,\n session: PrivateSession | undefined,\n reader: InboxReadback | undefined,\n command: string | undefined;\n const listeners = new Map<symbol, (state: InboxSetupViewSnapshot) => void>();\n const current = (generation = epoch) =>\n !closed && generation === epoch && capture.current();\n const snapshot = () => {\n if (closed) return { ...unavailable(), status: 'closed' };\n if (!capture.current()) return unavailable();\n return JSON.parse(JSON.stringify(state)) as InboxSetupViewSnapshot;\n };\n function notify() {\n for (const listener of listeners.values()) {\n try {\n listener(snapshot());\n } catch {\n /* Isolate presentation observers. */\n }\n }\n }\n function update(status: string, busy = state.busy) {\n state = { ...state, status, busy };\n notify();\n }\n function inspect() {\n if (!resolver || !current()) return;\n const observed = inboxResolutionSnapshot(resolver);\n if (!current() || observed.author !== capture.owner) return;\n const head = observed.head && inboxPreferenceSnapshot(observed.head);\n state = {\n ...state,\n currentWire: observed.head\n ? (inboxPreferenceWire(observed.head) ?? null)\n : null,\n existingInboxes: head?.relays.slice() ?? [],\n setupComplete: false\n };\n if (\n observed.coverage !== 'bounded-eose' ||\n observed.status === 'inconclusive'\n ) {\n update('lookup_incomplete');\n return;\n }\n const compatible =\n head?.status === 'supported' &&\n inboxRelayTargets(input.policy, head.relays, 'read').length > 0 &&\n inboxRelayTargets(input.policy, head.relays, 'write').length > 0;\n update(\n compatible\n ? 'compatible'\n : observed.status === 'missing'\n ? 'not_observed'\n : 'needs_review'\n );\n }\n async function work(\n status: string,\n perform: (generation: number) => Promise<void>\n ) {\n if (!current() || state.busy) return;\n const generation = epoch;\n update(status, true);\n if (!current(generation)) return;\n try {\n await perform(generation);\n } catch {\n if (current(generation)) update('unavailable');\n } finally {\n if (current(generation)) {\n state = { ...state, busy: false };\n notify();\n }\n }\n }\n function stop() {\n epoch++;\n if (action) stopInboxPreferenceOperation(action);\n review = undefined;\n state = { ...state, preview: undefined, setupComplete: false };\n if (reader) closeInboxReadback(reader);\n reader = undefined;\n if (resolver) closeInboxResolver(resolver);\n resolver = undefined;\n update('paused', false);\n }\n const invalidate = subscribeIdentityInvalidation(input.identity, () => {\n if (!capture.current()) stop();\n });\n views.set(token, {\n ownership: () =>\n current()\n ? {\n identity: input.identity,\n policy: input.policy,\n session,\n resolver,\n observeAccess: input.observeAccess,\n current: () => current()\n }\n : undefined,\n observe() {\n if (current() && !state.busy && state.status === 'lookup_incomplete')\n inspect();\n },\n snapshot,\n subscribe(listener) {\n const id = Symbol();\n listeners.set(id, listener);\n try {\n listener(snapshot());\n } catch {\n /* Isolate presentation observers. */\n }\n return () => {\n listeners.delete(id);\n };\n },\n check: () =>\n work('checking', async (generation) => {\n if (resolver) closeInboxResolver(resolver);\n const found = await input.lookup(() => current(generation));\n if (!current(generation)) {\n closeInboxResolver(found);\n return;\n }\n resolver = found;\n review = undefined;\n state = { ...state, preview: undefined };\n inspect();\n }),\n review: (selected, removeTags, removeFields) =>\n work('reviewing', async (generation) => {\n if (!resolver) {\n update('lookup_incomplete');\n return;\n }\n inspect();\n if (!current(generation) || state.status === 'compatible') return;\n const result = await reviewInboxSetup(\n input.identity,\n resolver,\n input.policy,\n JSON.stringify({\n selectedInboxes: selected,\n removeTagIndices: removeTags,\n removeExtraFields: removeFields,\n createdAt: (input.now ?? (() => Math.floor(Date.now() / 1000)))()\n }),\n input.now\n );\n if (!current(generation)) return;\n if (result.status !== 'review') {\n update(result.reason);\n return;\n }\n review = result.review;\n state = { ...state, preview: inboxSetupPreview(review) };\n update('review');\n }),\n enable: () =>\n work('approval_wait', async (generation) => {\n if (\n !review ||\n state.preview === undefined ||\n !manifest.postingEnabled ||\n !manifest.messagingEnabled\n ) {\n update('unavailable');\n return;\n }\n const opened = await openBrowserDatabase();\n if (!current(generation)) {\n if (opened.state === 'ready') closeBrowserDatabase(opened.owner);\n return;\n }\n if (opened.state !== 'ready') {\n update('storage_unavailable');\n return;\n }\n if (database) closeBrowserDatabase(database);\n database = opened.owner;\n repository = createPublicQuotaRepository(database, capture.owner);\n if (!repository) {\n update('storage_unavailable');\n return;\n }\n command = crypto.randomUUID();\n const prepared = await beginInboxPreferenceOperation(\n repository,\n input.identity,\n input.policy,\n review,\n command,\n () => input.lookup(() => current(generation)),\n 'reviewed_global_inbox_replacement'\n );\n if (!current(generation)) {\n if (prepared.status === 'prepared')\n stopInboxPreferenceOperation(prepared.action);\n return;\n }\n if (prepared.status !== 'prepared') {\n update(prepared.status);\n return;\n }\n action = prepared.action;\n const result = await runInboxPreferenceOperation(action);\n if (!current(generation)) return;\n const stored = await loadPreferenceOperation(repository, command);\n if (!current(generation)) return;\n const row =\n stored.ok &&\n publicRecordSnapshot(stored.value, capture.owner, command);\n state = {\n ...state,\n accepted:\n row && row.family === 'preference_operation'\n ? row.receipts\n .filter(\n (fact) =>\n fact.status === 'accepted' &&\n fact.eventId === row.artifact?.eventId\n )\n .map((fact) => fact.origin)\n : [],\n setupComplete: false\n };\n review = undefined;\n state = { ...state, preview: undefined };\n update(\n result.status === 'completed' ? 'awaiting_readback' : result.status\n );\n }),\n unlock: () =>\n work('approval_wait', async (generation) => {\n const acquired = await createPrivateSession(\n input.identity,\n 'reviewed_private_session'\n );\n if (!current(generation)) {\n if (acquired) closePrivateSession(acquired);\n return;\n }\n session = acquired;\n if (!session || !resolver) {\n update('unavailable');\n return;\n }\n const result = existingInboxSetupSnapshot(\n input.identity,\n session,\n input.policy,\n resolver,\n input.observeAccess\n );\n if (!current(generation)) return;\n state = { ...state, setupComplete: result.setupComplete };\n update(result.status);\n }),\n readback: () =>\n work('checking_readback', async (generation) => {\n if (!repository || !command || !input.readback) {\n update('awaiting_readback');\n return;\n }\n if (!reader) {\n const stored = await loadPreferenceOperation(repository, command);\n if (!current(generation)) return;\n if (!stored.ok) {\n update('storage_unavailable');\n return;\n }\n reader = input.readback(stored.value, capture.owner, command);\n }\n const observation = reader && inboxReadbackSnapshot(reader);\n if (!observation || observation.status === 'pending') {\n update('awaiting_readback');\n return;\n }\n state = { ...state, readback: observation.sources.slice() };\n const result = await verifyInboxSetupOperation(\n repository,\n input.identity,\n session,\n input.policy,\n reader!,\n input.observeAccess\n );\n if (!current(generation)) return;\n state = { ...state, setupComplete: result.setupComplete };\n closeInboxReadback(reader!);\n reader = undefined;\n update(result.status);\n }),\n stop,\n close() {\n if (!pendingClose) {\n closed = true;\n const originalResolver = resolver,\n originalReader = reader,\n originalSession = session,\n originalDatabase = database;\n pendingClose = [\n stop,\n invalidate,\n () => {\n if (originalReader) closeInboxReadback(originalReader);\n },\n () => {\n if (originalResolver) closeInboxResolver(originalResolver);\n },\n () => {\n if (originalSession && !closePrivateSession(originalSession))\n throw Error('private_cleanup_required');\n },\n () => {\n if (originalDatabase) closeBrowserDatabase(originalDatabase);\n },\n () => input.close?.(),\n () => listeners.clear()\n ];\n }\n let unfinished = Array.from<() => void>([]);\n for (const cleanup of pendingClose) {\n try {\n cleanup();\n } catch {\n unfinished = unfinished.concat(cleanup);\n }\n }\n pendingClose = unfinished;\n // Closed admission and completed disposal are separate facts. A failed\n // original cleanup remains owned and retryable after invalidation.\n if (unfinished.length > 0) throw Error('inbox_setup_cleanup_required');\n }\n });\n return token;\n}\n// Production egress always comes from the root's governed runtime and fixed\n// deployment manifest. No fixture, arbitrary relay, signing template or sender.\nexport function createRuntimeInboxSetupView(\n context: IdentityViewContext,\n runtime: PublicRuntime\n): InboxSetupView | undefined {\n const identity = identityViewSession(context);\n if (!identity) return undefined;\n const view = createPublicView(runtime);\n try {\n const controller = createInboxSetupView({\n identity,\n policy: deploymentRelayPolicy,\n lookup: (current = () => true) => {\n const owner = identityMessagingOwnership(identity);\n if (!owner) throw new Error('inbox_owner_unavailable');\n return settleInboxResolver(\n resolveInboxPreference(view, beginPublicViewRun(view), owner.owner),\n () => owner.current() && current()\n );\n },\n readback: (record, owner, id) =>\n resolveInboxReadback(\n view,\n beginPublicViewRun(view),\n record,\n owner,\n id,\n deploymentRelayPolicy\n ),\n close: () => disposePublicView(view)\n });\n if (!controller) disposePublicView(view);\n return controller;\n } catch {\n disposePublicView(view);\n return undefined;\n }\n}\nexport function inboxSetupViewSnapshot(\n view: InboxSetupView | undefined\n): InboxSetupViewSnapshot {\n return (view && views.get(view)?.snapshot()) || unavailable();\n}\nexport function subscribeInboxSetupView(\n view: InboxSetupView | undefined,\n listener: (state: InboxSetupViewSnapshot) => void\n): () => void {\n return (view && views.get(view)?.subscribe(listener)) || (() => {});\n}\nexport async function checkInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.check());\n}\nexport async function reviewInboxSetupView(\n view: InboxSetupView | undefined,\n selected: string[],\n removeTags: number[],\n removeFields: string[]\n): Promise<void> {\n await (view && views.get(view)?.review(selected, removeTags, removeFields));\n}\nexport async function enableInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.enable());\n}\nexport async function unlockInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.unlock());\n}\nexport async function readbackInboxSetupView(\n view: InboxSetupView | undefined\n): Promise<void> {\n await (view && views.get(view)?.readback());\n}\nexport function stopInboxSetupView(view: InboxSetupView | undefined): void {\n if (view) views.get(view)?.stop();\n}\nexport function closeInboxSetupView(view: InboxSetupView | undefined): void {\n if (view) views.get(view)?.close();\n}\n\n// Detached original-token observation for trusted page orchestration. Neither\n// its scalar fields nor mutation of this fresh object changes stored custody.\nexport function inboxSetupViewOwnership(view: InboxSetupView | undefined) {\n return view && views.get(view)?.ownership();\n}\nexport function observeInboxSetupView(view: InboxSetupView | undefined): void {\n if (view) views.get(view)?.observe();\n}\n", 185 sha256: 186 '4ec9025232bb1355fef1ba039b46ce0a2be10e02e348e1b4eaadc3d1f3c2fd84' 187 }, 188 'src/lib/messaging/reply-controller.ts': { 189 source: 190 "import { inboxReplyOwnership, type InboxView } from './inbox-view.ts';\nimport { inboxSetupViewOwnership } from './inbox-setup-view.ts';\nimport { messagingReadinessSnapshot } from './readiness.ts';\nimport {\n createInboxRoutePlan,\n inboxRoutePlanSnapshot\n} from './inbox-routing.ts';\nimport {\n resolveInboxPreference,\n closeInboxResolver,\n type InboxResolver\n} from './resolve-inbox.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n publicViewRunCurrent,\n disposePublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n createPrivateComposer,\n privateComposerText,\n privateComposerSnapshot,\n updatePrivateComposerText,\n bindPrivateComposerPreparation,\n closePrivateComposer\n} from './composer-state.ts';\nimport {\n captureDirtyNavigation,\n requestPrivateNavigation,\n confirmDiscardNavigation,\n keepPrivateEditing,\n dirtyNavigationSnapshot,\n privateNavigationBeforeUnload\n} from '../runtime/dirty-navigation.ts';\nimport {\n captureAuthenticatedReplyRumor,\n stopRumorPlan,\n type RumorPlan\n} from './rumor-plan.ts';\nimport { createPrivateSendReservationRepository } from '../persistence/private-send-reservations.ts';\nimport { reserveSendIdentity } from './send-identity.ts';\nimport {\n captureSelfRecoveryPreparation,\n prepareSelfRecovery,\n preparedSelfRecovery,\n preparePairedDelivery,\n preparedPairedDelivery,\n selfRecoveryPreparationSnapshot,\n type SelfRecoveryPreparation\n} from './prepare-send.ts';\nimport { getPrivatePool } from '../nostr/private-pool.ts';\nimport {\n capturePrivateRetry,\n runPrivateRetry,\n stopPrivateRetry,\n type PrivateRetry\n} from './retry-send.ts';\nimport { newLocalId } from '../private-handles.ts';\nimport { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';\nimport { subscribePrivateSessionClose } from '../runtime/private-session.ts';\n\ndeclare const replyBrand: unique symbol;\nexport type ReplyController = Readonly<{ [replyBrand]: true }>;\ntype Result = Readonly<{\n status: 'invalid' | 'busy' | 'stopped' | 'needs_action' | 'completed';\n}>;\ntype Options = Readonly<{\n lookupPeer?(peer: string): Promise<InboxResolver>;\n close?(): void;\n}>;\ntype State =\n | 'idle'\n | 'checking'\n | 'preparing'\n | 'publishing'\n | 'needs_action'\n | 'completed';\ntype Snapshot = Readonly<{\n state: State;\n busy: boolean;\n dirty: boolean;\n copy: string;\n saveCopy: string;\n pairCopy: string;\n navigation: 'idle' | 'confirmation_required';\n}>;\ntype Controller = {\n snapshot(): Snapshot | undefined;\n text(): string | undefined;\n update(text: unknown, review: unknown): boolean;\n select(parent: unknown, review: unknown): boolean;\n send(review: unknown): Promise<Result>;\n request(): ReturnType<typeof requestPrivateNavigation>;\n keep(): boolean;\n discard(review: unknown): ReturnType<typeof confirmDiscardNavigation>;\n unload(event: BeforeUnloadEvent): boolean;\n close(): void;\n};\nconst controllers = new WeakMap<ReplyController, Controller>();\n\n// Allocating or typing a draft performs no SDK, native write or discovery.\n// Caller hints are resolved through the original selected view's Room/cache.\nexport function createReplyController(\n view: InboxView,\n conversationId: unknown,\n parent: unknown,\n options: Options = {}\n): ReplyController | undefined {\n if (typeof window === 'undefined') return;\n let scope = inboxReplyOwnership(view, conversationId, parent);\n if (!scope?.current()) return;\n const original = scope,\n composer = createPrivateComposer(\n original.identity,\n 'reviewed_private_composer'\n );\n const navigation = composer && captureDirtyNavigation(composer);\n if (!composer || !navigation) {\n if (composer) closePrivateComposer(composer);\n return;\n }\n let active = true,\n busy = false,\n state: State = 'idle',\n copy = '',\n attempted = false;\n let plan: RumorPlan | undefined,\n preparation: SelfRecoveryPreparation | undefined,\n retry: PrivateRetry | undefined;\n let identityOff = () => {},\n privateOff = () => {};\n function close() {\n if (!active) return;\n active = false;\n if (retry) stopPrivateRetry(retry);\n closePrivateComposer(composer!);\n if (plan) stopRumorPlan(plan);\n identityOff();\n privateOff();\n options.close?.();\n }\n function current() {\n if (!active || !scope?.current() || !privateComposerSnapshot(composer!)) {\n close();\n return false;\n }\n return true;\n }\n function snapshot(): Snapshot | undefined {\n if (!current()) return;\n const draft = privateComposerSnapshot(composer!),\n workflow = preparation && selfRecoveryPreparationSnapshot(preparation);\n if (!draft) return;\n return {\n state,\n busy,\n dirty: draft.dirty,\n copy:\n copy ||\n (state === 'preparing'\n ? 'Preparing encryption. The extension may ask for several approvals.'\n : state === 'publishing'\n ? 'Publishing encrypted copies to the reviewed inbox relays.'\n : ''),\n saveCopy: draft.copy,\n pairCopy: workflow?.pairCopy ?? draft.pairCopy,\n navigation: dirtyNavigationSnapshot(navigation!)?.state ?? 'idle'\n };\n }\n async function send(review: unknown): Promise<Result> {\n if (review !== 'reviewed_reply_send') return { status: 'invalid' };\n if (!current()) return { status: 'stopped' };\n if (busy) return { status: 'busy' };\n const text = privateComposerText(composer!);\n if (!text?.trim()) return { status: 'invalid' };\n if (attempted) return { status: 'needs_action' };\n busy = true;\n state = 'checking';\n copy =\n 'Checking the authenticated peer inbox. Your text remains in memory.';\n const captured = scope!;\n const admitted = () => current() && scope === captured;\n function needsAction(): Result {\n state = 'needs_action';\n copy =\n 'Send needs review. Keep this draft; check inbox setup or connection, then explicitly send again. Existing encrypted work needs its own recovery review.';\n return { status: 'needs_action' };\n }\n try {\n const setup = inboxSetupViewOwnership(captured.setup);\n if (!setup?.current() || !setup.resolver || !options.lookupPeer)\n return needsAction();\n const other = await options.lookupPeer(captured.peer);\n if (!admitted()) return { status: 'stopped' };\n if (\n !messagingReadinessSnapshot(\n captured.identity,\n captured.session,\n setup.policy,\n setup.resolver,\n { author: captured.peer, resolver: other },\n setup.observeAccess\n ).sendReady ||\n !admitted()\n )\n return needsAction();\n const routes = createInboxRoutePlan(\n setup.policy,\n captured.owner,\n captured.peer,\n setup.resolver,\n other\n );\n const routeData = routes && inboxRoutePlanSnapshot(routes);\n const reservations = createPrivateSendReservationRepository(\n captured.database,\n captured.owner\n );\n if (!routes || !routeData || !reservations || !admitted())\n return needsAction();\n plan = captureAuthenticatedReplyRumor(\n captured.identity,\n captured.session,\n captured.unlocked,\n captured.room,\n text,\n Math.floor(Date.now() / 1000)\n );\n const command = newLocalId();\n if (!plan || !command || !admitted()) return needsAction();\n // After a native intent may exist, repeated Send never creates another\n // rumor or silently replays this command. Recovery has its own owner.\n attempted = true;\n const reserved = await reserveSendIdentity(\n reservations,\n captured.identity,\n command,\n plan,\n 'reviewed_private_intent'\n );\n if (!admitted()) return { status: 'stopped' };\n if (!('identity' in reserved)) return needsAction();\n preparation = captureSelfRecoveryPreparation(\n captured.repository,\n captured.identity,\n reserved.identity,\n 'reviewed_self_recovery'\n );\n if (\n !preparation ||\n !bindPrivateComposerPreparation(\n composer!,\n reserved.identity,\n preparation,\n undefined,\n 'reviewed_composer_preparation'\n )\n )\n return needsAction();\n state = 'preparing';\n copy = '';\n const self = await prepareSelfRecovery(\n preparation,\n 'reviewed_self_recovery'\n );\n if (!admitted()) return { status: 'stopped' };\n const saved = preparedSelfRecovery(preparation);\n if (\n !['saved', 'existing', 'reconciled'].includes(self.status) ||\n !saved ||\n !(await captured.acceptLocalReply(saved, 'reviewed_local_reply')) ||\n !admitted()\n )\n return needsAction();\n const context = {\n plan: routes,\n policy: setup.policy,\n own: setup.resolver,\n other\n };\n const paired = await preparePairedDelivery(\n preparation,\n context,\n 'reviewed_pair_preparation'\n );\n if (!admitted()) return { status: 'stopped' };\n const receipt = preparedPairedDelivery(preparation);\n if (\n !['prepared', 'existing', 'reconciled'].includes(paired.status) ||\n !receipt\n )\n return needsAction();\n const origins = Array.from(\n new Set([...routeData.peer.targets, ...routeData.archive.targets])\n );\n const pool = getPrivatePool(captured.session, setup.policy, origins);\n if (!pool || !admitted()) return needsAction();\n retry = capturePrivateRetry(\n captured.repository,\n captured.session,\n receipt,\n context,\n pool,\n 'reviewed_private_retry'\n );\n if (!retry || !admitted()) return needsAction();\n state = 'publishing';\n const delivered = await runPrivateRetry(retry, 'reviewed_private_retry');\n if (!admitted()) return { status: 'stopped' };\n if (delivered.status !== 'completed') return needsAction();\n state = 'completed';\n copy =\n 'Accepted by recipient inbox relay. This does not confirm that the person read the message.';\n return { status: 'completed' };\n } catch {\n return current() ? needsAction() : { status: 'stopped' };\n } finally {\n busy = false;\n }\n }\n const token = Object.freeze({}) as ReplyController;\n controllers.set(token, {\n snapshot,\n text: () => (current() ? privateComposerText(composer) : undefined),\n update: (text, review) =>\n current() &&\n !busy &&\n !attempted &&\n updatePrivateComposerText(composer, text, review),\n select(parent, review) {\n if (review !== 'reviewed_reply_parent' || !current() || busy || attempted)\n return false;\n const selected = inboxReplyOwnership(view, conversationId, parent);\n if (\n !selected?.current() ||\n selected.identity !== original.identity ||\n selected.session !== original.session ||\n selected.peer !== original.peer\n )\n return false;\n scope = selected;\n return true;\n },\n send,\n request: () =>\n current() ? requestPrivateNavigation(navigation) : 'invalid',\n keep: () => current() && keepPrivateEditing(navigation),\n discard: (review) =>\n current() ? confirmDiscardNavigation(navigation, review) : 'invalid',\n unload: (event) =>\n current() && privateNavigationBeforeUnload(navigation, event),\n close\n });\n identityOff = subscribeIdentityInvalidation(original.identity, () => {\n if (!original.current()) close();\n });\n privateOff = subscribePrivateSessionClose(original.session, close);\n return current() ? token : undefined;\n}\n\nexport function createRuntimeReplyController(\n view: InboxView,\n id: unknown,\n parent: unknown,\n runtime: PublicRuntime\n): ReplyController | undefined {\n const publicView = createPublicView(runtime);\n let resolver: InboxResolver | undefined,\n run: ReturnType<typeof beginPublicViewRun> | undefined;\n const token = createReplyController(view, id, parent, {\n lookupPeer: (peer) => {\n // Only this explicit Send lookup may renew an expired run. An active\n // lookup retains its original bounded work, including pending results.\n if (!resolver || !run || !publicViewRunCurrent(publicView, run)) {\n if (resolver) closeInboxResolver(resolver);\n resolver = undefined;\n run = beginPublicViewRun(publicView);\n resolver = resolveInboxPreference(publicView, run, peer);\n }\n return Promise.resolve(resolver);\n },\n close: () => {\n if (resolver) closeInboxResolver(resolver);\n disposePublicView(publicView);\n }\n });\n if (!token) disposePublicView(publicView);\n return token;\n}\nexport function replySnapshot(token: ReplyController) {\n return controllers.get(token)?.snapshot();\n}\nexport function replyText(token: ReplyController) {\n return controllers.get(token)?.text();\n}\nexport function updateReplyText(\n token: ReplyController,\n text: unknown,\n review: unknown\n) {\n return controllers.get(token)?.update(text, review) ?? false;\n}\nexport function selectReplyParent(\n token: ReplyController,\n parent: unknown,\n review: unknown\n) {\n return controllers.get(token)?.select(parent, review) ?? false;\n}\nexport function sendReply(\n token: ReplyController,\n review: unknown\n): Promise<Result> {\n return (\n controllers.get(token)?.send(review) ??\n Promise.resolve({ status: 'invalid' })\n );\n}\nexport function requestReplyNavigation(token: ReplyController) {\n return controllers.get(token)?.request() ?? 'invalid';\n}\nexport function keepReplyEditing(token: ReplyController) {\n return controllers.get(token)?.keep() ?? false;\n}\nexport function discardReplyNavigation(\n token: ReplyController,\n review: unknown\n) {\n return controllers.get(token)?.discard(review) ?? 'invalid';\n}\nexport function replyBeforeUnload(\n token: ReplyController,\n event: BeforeUnloadEvent\n) {\n return controllers.get(token)?.unload(event) ?? false;\n}\nexport function closeReplyController(token: ReplyController) {\n controllers.get(token)?.close();\n}\n", 191 sha256: 192 'c13f1395b5317febcd23396babbcc116065ff96e8cbeb29c8eadfdfc14e45c2d' 193 }, 194 'src/lib/messaging/product-request-controller.ts': { 195 source: 196 "import {\n productEnquirySnapshot,\n productEnquirySendOwnership,\n updateProductEnquiry,\n closeProductEnquiry,\n type ProductEnquiry\n} from './product-enquiry.ts';\nimport {\n identityMessagingOwnership,\n subscribeIdentityInvalidation,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n inboxSetupViewOwnership,\n type InboxSetupView\n} from './inbox-setup-view.ts';\nimport { messagingReadinessSnapshot } from './readiness.ts';\nimport {\n sellerInboxStatus,\n sellerInboxCopy,\n type SellerInboxStatus\n} from './enquiry-readiness.ts';\nimport {\n createInboxRoutePlan,\n inboxRoutePlanSnapshot\n} from './inbox-routing.ts';\nimport {\n resolveInboxPreference,\n settleInboxResolver,\n closeInboxResolver,\n type InboxResolver\n} from './resolve-inbox.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport { createPrivateStorageRepository } from '../persistence/private-storage.ts';\nimport { createPrivateSendReservationRepository } from '../persistence/private-send-reservations.ts';\nimport {\n createPrivateComposer,\n updatePrivateComposerText,\n privateComposerSnapshot,\n bindPrivateComposerPreparation,\n closePrivateComposer,\n type PrivateComposer\n} from './composer-state.ts';\nimport {\n captureEnquiryRumor,\n stopRumorPlan,\n type RumorPlan\n} from './rumor-plan.ts';\nimport { reserveSendIdentity } from './send-identity.ts';\nimport {\n captureSelfRecoveryPreparation,\n prepareSelfRecovery,\n preparedSelfRecovery,\n preparePairedDelivery,\n preparedPairedDelivery,\n selfRecoveryPreparationSnapshot,\n type SelfRecoveryPreparation\n} from './prepare-send.ts';\nimport { getPrivatePool } from '../nostr/private-pool.ts';\nimport {\n capturePrivateRetry,\n runPrivateRetry,\n stopPrivateRetry,\n type PrivateRetry\n} from './retry-send.ts';\nimport { newLocalId } from '../private-handles.ts';\nimport { privateSessionOwnership } from '../runtime/private-session.ts';\n\ndeclare const requestBrand: unique symbol;\nexport type ProductRequestController = Readonly<{ [requestBrand]: true }>;\ntype Result = Readonly<{\n status: 'invalid' | 'busy' | 'stopped' | 'needs_action' | 'completed';\n}>;\ntype NavigationResult =\n 'invalid' | 'allowed' | 'confirmation_required' | 'review_required';\ntype State =\n | 'idle'\n | 'checking'\n | 'preparing'\n | 'publishing'\n | 'needs_action'\n | 'completed';\ntype Snapshot = Readonly<{\n state: State;\n busy: boolean;\n dirty: boolean;\n revision: number;\n readyToSend: boolean;\n sellerInbox: SellerInboxStatus;\n copy: string;\n saveCopy: string;\n pairCopy: string;\n navigation: 'idle' | 'confirmation_required';\n}>;\ntype Controller = {\n snapshot(): Snapshot | undefined;\n text(): string | undefined;\n update(text: unknown, review: unknown): boolean;\n configure(\n identity: IdentitySession,\n setup: InboxSetupView,\n review: unknown\n ): boolean;\n send(review: unknown): Promise<Result>;\n request(): NavigationResult;\n keep(): boolean;\n discard(review: unknown): NavigationResult;\n unload(event: BeforeUnloadEvent): boolean;\n close(): void;\n stop(review: unknown): boolean;\n};\nconst controllers = new WeakMap<ProductRequestController, Controller>();\n\n// Guest allocation and configuration preserve the original enquiry memory.\n// Only the reviewed Send command acquires storage, crypto or publication.\nexport function createProductRequestController(\n enquiry: ProductEnquiry,\n runtime?: PublicRuntime\n): ProductRequestController | undefined {\n if (typeof window === 'undefined' || !productEnquirySnapshot(enquiry)) return;\n let active = true,\n busy = false,\n attempted = false;\n let state: State = 'idle',\n copy = '',\n requestedRevision: number | undefined,\n sentRevision: number | undefined;\n let identity: IdentitySession | undefined, setup: InboxSetupView | undefined;\n let composer: PrivateComposer | undefined,\n database: BrowserDatabase | undefined;\n let plan: RumorPlan | undefined,\n preparation: SelfRecoveryPreparation | undefined,\n retry: PrivateRetry | undefined;\n let identityOff = () => {},\n generation = 0;\n const source = runtime && createPublicView(runtime);\n let resolver: InboxResolver | undefined;\n function stopWork(preserveComposer = false) {\n generation++;\n if (preserveComposer && composer) privateComposerSnapshot(composer);\n if (retry) stopPrivateRetry(retry);\n if (plan) stopRumorPlan(plan);\n if (!preserveComposer) {\n if (composer) closePrivateComposer(composer);\n composer = undefined;\n }\n }\n function close() {\n if (!active) return;\n active = false;\n stopWork();\n identityOff();\n closeProductEnquiry(enquiry);\n if (resolver) closeInboxResolver(resolver);\n if (source) disposePublicView(source);\n if (database) closeBrowserDatabase(database);\n }\n function current() {\n if (!active || !productEnquirySnapshot(enquiry)) {\n close();\n return false;\n }\n return true;\n }\n function ownership() {\n const actor = identity && identityMessagingOwnership(identity);\n const own = inboxSetupViewOwnership(setup);\n const product = productEnquirySendOwnership(enquiry);\n const data = productEnquirySnapshot(enquiry);\n return current() &&\n actor?.current() &&\n own?.current() &&\n own.identity === identity &&\n own.session &&\n product?.current() &&\n data &&\n data.peer !== actor.owner\n ? { actor, own, product, data }\n : undefined;\n }\n function ready() {\n const scope = ownership();\n return (\n !!scope &&\n !!source &&\n messagingReadinessSnapshot(\n identity!,\n scope.own.session,\n scope.own.policy,\n scope.own.resolver,\n undefined,\n scope.own.observeAccess\n ).newListingReady\n );\n }\n function snapshot(): Snapshot | undefined {\n if (!current()) return;\n const actual = productEnquirySnapshot(enquiry);\n const draft =\n actual?.revision === sentRevision &&\n composer &&\n privateComposerSnapshot(composer);\n const workflow =\n preparation && selfRecoveryPreparationSnapshot(preparation);\n return {\n state,\n busy,\n dirty: draft\n ? draft.dirty\n : !!productEnquirySnapshot(enquiry)?.text.trim(),\n revision: actual?.revision ?? 0,\n readyToSend: !attempted && state !== 'needs_action' && ready(),\n sellerInbox: sellerInboxStatus(\n resolver,\n actual!.peer,\n inboxSetupViewOwnership(setup)?.policy\n ),\n copy:\n copy ||\n (state === 'preparing'\n ? 'Preparing encryption. The extension may ask for several approvals.'\n : state === 'publishing'\n ? 'Publishing encrypted copies to the reviewed inbox relays.'\n : ''),\n saveCopy: draft\n ? draft.copy\n : attempted\n ? 'Encrypted work needs review in this browser.'\n : 'Not yet saved.',\n pairCopy: workflow?.pairCopy ?? '',\n navigation:\n requestedRevision === undefined ? 'idle' : 'confirmation_required'\n };\n }\n async function send(review: unknown): Promise<Result> {\n if (review !== 'reviewed_product_request_send')\n return { status: 'invalid' };\n if (!current()) return { status: 'stopped' };\n if (busy) return { status: 'busy' };\n if (attempted) return { status: 'needs_action' };\n const captured = ownership();\n if (\n !captured ||\n !ready() ||\n !identity ||\n !source ||\n !captured.data.text.trim()\n )\n return { status: 'invalid' };\n const actor = identity,\n originalSetup = setup,\n originalGeneration = generation;\n const privateOwner = privateSessionOwnership(captured.own.session!);\n if (\n !privateOwner?.current() ||\n privateOwner.owner !== captured.actor.owner ||\n privateOwner.session !== captured.actor.session\n )\n return { status: 'invalid' };\n const admitted = () =>\n current() &&\n generation === originalGeneration &&\n identity === actor &&\n setup === originalSetup &&\n captured.actor.current() &&\n captured.own.current() &&\n captured.product.current() &&\n privateOwner.current() &&\n productEnquirySnapshot(enquiry)?.revision === captured.data.revision &&\n inboxSetupViewOwnership(originalSetup)?.session === captured.own.session;\n function needsAction(): Result {\n state = 'needs_action';\n copy =\n 'Send needs review. Your unsent text stays in memory. Existing encrypted work requires its own recovery review.';\n return { status: 'needs_action' };\n }\n busy = true;\n state = 'checking';\n copy =\n 'Checking the intended publisher inbox. Your text remains in memory.';\n try {\n if (resolver) closeInboxResolver(resolver);\n resolver = resolveInboxPreference(\n source,\n beginPublicViewRun(source),\n captured.data.peer\n );\n const other = resolver;\n // Resolver observations are asynchronous; sample their original bounded\n // result through the existing readiness projection, without guessing.\n await settleInboxResolver(other, admitted);\n if (!admitted()) {\n const unavailable = sellerInboxCopy(\n sellerInboxStatus(other, captured.data.peer, captured.own.policy)\n );\n if (\n unavailable &&\n current() &&\n generation === originalGeneration &&\n identity === actor &&\n setup === originalSetup &&\n captured.actor.current() &&\n captured.own.current() &&\n privateOwner.current() &&\n productEnquirySnapshot(enquiry)?.revision === captured.data.revision\n ) {\n state = 'needs_action';\n copy =\n (captured.product.current()\n ? ''\n : 'Listing status changed or could not be confirmed. Review the current listing before sending. ') +\n unavailable +\n ' Your unsent text stays in memory.';\n }\n return { status: 'stopped' };\n }\n if (\n !messagingReadinessSnapshot(\n actor,\n captured.own.session,\n captured.own.policy,\n captured.own.resolver,\n { author: captured.data.peer, resolver: other },\n captured.own.observeAccess\n ).sendReady\n ) {\n const result = needsAction();\n const unavailable = sellerInboxCopy(\n sellerInboxStatus(other, captured.data.peer, captured.own.policy)\n );\n if (unavailable)\n copy =\n unavailable +\n ' Your unsent text stays in memory. Optional other contact details may be available on the listing.';\n return result;\n }\n const routes = createInboxRoutePlan(\n captured.own.policy,\n captured.actor.owner,\n captured.data.peer,\n captured.own.resolver!,\n other\n );\n const routeData = routes && inboxRoutePlanSnapshot(routes);\n if (!routes || !routeData || !admitted()) return needsAction();\n const opened = await openBrowserDatabase();\n if (opened.state !== 'ready') return needsAction();\n database = opened.owner;\n if (!admitted()) return { status: 'stopped' };\n const repository = createPrivateStorageRepository(\n database,\n captured.actor.owner\n );\n const reservations = createPrivateSendReservationRepository(\n database,\n captured.actor.owner\n );\n composer = createPrivateComposer(actor, 'reviewed_private_composer');\n sentRevision = captured.data.revision;\n if (\n !repository ||\n !reservations ||\n !composer ||\n !updatePrivateComposerText(\n composer,\n captured.data.text,\n 'reviewed_private_text'\n )\n )\n return needsAction();\n plan = captureEnquiryRumor(\n actor,\n captured.product.context,\n captured.data.text,\n Math.floor(Date.now() / 1000),\n admitted\n );\n const command = newLocalId();\n if (!plan || !command || !admitted()) return needsAction();\n attempted = true;\n const reserved = await reserveSendIdentity(\n reservations,\n actor,\n command,\n plan,\n 'reviewed_private_intent'\n );\n if (!admitted()) return { status: 'stopped' };\n if (!('identity' in reserved)) return needsAction();\n preparation = captureSelfRecoveryPreparation(\n repository,\n actor,\n reserved.identity,\n 'reviewed_self_recovery'\n );\n if (\n !preparation ||\n !bindPrivateComposerPreparation(\n composer,\n reserved.identity,\n preparation,\n captured.product.context,\n 'reviewed_composer_preparation'\n )\n )\n return needsAction();\n state = 'preparing';\n copy = '';\n const self = await prepareSelfRecovery(\n preparation,\n 'reviewed_self_recovery'\n );\n if (!admitted()) return { status: 'stopped' };\n if (\n !['saved', 'existing', 'reconciled'].includes(self.status) ||\n !preparedSelfRecovery(preparation)\n )\n return needsAction();\n const context = {\n plan: routes,\n policy: captured.own.policy,\n own: captured.own.resolver!,\n other\n };\n const paired = await preparePairedDelivery(\n preparation,\n context,\n 'reviewed_pair_preparation'\n );\n if (!admitted()) return { status: 'stopped' };\n const receipt = preparedPairedDelivery(preparation);\n if (\n !['prepared', 'existing', 'reconciled'].includes(paired.status) ||\n !receipt\n )\n return needsAction();\n const pool = getPrivatePool(\n captured.own.session!,\n captured.own.policy,\n Array.from(\n new Set([...routeData.peer.targets, ...routeData.archive.targets])\n )\n );\n if (!pool || !admitted()) return needsAction();\n retry = capturePrivateRetry(\n repository,\n captured.own.session!,\n receipt,\n context,\n pool,\n 'reviewed_private_retry'\n );\n if (!retry || !admitted()) return needsAction();\n state = 'publishing';\n const delivered = await runPrivateRetry(retry, 'reviewed_private_retry');\n if (!admitted()) return { status: 'stopped' };\n if (delivered.status !== 'completed') return needsAction();\n state = 'completed';\n copy =\n 'Accepted by recipient inbox relay. This does not confirm that the person read the message.';\n return { status: 'completed' };\n } catch {\n return admitted() ? needsAction() : { status: 'stopped' };\n } finally {\n busy = false;\n }\n }\n const token = Object.freeze({}) as ProductRequestController;\n controllers.set(token, {\n snapshot,\n text: () => (current() ? productEnquirySnapshot(enquiry)?.text : undefined),\n update(text, review) {\n if (\n review !== 'reviewed_private_text' ||\n !current() ||\n busy ||\n attempted ||\n !updateProductEnquiry(enquiry, text, 'reviewed_product_enquiry_edit')\n )\n return false;\n return true;\n },\n configure(nextIdentity, nextSetup, review) {\n if (\n review !== 'reviewed_product_request_setup' ||\n !current() ||\n attempted ||\n busy\n )\n return false;\n const actor = identityMessagingOwnership(nextIdentity),\n own = inboxSetupViewOwnership(nextSetup);\n if (!actor?.current() || !own?.current() || own.identity !== nextIdentity)\n return false;\n if (identity === nextIdentity && setup === nextSetup) return true;\n stopWork();\n identityOff();\n identity = nextIdentity;\n setup = nextSetup;\n identityOff = subscribeIdentityInvalidation(nextIdentity, () => {\n if (!actor.current()) {\n stopWork();\n copy = 'Connection changed. Your unsent text stays in memory.';\n }\n });\n return true;\n },\n send,\n stop(review) {\n if (review !== 'reviewed_product_request_cancel' || !current())\n return false;\n stopWork(true);\n if (state !== 'completed') {\n state = attempted ? 'needs_action' : 'idle';\n copy =\n 'Sending is paused. Your unsent text stays in this page; existing encrypted work requires its own recovery review.';\n }\n return true;\n },\n request() {\n if (!current()) return 'invalid';\n if (!snapshot()?.dirty) return 'allowed';\n requestedRevision = productEnquirySnapshot(enquiry)?.revision;\n return 'confirmation_required';\n },\n keep() {\n if (!current()) return false;\n requestedRevision = undefined;\n return true;\n },\n discard(review) {\n if (\n !current() ||\n review !== 'reviewed_discard_private_text' ||\n requestedRevision === undefined\n )\n return 'invalid';\n const expected = requestedRevision;\n requestedRevision = undefined;\n if (expected !== productEnquirySnapshot(enquiry)?.revision)\n return 'review_required';\n close();\n return 'allowed';\n },\n unload(event) {\n if (!current() || !snapshot()?.dirty) return false;\n event.preventDefault();\n return true;\n },\n close\n });\n return token;\n}\nexport function productRequestSnapshot(token: ProductRequestController) {\n return controllers.get(token)?.snapshot();\n}\nexport function productRequestText(token: ProductRequestController) {\n return controllers.get(token)?.text();\n}\nexport function updateProductRequestText(\n token: ProductRequestController,\n text: unknown,\n review: unknown\n) {\n return controllers.get(token)?.update(text, review) ?? false;\n}\nexport function configureProductRequest(\n token: ProductRequestController,\n identity: IdentitySession,\n setup: InboxSetupView,\n review: unknown\n) {\n return controllers.get(token)?.configure(identity, setup, review) ?? false;\n}\nexport function sendProductRequest(\n token: ProductRequestController,\n review: unknown\n): Promise<Result> {\n return (\n controllers.get(token)?.send(review) ??\n Promise.resolve({ status: 'invalid' })\n );\n}\nexport function requestProductRequestNavigation(\n token: ProductRequestController\n): NavigationResult {\n return controllers.get(token)?.request() ?? 'invalid';\n}\nexport function keepProductRequestEditing(token: ProductRequestController) {\n return controllers.get(token)?.keep() ?? false;\n}\nexport function discardProductRequestNavigation(\n token: ProductRequestController,\n review: unknown\n): NavigationResult {\n return controllers.get(token)?.discard(review) ?? 'invalid';\n}\nexport function productRequestBeforeUnload(\n token: ProductRequestController,\n event: BeforeUnloadEvent\n) {\n return controllers.get(token)?.unload(event) ?? false;\n}\nexport function closeProductRequestController(token: ProductRequestController) {\n controllers.get(token)?.close();\n}\nexport function stopProductRequestWork(\n token: ProductRequestController,\n review: unknown\n) {\n return controllers.get(token)?.stop(review) ?? false;\n}\n", 197 sha256: 198 '9fb8bb41657de661d4fe32d05f78fdc453e215467b08ee7d8036d39093cb0979' 199 }, 200 'src/lib/nostr/inbox-preference-publication.ts': { 201 source: 202 "import type { NostrEvent } from 'applesauce-core/helpers';\nimport {\n publicRelayTargets,\n readRelayPolicy,\n type RelayPolicy\n} from '../config/relays.ts';\nimport {\n identityMessagingOwnership,\n identityPublicOperationOwnership,\n recheckIdentityOwner,\n type IdentitySession,\n type IdentityPublicOperation\n} from '../runtime/identity-session.ts';\nimport {\n publicEffectLeaseCurrent,\n type PublicEffectLease\n} from '../runtime/effect-ownership.ts';\nimport {\n loadPreferenceOperation,\n type PublicQuotaRepository\n} from '../persistence/quota.ts';\nimport {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\ndeclare const publicationBrand: unique symbol;\nexport type PreferencePublication = Readonly<{ [publicationBrand]: true }>;\ntype Saved = Readonly<{\n policy: RelayPolicy;\n wire: string;\n eventId: string;\n origins: readonly string[];\n current(): boolean;\n}>;\nconst publications = new WeakMap<PreferencePublication, Saved>();\n// Internal exact policy observation, not a Nostr cryptographic replacement.\nexport async function preferencePolicyFingerprint(\n policy: RelayPolicy\n): Promise<string> {\n const hash = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(JSON.stringify(readRelayPolicy(policy)))\n );\n return Array.from(new Uint8Array(hash), (byte) =>\n byte.toString(16).padStart(2, '0')\n ).join('');\n}\n// Only a genuine current identity operation and original lease can acquire this\n// one-attempt capability from actual acknowledged storage. No caller event wire.\n// beforeEffect is an internal bounded lookup port; its final fence is retained.\nexport async function authorizeStoredInboxPreference(\n repository: PublicQuotaRepository,\n identity: IdentitySession,\n operation: IdentityPublicOperation,\n lease: PublicEffectLease,\n original: PublicRecordHandle,\n id: string,\n policy: RelayPolicy,\n beforeEffect: () => Promise<(() => boolean) | undefined>\n): Promise<PreferencePublication | undefined> {\n try {\n if (typeof window === 'undefined') return undefined;\n const capture = identityPublicOperationOwnership(identity, operation);\n const messageOwner = identityMessagingOwnership(identity);\n if (\n !capture ||\n !messageOwner ||\n capture.owner !== messageOwner.owner ||\n capture.session !== messageOwner.session\n )\n return undefined;\n const originalWire = publicRecordWire(original, capture.owner, id),\n row = publicRecordSnapshot(original, capture.owner, id);\n if (\n !originalWire ||\n row?.family !== 'preference_operation' ||\n row.revision !== 0 ||\n row.capture.kind !== 10050\n )\n return undefined;\n const authority = {\n owner: capture.owner,\n id,\n recordWire: originalWire,\n session: capture.session\n };\n const fingerprint = await preferencePolicyFingerprint(policy),\n manifest = readRelayPolicy(policy),\n targets = publicRelayTargets(policy, 'write');\n if (\n !manifest.messagingEnabled ||\n !manifest.postingEnabled ||\n fingerprint !== row.capture.policyFingerprint ||\n JSON.stringify(targets) !== JSON.stringify(row.capture.targets)\n )\n return undefined;\n const read = await loadPreferenceOperation(repository, id);\n if (!read.ok) return undefined;\n const stored = publicRecordSnapshot(read.value, capture.owner, id);\n if (\n stored?.family !== 'preference_operation' ||\n stored.revision < 2 ||\n !stored.artifact ||\n JSON.stringify(stored.capture) !== JSON.stringify(row.capture) ||\n JSON.stringify(stored.source) !== JSON.stringify(row.source) ||\n stored.consent !== row.consent\n )\n return undefined;\n const headCurrent = await beforeEffect();\n if (!headCurrent) return undefined;\n await recheckIdentityOwner(identity);\n const current = () =>\n capture.current() &&\n messageOwner.current() &&\n headCurrent() &&\n publicEffectLeaseCurrent(lease, authority);\n if (!current()) return undefined;\n const token = Object.freeze({}) as PreferencePublication;\n publications.set(token, {\n policy,\n wire: stored.artifact.wire,\n eventId: stored.artifact.eventId,\n origins: [...stored.capture.targets],\n current\n });\n return token;\n } catch {\n return undefined;\n }\n}\n// Detached metadata never grants permission. Pool consumes the original token.\nexport function preferencePublicationSnapshot(token: PreferencePublication) {\n const saved = publications.get(token);\n return saved\n ? { eventId: saved.eventId, origins: [...saved.origins] }\n : undefined;\n}\nexport function takePreferencePublication(\n token: PreferencePublication,\n policy: RelayPolicy,\n origin: string\n): Readonly<{ event: NostrEvent; current(): boolean }> | undefined {\n const saved = publications.get(token);\n if (!saved) return undefined;\n publications.delete(token);\n if (\n saved.policy !== policy ||\n !saved.origins.includes(origin) ||\n !saved.current()\n )\n return undefined;\n return {\n event: JSON.parse(saved.wire) as NostrEvent,\n current: saved.current\n };\n}\n", 203 sha256: 204 'fbad642340732bf7cf92905010af314829b80cc7b134121396f14e9bb8e765cc' 205 } 206 }, 207 ...{ 208 'src/routes/privacy/+page.svelte': { 209 source: 210 "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import Button from '../../lib/components/primitives/Button.svelte';\n import {\n LOCAL_PUBLIC_HIDES_CONTEXT,\n PUBLIC_HIDE_DISCLOSURE,\n localPublicHidesSnapshot,\n subscribeLocalPublicHides,\n undoLocalPublicPublisher,\n type LocalPublicHides\n } from '../../lib/persistence/local-public-hides.ts';\n const hides = getContext<LocalPublicHides | undefined>(\n LOCAL_PUBLIC_HIDES_CONTEXT\n );\n import {\n LOCAL_PRIVATE_BLOCKS_CONTEXT,\n PRIVATE_BLOCK_DISCLOSURE,\n localPrivateBlocksViewSnapshot,\n subscribeLocalPrivateBlocksView,\n undoLocalPrivateBlocksView,\n type LocalPrivateBlocksView\n } from '../../lib/persistence/local-private-blocks.ts';\n const blocks = getContext<LocalPrivateBlocksView | undefined>(\n LOCAL_PRIVATE_BLOCKS_CONTEXT\n );\n let privateSnapshot = $state.raw(\n blocks\n ? localPrivateBlocksViewSnapshot(blocks)\n : { state: 'guest' as const }\n );\n let privateNotice = $state<string | undefined>();\n let privateBusy = $state(false);\n onMount(() => {\n if (!blocks) return;\n privateSnapshot = localPrivateBlocksViewSnapshot(blocks);\n return subscribeLocalPrivateBlocksView(blocks, () => {\n privateSnapshot = localPrivateBlocksViewSnapshot(blocks);\n privateNotice = undefined;\n });\n });\n async function undoBlock(peer: string) {\n if (!blocks || privateBusy || privateSnapshot.state !== 'ready') return;\n const owner = privateSnapshot.owner;\n privateBusy = true;\n const result = await undoLocalPrivateBlocksView(\n blocks,\n peer,\n 'reviewed_local_private_undo'\n );\n if (!alive) return;\n privateBusy = false;\n const current = localPrivateBlocksViewSnapshot(blocks);\n if (current.state !== 'ready' || current.owner !== owner) return;\n privateNotice =\n result.status === 'saved' || result.status === 'existing'\n ? 'Block undone. Eligible local views can be shown again. Another explicit bounded decryption action may be needed; Undo starts no message work.'\n : 'Undo was not confirmed. Existing local data has not been reset.';\n }\n let snapshot = $state.raw(\n hides ? localPublicHidesSnapshot(hides) : { state: 'guest' as const }\n );\n let notice = $state<string | undefined>(),\n busy = $state(false);\n let alive = false;\n onMount(() => {\n alive = true;\n const off = hides\n ? subscribeLocalPublicHides(hides, () => {\n snapshot = localPublicHidesSnapshot(hides);\n notice = undefined;\n })\n : () => {};\n if (hides) snapshot = localPublicHidesSnapshot(hides);\n return () => {\n alive = false;\n off();\n };\n });\n async function undo(publisher: string) {\n if (!hides || busy || snapshot.state !== 'ready') return;\n const owner = snapshot.owner;\n busy = true;\n const result = await undoLocalPublicPublisher(\n hides,\n publisher,\n 'reviewed_local_public_undo'\n );\n if (!alive) return;\n busy = false;\n const current = localPublicHidesSnapshot(hides);\n if (current.state !== 'ready' || current.owner !== owner) return;\n notice =\n result.status === 'saved' || result.status === 'existing'\n ? 'Hide undone. Eligible public listings can be shown again; operator policy still applies.'\n : 'Undo was not confirmed. Existing local data has not been reset.';\n }\n</script>\n\n<svelte:head><title>Privacy \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Privacy</h1>\n <p>\n Listings are public. Relay queries can reveal your search or publisher\n interest; search URLs may remain in browser history and hosting logs. This\n prototype uses no tracking analytics.\n </p>\n <p>{PUBLIC_HIDE_DISCLOSURE}</p>\n <h2>Local publisher controls</h2>\n {#if snapshot.state === 'ready'}\n {#if snapshot.publishers.length}\n <ul class=\"stack\">\n {#each snapshot.publishers as publisher (publisher)}\n <li class=\"stack\">\n <p class=\"key\">{publisher}</p>\n <Button\n label=\"Undo hide\"\n onclick={() => undo(publisher)}\n disabled={busy}\n />\n </li>\n {/each}\n </ul>\n {:else}<p>No publishers hidden for this account in this browser.</p>{/if}\n {:else if snapshot.state === 'guest'}\n <p>\n Connect to review your account-local publisher preferences. Guest browsing\n does not expose an account inventory.\n </p>\n {:else if snapshot.state === 'loading'}\n <p>Checking local publisher preferences\u2026</p>\n {:else}\n <p class=\"notice\">\n Local preferences could not be checked. You can still browse public food.\n Existing local data has not been reset; previous hides are unconfirmed.\n </p>\n {/if}\n {#if notice}<p role=\"status\">{notice}</p>{/if}\n <p>{PRIVATE_BLOCK_DISCLOSURE}</p>\n <h2>Local private blocks</h2>\n {#if privateSnapshot.state === 'ready'}\n {#if privateSnapshot.peers.length}\n <ul class=\"stack\">\n {#each privateSnapshot.peers as peer (peer)}\n <li class=\"stack\">\n <p class=\"key\">{peer}</p>\n <Button\n label=\"Undo block\"\n onclick={() => undoBlock(peer)}\n disabled={privateBusy}\n />\n </li>\n {/each}\n </ul>\n {:else}<p>No people blocked for this account in this browser.</p>{/if}\n {:else if privateSnapshot.state === 'guest'}\n <p>\n Connect to review account-local blocks. Guest browsing does not expose a\n private inventory.\n </p>\n {:else if privateSnapshot.state === 'loading'}\n <p>Checking local private block preferences\u2026</p>\n {:else}\n <p class=\"notice\">\n Local private preferences could not be checked. Previous blocks are\n unconfirmed; private rendering and decryption continuation are\n unavailable. Existing local data has not been reset.\n </p>\n {/if}\n {#if privateNotice}<p role=\"status\">{privateNotice}</p>{/if}\n</div>\n", 211 sha256: 212 'b16f21dddcff172b837ab9980a5d8e93b59d5ddb5fa15ce463e07affdee79547' 213 }, 214 'src/lib/persistence/quota.ts': { 215 source: 216 "import { canonicalPublicKey } from '../contracts/public-key.ts';\nimport {\n exactLocalFields,\n type PublicRecord,\n type PublicDraftRecord\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';\nimport {\n browserDatabaseState,\n browserDatabaseTransaction,\n type BrowserDatabase\n} from './database.ts';\nimport {\n decodePublicRecord,\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from './records.ts';\nimport {\n publicInventoryRow,\n PUBLIC_CLEANUP_CONSEQUENCES,\n type PublicInventoryRow\n} from './local-inventory.ts';\n\nimport {\n publicTransitionIdentity,\n publicTransitionSnapshot,\n type PublicOperationTransition\n} from './artifact-records.ts';\nimport { decideFrozenTransition } from './operation-transactions.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\n\ndeclare const repositoryBrand: unique symbol;\ndeclare const inventoryBrand: unique symbol;\ndeclare const cleanupBrand: unique symbol;\nexport type PublicQuotaRepository = Readonly<{ [repositoryBrand]: true }>;\nexport type PublicInventory = Readonly<{ [inventoryBrand]: true }>;\nexport type PublicCleanup = Readonly<{ [cleanupBrand]: true }>;\nexport type PublicQuotaFailure =\n | 'invalid_scope'\n | 'invalid_record'\n | 'invalid_selection'\n | 'protected'\n | 'conflict'\n | 'capacity'\n | 'corrupt_record'\n | 'unavailable'\n | 'aborted'\n | 'unknown_completion';\nexport type PublicQuotaResult<T> =\n | Readonly<{ ok: true; value: T }>\n | Readonly<{ ok: false; reason: PublicQuotaFailure }>;\ntype Scope = Readonly<{ database: BrowserDatabase; owner: string }>;\ntype Store = 'public_drafts' | 'public_operations' | 'preference_operations';\ntype Row = Readonly<{\n store: Store;\n wire: string;\n record: PublicRecord;\n bytes: number;\n}>;\ntype Inspection = Readonly<{\n repository: PublicQuotaRepository;\n rows: readonly Row[];\n}>;\ntype Cleanup = Readonly<{ inventory: Inspection; selected: readonly string[] }>;\nconst repositories = new WeakMap<PublicQuotaRepository, Scope>();\nconst inventories = new WeakMap<PublicInventory, Inspection>();\nconst cleanups = new WeakMap<PublicCleanup, Cleanup>();\nconst stores: readonly Store[] = [\n 'public_drafts',\n 'public_operations',\n 'preference_operations'\n];\nfunction failed(reason: PublicQuotaFailure): PublicQuotaResult<never> {\n return { ok: false, reason };\n}\nfunction scopeOf(repository: PublicQuotaRepository): Scope | undefined {\n const scope = repositories.get(repository);\n try {\n return scope && browserDatabaseState(scope.database).state === 'ready'\n ? scope\n : undefined;\n } catch {\n return undefined;\n }\n}\n// Metadata only; this does not grant installed-account or effect authority.\nexport function publicQuotaOwner(\n repository: PublicQuotaRepository\n): string | undefined {\n return scopeOf(repository)?.owner;\n}\n// A namespace capability only; installed-account authorization belongs to the\n// account workflow. This repository never acquires any private store.\nexport function createPublicQuotaRepository(\n database: BrowserDatabase,\n expectedOwner: unknown\n): PublicQuotaRepository | undefined {\n const owner = canonicalPublicKey(expectedOwner);\n try {\n if (!owner || browserDatabaseState(database).state !== 'ready')\n return undefined;\n const handle = Object.freeze({}) as PublicQuotaRepository;\n repositories.set(handle, { database, owner });\n return handle;\n } catch {\n return undefined;\n }\n}\nfunction stored(\n value: unknown,\n store: Store,\n owner: string,\n id: string\n): Row | undefined {\n if (\n !exactLocalFields(value, ['owner', 'id', 'wire']) ||\n value.owner !== owner ||\n value.id !== id ||\n typeof value.wire !== 'string'\n )\n return undefined;\n const admitted = decodePublicRecord(value.wire, owner, id);\n if (!admitted.ok) return undefined;\n const record = publicRecordSnapshot(admitted.value, owner, id);\n const family =\n store === 'public_drafts'\n ? 'public_draft'\n : store === 'public_operations'\n ? 'public_operation'\n : 'preference_operation';\n return record?.family === family\n ? {\n store,\n record,\n wire: value.wire,\n bytes: new TextEncoder().encode(value.wire).length\n }\n : undefined;\n}\nfunction transaction<T>(\n scope: Scope,\n mode: 'readonly' | 'readwrite',\n finish: (\n rows: readonly Row[],\n transaction: IDBTransaction,\n refuse: (reason: PublicQuotaFailure) => void\n ) => PublicQuotaResult<T> | undefined\n): Promise<PublicQuotaResult<T>> {\n let active: IDBTransaction;\n try {\n active = browserDatabaseTransaction(scope.database, stores, mode);\n } catch {\n return Promise.resolve(failed('unavailable'));\n }\n return new Promise((resolve) => {\n let result: PublicQuotaResult<T> | undefined;\n let rows = Array.from<Row>([]),\n draftCount = 0,\n operationCount = 0,\n operationBytes = 0;\n function refuse(reason: PublicQuotaFailure) {\n result = failed(reason);\n try {\n active.abort();\n } catch {\n result = failed('unknown_completion');\n }\n }\n active.addEventListener('complete', () =>\n resolve(result ?? failed('unknown_completion'))\n );\n active.addEventListener('abort', () =>\n resolve(result && !result.ok ? result : failed('aborted'))\n );\n function scan(index: number): void {\n try {\n const store = stores[index];\n if (store === undefined) {\n const finished = finish(rows, active, refuse);\n if (finished !== undefined) result = finished;\n return;\n }\n const request = active\n .objectStore(store)\n .index('by_owner')\n .openCursor(IDBKeyRange.only(scope.owner));\n request.addEventListener('success', () => {\n try {\n const cursor = request.result;\n if (!cursor) {\n scan(index + 1);\n return;\n }\n const key = cursor.primaryKey;\n const id =\n Array.isArray(key) && key.length === 2 && key[0] === scope.owner\n ? canonicalLocalId(key[1])\n : undefined;\n const row = id && stored(cursor.value, store, scope.owner, id);\n if (!row) {\n refuse('corrupt_record');\n return;\n }\n if (row.record.family === 'public_draft') draftCount++;\n else {\n operationCount++;\n operationBytes += row.bytes;\n }\n if (\n draftCount > LOCAL_PERSISTENCE_BUDGETS.publicDrafts ||\n operationCount > LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operationBytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n rows = rows.concat(row);\n cursor.continue();\n } catch {\n refuse('aborted');\n }\n });\n } catch {\n refuse('aborted');\n }\n }\n scan(0);\n });\n}\n// Explicit new-row admission only. Artifact/CAS transitions retain HCP050.\n// Logical bytes include the exact stored record wire, not browser disk/heap use.\nexport function admitPublicOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle\n): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n const record = publicRecordSnapshot(handle, scope.owner, id),\n wire = publicRecordWire(handle, scope.owner, id);\n if (\n !record ||\n !wire ||\n record.family === 'public_draft' ||\n record.revision !== 0\n )\n return Promise.resolve(failed('invalid_record'));\n const store: Store =\n record.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const bytes = new TextEncoder().encode(wire).length;\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const previous = rows.find(\n (row) => row.store === store && row.record.id === id\n );\n if (previous)\n return previous.wire === wire\n ? { ok: true, value: { id, revision: 0 } }\n : (refuse('conflict'), undefined);\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n if (\n operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operations.reduce((sum, row) => sum + row.bytes, bytes) >\n LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n active.objectStore(store).put({ owner: scope.owner, id, wire });\n return { ok: true, value: { id, revision: 0 } };\n });\n}\n// Claim under the caller's origin/author Web Lock. A previous capture is never\n// overwritten or automatically signed again, even after a page lost its lock.\n// No extension/network await occurs inside the short transaction.\nexport function claimPublicOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n return claimOperation(repository, expectedId, handle);\n}\ntype DraftAdmission = Readonly<{\n expected: PublicDraftRecord;\n current(this: void): boolean;\n draftCurrent(this: void): boolean;\n revisionBase?: Readonly<{ command: string; record: PublicRecordHandle }>;\n}>;\n// Storage-only atomic draft/CAS reservation. Current original account/review\n// ownership is supplied by the public listing command owner, never a UI flag.\n// Existing commands retain their original capture even after future draft edits.\nexport function claimPublicDraftOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle,\n admission: DraftAdmission\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n return claimOperation(repository, expectedId, handle, admission);\n}\nfunction claimOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown,\n handle: PublicRecordHandle,\n draft?: DraftAdmission\n): Promise<\n PublicQuotaResult<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >\n> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n const record = publicRecordSnapshot(handle, scope.owner, id),\n wire = publicRecordWire(handle, scope.owner, id);\n if (\n !record ||\n !wire ||\n record.family === 'public_draft' ||\n record.revision !== 0 ||\n record.artifact !== null\n )\n return Promise.resolve(failed('invalid_record'));\n const store: Store =\n record.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const bytes = new TextEncoder().encode(wire).length;\n return transaction<\n Readonly<{ state: 'created' | 'existing'; record: PublicRecordHandle }>\n >(scope, 'readwrite', (rows, active, refuse) => {\n if (draft && !draft.current()) {\n refuse('unavailable');\n return;\n }\n const previous = rows.find(\n (row) => row.record.family !== 'public_draft' && row.record.id === id\n );\n if (previous) {\n const original = previous.record;\n if (\n original.family === 'public_draft' ||\n original.family !== record.family ||\n JSON.stringify(original.source) !== JSON.stringify(record.source) ||\n JSON.stringify(original.capture) !== JSON.stringify(record.capture) ||\n ('consent' in original ? original.consent : null) !==\n ('consent' in record ? record.consent : null)\n ) {\n refuse('conflict');\n return;\n }\n const decoded = decodePublicRecord(previous.wire, scope.owner, id);\n if (!decoded.ok) {\n refuse('corrupt_record');\n return;\n }\n return { ok: true, value: { state: 'existing', record: decoded.value } };\n }\n if (draft) {\n if (draft.revisionBase) {\n const revisionBase = draft.revisionBase;\n const witness = publicRecordSnapshot(\n revisionBase.record,\n scope.owner,\n revisionBase.command\n );\n const base = rows.find(\n (row) =>\n row.record.family === 'public_operation' &&\n row.record.id === revisionBase.command\n )?.record;\n const oldTemplate =\n witness?.family === 'public_operation' &&\n inspectLocalTemplate(witness.capture.wire, scope.owner, 30402);\n const nextTemplate =\n record.family === 'public_operation' &&\n inspectLocalTemplate(\n record.capture.wire,\n scope.owner,\n record.capture.kind\n );\n const tag = (\n template: NonNullable<ReturnType<typeof inspectLocalTemplate>>,\n key: string\n ) => template.tags.find((value) => value[0] === key)?.[1];\n if (\n !witness ||\n witness.family !== 'public_operation' ||\n !witness.artifact ||\n !base ||\n base.family !== 'public_operation' ||\n !oldTemplate ||\n !nextTemplate ||\n JSON.stringify(base.source) !== JSON.stringify(witness.source) ||\n JSON.stringify(base.capture) !== JSON.stringify(witness.capture) ||\n JSON.stringify(base.artifact) !== JSON.stringify(witness.artifact) ||\n (nextTemplate.kind === 5\n ? record.family !== 'public_operation' ||\n record.source.type !== 'public_head' ||\n record.source.wire !== witness.artifact.wire ||\n JSON.stringify(nextTemplate.tags) !==\n JSON.stringify([\n ['e', witness.artifact.eventId],\n ['a', `30402:${scope.owner}:${tag(oldTemplate, 'd')}`],\n ['k', '30402']\n ]) ||\n nextTemplate.content !== ''\n : tag(oldTemplate, 'd') !== tag(nextTemplate, 'd') ||\n tag(oldTemplate, 'published_at') !==\n tag(nextTemplate, 'published_at')) ||\n nextTemplate.created_at <= oldTemplate.created_at ||\n rows.some((row) => {\n if (\n row.record.family !== 'public_operation' ||\n row.record.id === base.id\n )\n return false;\n const other = inspectLocalTemplate(\n row.record.capture.wire,\n scope.owner,\n row.record.capture.kind\n );\n return (\n !!other &&\n (other.kind === 5\n ? other.tags.some(\n (value) =>\n (value[0] === 'e' &&\n value[1] === witness.artifact!.eventId) ||\n (value[0] === 'a' &&\n value[1] ===\n `30402:${scope.owner}:${tag(oldTemplate, 'd')}`)\n ) && other.created_at >= oldTemplate.created_at\n : tag(other, 'd') === tag(oldTemplate, 'd') &&\n other.created_at >= oldTemplate.created_at)\n );\n })\n ) {\n refuse('conflict');\n return;\n }\n }\n const source =\n record.family === 'public_operation' ? record.source : undefined;\n const previousDraft = rows.find(\n (row) =>\n row.record.family === 'public_draft' &&\n row.record.id === draft.expected.id\n );\n if (\n !source ||\n (source.type !== 'draft' &&\n !(\n source.type === 'public_head' &&\n record.family === 'public_operation' &&\n record.capture.kind === 5 &&\n draft.revisionBase\n )) ||\n draft.expected.owner !== scope.owner ||\n (source.type === 'draft' &&\n (source.id !== draft.expected.id ||\n source.revision !== draft.expected.revision)) ||\n !previousDraft ||\n JSON.stringify(previousDraft.record) !==\n JSON.stringify(draft.expected) ||\n !draft.draftCurrent()\n ) {\n refuse('conflict');\n return;\n }\n }\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n if (\n operations.length >= LOCAL_PERSISTENCE_BUDGETS.publicOperations ||\n operations.reduce((sum, row) => sum + row.bytes, bytes) >\n LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes\n ) {\n refuse('capacity');\n return;\n }\n if (draft && (!draft.current() || !draft.draftCurrent())) {\n refuse('conflict');\n return;\n }\n active.objectStore(store).put({ owner: scope.owner, id, wire });\n return { ok: true, value: { state: 'created', record: handle } };\n });\n}\nexport function inspectPublicStorage(\n repository: PublicQuotaRepository\n): Promise<PublicQuotaResult<PublicInventory>> {\n const scope = scopeOf(repository);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n return transaction(scope, 'readonly', (rows) => {\n const handle = Object.freeze({}) as PublicInventory;\n inventories.set(handle, { repository, rows });\n return { ok: true, value: handle };\n });\n}\nexport function publicInventorySnapshot(\n repository: PublicQuotaRepository,\n handle: PublicInventory\n):\n | Readonly<{ rows: readonly PublicInventoryRow[]; consequences: string }>\n | undefined {\n const inventory = inventories.get(handle);\n return scopeOf(repository) && inventory?.repository === repository\n ? {\n rows: inventory.rows.map((row) =>\n publicInventoryRow(row.record, row.bytes)\n ),\n consequences: PUBLIC_CLEANUP_CONSEQUENCES\n }\n : undefined;\n}\nexport function reviewPublicCleanup(\n repository: PublicQuotaRepository,\n handle: PublicInventory,\n selection: unknown\n): PublicQuotaResult<PublicCleanup> {\n const inventory = inventories.get(handle);\n if (!scopeOf(repository) || inventory?.repository !== repository)\n return failed('invalid_scope');\n try {\n if (!Array.isArray(selection)) return failed('invalid_selection');\n const length = selection.length;\n if (\n !Number.isSafeInteger(length) ||\n length <= 0 ||\n length >\n LOCAL_PERSISTENCE_BUDGETS.publicDrafts +\n LOCAL_PERSISTENCE_BUDGETS.publicOperations\n )\n return failed('invalid_selection');\n let selected = Array.from<string>([]);\n for (let index = 0; index < length; index++) {\n const key: unknown = selection[index];\n if (typeof key !== 'string' || selected.includes(key))\n return failed('invalid_selection');\n const row = inventory.rows.find(\n (row) => publicInventoryRow(row.record, row.bytes).key === key\n );\n if (!row) return failed('invalid_selection');\n if (publicInventoryRow(row.record, row.bytes).state !== 'settled')\n return failed('protected');\n selected = selected.concat(key);\n }\n if (!scopeOf(repository)) return failed('invalid_scope');\n const token = Object.freeze({}) as PublicCleanup;\n cleanups.set(token, { inventory, selected });\n return { ok: true, value: token };\n } catch {\n return failed('invalid_selection');\n }\n}\nexport function publicCleanupSnapshot(\n repository: PublicQuotaRepository,\n handle: PublicCleanup\n):\n | Readonly<{\n selected: readonly PublicInventoryRow[];\n logicalBytesRemoved: number;\n consequences: string;\n }>\n | undefined {\n const cleanup = cleanups.get(handle);\n if (!scopeOf(repository) || cleanup?.inventory.repository !== repository)\n return undefined;\n const selected = cleanup.inventory.rows\n .map((row) => publicInventoryRow(row.record, row.bytes))\n .filter((row) => cleanup.selected.includes(row.key));\n return {\n selected,\n logicalBytesRemoved: selected.reduce(\n (sum, row) => sum + row.logicalBytes,\n 0\n ),\n consequences: PUBLIC_CLEANUP_CONSEQUENCES\n };\n}\nexport function commitPublicCleanup(\n repository: PublicQuotaRepository,\n handle: PublicCleanup\n): Promise<PublicQuotaResult<readonly string[]>> {\n const cleanup = cleanups.get(handle),\n scope = scopeOf(repository);\n if (!scope || cleanup?.inventory.repository !== repository)\n return Promise.resolve(failed('invalid_scope'));\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const before = cleanup.inventory.rows;\n if (\n rows.length !== before.length ||\n rows.some(\n (row, i) =>\n row.store !== before[i].store ||\n row.record.id !== before[i].record.id ||\n row.wire !== before[i].wire\n )\n ) {\n refuse('conflict');\n return;\n }\n const selected = rows.filter((row) =>\n cleanup.selected.includes(publicInventoryRow(row.record, row.bytes).key)\n );\n if (\n selected.length !== cleanup.selected.length ||\n selected.some(\n (row) => publicInventoryRow(row.record, row.bytes).state !== 'settled'\n )\n ) {\n refuse('protected');\n return;\n }\n for (const row of selected)\n active.objectStore(row.store).delete([scope.owner, row.record.id]);\n return { ok: true, value: Array.from(cleanup.selected) };\n });\n}\n\n// No signer/network await exists inside this transaction. It consumes only a\n// genuine immutable typed transition captured before storage acquisition.\n// Exact owner-scoped actual stored preference, not a caller's structural row.\n// Read is bounded by the same complete quota/codec scan and transaction ack.\nexport function loadPreferenceOperation(\n repository: PublicQuotaRepository,\n expectedId: unknown\n): Promise<PublicQuotaResult<PublicRecordHandle>> {\n const scope = scopeOf(repository),\n id = canonicalLocalId(expectedId);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n if (!id) return Promise.resolve(failed('invalid_record'));\n return transaction(scope, 'readonly', (rows) => {\n const row = rows.find(\n (row) => row.store === 'preference_operations' && row.record.id === id\n );\n if (!row) return failed('invalid_record');\n const decoded = decodePublicRecord(row.wire, scope.owner, id);\n return decoded.ok ? decoded : failed('corrupt_record');\n });\n}\nexport function commitPublicOperationTransition(\n repository: PublicQuotaRepository,\n handle: PublicOperationTransition\n): Promise<PublicQuotaResult<Readonly<{ id: string; revision: number }>>> {\n const scope = scopeOf(repository);\n if (!scope) return Promise.resolve(failed('invalid_scope'));\n const identity = publicTransitionIdentity(handle);\n const command =\n identity && publicTransitionSnapshot(handle, scope.owner, identity.id);\n if (!command) return Promise.resolve(failed('invalid_record'));\n const store: Store =\n command.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n return transaction(scope, 'readwrite', (rows, active, refuse) => {\n const previous = rows.find(\n (row) => row.store === store && row.record.id === command.id\n );\n const decision = decideFrozenTransition(\n previous?.wire,\n command.baseWire,\n command.nextWire\n );\n if (decision === 'conflict') {\n refuse('conflict');\n return;\n }\n if (decision === 'committed')\n return {\n ok: true,\n value: { id: command.id, revision: command.revision }\n };\n const operations = rows.filter(\n (row) => row.record.family !== 'public_draft'\n );\n const bytes =\n operations.reduce((sum, row) => sum + row.bytes, 0) -\n (previous?.bytes ?? 0) +\n new TextEncoder().encode(command.nextWire).length;\n if (bytes > LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes) {\n refuse('capacity');\n return;\n }\n active\n .objectStore(store)\n .put({ owner: scope.owner, id: command.id, wire: command.nextWire });\n return { ok: true, value: { id: command.id, revision: command.revision } };\n });\n}\nexport async function observePublicOperationTransition(\n repository: PublicQuotaRepository,\n handle: PublicOperationTransition\n): Promise<\n | Readonly<{ state: 'committed'; id: string; revision: number }>\n | Readonly<{ state: 'base_observed' | 'conflict' | 'unavailable' }>\n> {\n const scope = scopeOf(repository),\n identity = publicTransitionIdentity(handle);\n const command =\n scope &&\n identity &&\n publicTransitionSnapshot(handle, scope.owner, identity.id);\n if (!scope || !command) return { state: 'unavailable' };\n const store: Store =\n command.family === 'public_operation'\n ? 'public_operations'\n : 'preference_operations';\n const read = await transaction(scope, 'readonly', (rows) => ({\n ok: true,\n value: decideFrozenTransition(\n rows.find((row) => row.store === store && row.record.id === command.id)\n ?.wire,\n command.baseWire,\n command.nextWire\n )\n }));\n if (!read.ok || !scopeOf(repository)) return { state: 'unavailable' };\n return read.value === 'committed'\n ? { state: 'committed', id: command.id, revision: command.revision }\n : { state: read.value };\n}\n", 217 sha256: 218 'e261a7c9c81d0685021663639b1bb543192e65580edb64fa58ccbb9a4a04cc95' 219 } 220 }, 221 ...{ 222 'src/routes/about/+page.svelte': { 223 source: 224 '<svelte:head><title>About \u2014 HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>About</h1>\n <p class="notice">\n Information about HarvestCircle is unavailable during development.\n </p>\n <section id="help">\n <h2>Help / report</h2>\n <p>Help and reporting are unavailable during development.</p>\n </section>\n</div>\n', 225 sha256: 226 'eb405489e948426aee5716354304e8d6fb4dffcfefc9f6836470e3f5e02623a7' 227 }, 228 'src/routes/products/[naddr=naddr]/+page.svelte': { 229 source: 230 "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import { page } from '$app/state';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n createPublicView,\n disposePublicView,\n type PublicView,\n type PublicRuntime,\n type PublicRuntimeContext\n } from '../../../lib/runtime/public-runtime.ts';\n import {\n createProductView,\n closeProductView,\n type ProductView,\n type ProductViewSnapshot\n } from '../../../lib/catalog/product-view.ts';\n import { decodeProductReference } from '../../../lib/nostr/references.ts';\n import { readPublicContact } from '../../../lib/contracts/food-availability-v1/contact-read.ts';\n import { copyProductReference } from '../../../lib/navigation-copy.ts';\n import { internalHref, navigationHref } from '../../../lib/navigation-url.ts';\n import ListingFacts from '../../../lib/components/ListingFacts.svelte';\n import PublisherIdentity from '../../../lib/components/PublisherIdentity.svelte';\n import Disclosure from '../../../lib/components/primitives/Disclosure.svelte';\n import Button from '../../../lib/components/primitives/Button.svelte';\n import ProductEnquiry from '../../../lib/components/ProductEnquiry.svelte';\n import PublisherHide from '../../../lib/components/PublisherHide.svelte';\n const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);\n let runtime = $state.raw<PublicRuntime | undefined>(),\n result = $state.raw<ProductViewSnapshot | undefined>(),\n error = $state<string | undefined>(),\n copyNotice = $state<string | undefined>();\n let productOwner = $state.raw<ProductView | undefined>();\n const reference = $derived(decodeProductReference(page.params.naddr));\n const contact = $derived(readPublicContact(result?.food?.content));\n let disposed = false;\n onMount(() => {\n const unavailable = () => {\n if (!disposed) error = 'Food sources are unavailable.';\n };\n try {\n void publicRuntimeReady(context)\n .then((value) => {\n if (!disposed) {\n runtime = value;\n if (!value) unavailable();\n }\n })\n .catch(unavailable);\n } catch {\n unavailable();\n }\n return () => {\n disposed = true;\n };\n });\n $effect(() => {\n const selected = reference,\n shared = runtime;\n result = undefined;\n productOwner = undefined;\n copyNotice = undefined;\n if (!selected || !shared) return;\n let active = true,\n acquired: PublicView | undefined,\n owner: ProductView | undefined;\n try {\n acquired = createPublicView(shared);\n owner = createProductView(\n acquired,\n selected.naddr,\n { nowSeconds: () => Math.floor(Date.now() / 1000) },\n (value) => {\n if (active && !disposed) result = value;\n }\n );\n productOwner = owner;\n error = undefined;\n } catch {\n error = 'Food sources are unavailable.';\n if (acquired)\n try {\n disposePublicView(acquired);\n } catch {\n /* Shared runtime keeps a failed disposer retryable. */\n }\n }\n return () => {\n active = false;\n if (owner) closeProductView(owner);\n };\n });\n async function copyLink() {\n const selected = reference;\n if (!selected) return;\n const copied = await copyProductReference(selected.naddr, page.url.origin);\n if (!disposed && reference?.naddr === selected.naddr)\n copyNotice = copied\n ? 'Link copied.'\n : 'Copy was unavailable. Select the public link below.';\n }\n</script>\n\n<svelte:head\n ><title>{result?.food?.title ?? 'Food'} \u2014 HarvestCircle</title></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a href={internalHref('/search')}>Search food</a>\n <h1>{result?.food?.title ?? 'Food'}</h1>\n {#if !reference}<p class=\"notice\">This food reference is invalid.</p>\n {:else if error || result?.outcome === 'unavailable'}<p class=\"notice\">\n Food sources are unavailable.\n </p>\n {:else if !result || result.outcome === 'checking'}<p>\n Checking food sources\u2026\n </p>\n {:else if result.outcome === 'unobserved'}<p class=\"notice\">\n This listing was not observed in the sources checked. It may be\n unavailable or missing from these sources.\n </p>\n {:else if result.outcome === 'withdrawn'}<p class=\"notice\">\n This listing was withdrawn by its publisher.\n </p>\n {:else if result.outcome === 'unsupported'}<p class=\"notice\">\n The latest known listing uses an unsupported food format.\n </p>\n {:else if result.outcome === 'future_quarantined' || result.outcome === 'clock_unavailable'}<p\n class=\"notice\"\n >\n Listing time could not be confirmed. Food details are unavailable.\n </p>{/if}\n {#if result}\n <PublisherIdentity publisher={result.publisher} />\n {#if result.lastKnown}<p class=\"notice\">\n This is last-known information. The listing status check is incomplete.\n </p>{/if}\n {#if result.food && result.createdAt !== undefined}<ListingFacts\n food={result.food}\n createdAt={result.createdAt}\n />{/if}\n {#if result.outcome === 'sold'}<p class=\"notice\">\n The seller marked this listing sold.\n </p>{/if}\n {#if result.outcome === 'active'}<p>\n Confirm availability with the seller.\n </p>\n {/if}\n {#if productOwner}<ProductEnquiry\n view={productOwner}\n observation={result}\n />{/if}\n {#if productOwner && result.eventId}\n <Disclosure summary=\"Publisher controls\"\n ><PublisherHide view={productOwner} /></Disclosure\n >\n {/if}\n <Disclosure summary=\"Listing and source details\">\n {#if result.eventId}<p>\n Listing version: <code>{result.eventId}</code>\n </p>{/if}\n {#each result.sources as source (source.result.context)}<p>\n {source.kind}: {source.state}. Coverage: {source.result.coverage}.\n </p>\n {#each source.result.sources as relay (relay.source)}<p>\n {relay.source}: {relay.state}.\n </p>{/each}{/each}\n <p>\n These bounded checks do not prove complete coverage or current stock.\n </p>\n </Disclosure>\n {#if contact && result.outcome === 'active'}<Disclosure\n summary=\"Other contact details\"\n ><a href={navigationHref(contact.href)}>{contact.href}</a></Disclosure\n >{/if}\n {/if}\n {#if reference}<Button label=\"Copy link\" onclick={copyLink} /><a\n href={internalHref(`/products/${reference.naddr}`)}>Public food link</a\n >{/if}\n {#if copyNotice}<p role=\"status\">{copyNotice}</p>{/if}\n <a href={internalHref('/privacy')}>Privacy and local publisher controls</a>\n</div>\n", 231 sha256: 232 'd3afe029ad6ed6384a300ad6719f32c324a1841271eddf9baee5b8f31f54e680' 233 }, 234 'src/lib/components/ConversationOptions.svelte': { 235 source: 236 "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import {\n subscribeInboxView,\n blockInboxConversation,\n type InboxView\n } from '../messaging/inbox-view.ts';\n import {\n conversationOptionsSnapshot,\n requestConversationOption\n } from '../messaging/cited-product.ts';\n let {\n controller,\n conversationId,\n onblock,\n onreport\n }: {\n controller: InboxView;\n conversationId: string;\n onblock?: (peer: string) => void;\n onreport?: (peer: string) => void;\n } = $props();\n let revision = $state(0);\n let reviewing = $state(false),\n busy = $state(false),\n notice = $state<string | undefined>();\n async function confirmBlock() {\n if (!reviewing || busy) return;\n busy = true;\n const result = await blockInboxConversation(\n controller,\n conversationId,\n 'reviewed_local_private_block'\n );\n busy = false;\n reviewing = false;\n notice =\n result.status === 'saved' || result.status === 'existing'\n ? 'Person blocked in this browser.'\n : 'Block was not confirmed. Existing local data has not been reset.';\n }\n const actual = $derived.by(() => {\n void revision;\n return conversationOptionsSnapshot(controller, conversationId);\n });\n onMount(() =>\n subscribeInboxView(controller, () => {\n revision++;\n })\n );\n</script>\n\n{#if actual}\n <details>\n <summary>Identity and conversation options</summary>\n <p>Authenticated conversation peer: {actual.peer}</p>\n <button\n type=\"button\"\n onclick={() => {\n if (onblock)\n requestConversationOption(\n controller,\n conversationId,\n 'block',\n onblock,\n 'reviewed_conversation_option'\n );\n else reviewing = true;\n }}>Block person</button\n >\n {#if reviewing}\n <p>\n Blocking hides messages and previews for this account in this browser\n and may discard unsaved private text. Encrypted evidence, delivery\n receipts and remote copies remain. It sends no report or sender\n notification and does not accept or reject an order. Undo is available\n in Privacy.\n </p>\n <button type=\"button\" disabled={busy} onclick={() => void confirmBlock()}\n >Confirm local block</button\n >\n <button\n type=\"button\"\n disabled={busy}\n onclick={() => {\n reviewing = false;\n }}>Cancel</button\n >\n {/if}\n {#if notice}<p role=\"status\">{notice}</p>{/if}\n {#if onreport}<button\n type=\"button\"\n onclick={() => {\n if (onreport)\n requestConversationOption(\n controller,\n conversationId,\n 'report',\n onreport,\n 'reviewed_conversation_option'\n );\n }}>Report conversation</button\n >{/if}\n </details>\n{/if}\n", 237 sha256: 238 'b40915c0b11456fbc852d67591fd4c629a33d5b271e79b79dd042fcf2c0f74cb' 239 } 240 }, 241 ...{ 242 'src/lib/runtime/identity-session.ts': { 243 source: 244 "import {\n createExtensionAdapter,\n extensionSnapshot,\n connectExtensionAdapter,\n recheckExtensionAdapter,\n probeExtensionAdapter,\n disconnectExtensionAdapter,\n extensionOwnershipCapture,\n extensionMessagingOwnershipCapture,\n subscribeExtensionInvalidation,\n signApprovedExtensionAdapter,\n markApprovedSigningWaitExpired,\n type ApprovedSignResult,\n type ExtensionAdapter,\n type ExtensionSnapshot,\n type ExtensionGuestReason\n} from '../nostr/extension.ts';\nimport { approveCapturedPublicSigning } from '../nostr/approved-signing.ts';\nimport {\n publicRecordSnapshot,\n publicRecordWire,\n type PublicRecordHandle\n} from '../persistence/records.ts';\nimport {\n stopPublicEffect,\n type PublicEffectLease,\n type PublicEffectCapture\n} from './effect-ownership.ts';\nimport {\n bindLatePublicResponse,\n latePublicResultIdentity,\n reviewLatePublicArtifact,\n type LatePublicArtifact\n} from './late-results.ts';\nimport {\n capturedArtifactSnapshot,\n type CapturedArtifact\n} from '../persistence/artifact-records.ts';\n\ndeclare const sessionBrand: unique symbol;\nexport type IdentitySession = Readonly<{ [sessionBrand]: true }>;\nexport type IdentitySnapshot = (\n | Readonly<{ state: 'guest'; reason: ExtensionGuestReason }>\n | Readonly<{ state: 'pending'; action: 'connect' | 'recheck' | 'probe' }>\n | Readonly<{\n state: 'connected' | 'signing_only' | 'messaging_capable';\n publicKey: string;\n messaging: 'not_probed' | 'unsupported' | 'refused' | 'capable';\n }>\n) &\n Readonly<{ admission?: 'busy' }>;\n// Per-client opaque session, never a module-global server user. A public key is\n// an extension observation, not installed-account or publishing authorization.\nconst sessions = new WeakMap<IdentitySession, ExtensionAdapter>();\ntype ViewController = { stamp(): symbol; invalidate(): void };\nconst views = new WeakMap<IdentitySession, ViewController>();\ndeclare const operationBrand: unique symbol;\nexport type IdentityPublicOperation = Readonly<{ [operationBrand]: true }>;\ntype OperationController = {\n session: IdentitySession;\n ownership(): PublicEffectCapture | undefined;\n sign(lease: PublicEffectLease): Promise<ApprovedSignResult>;\n stop(expired: boolean): void;\n snapshot(): Readonly<{\n owner: string;\n id: string;\n revision: number;\n hash: string;\n current: boolean;\n lateAvailable: boolean;\n outcome: ApprovedSignResult['status'] | 'not_started' | 'pending';\n }>;\n review(\n record: PublicRecordHandle,\n review: unknown\n ): CapturedArtifact | undefined;\n};\nconst operations = new WeakMap<IdentityPublicOperation, OperationController>();\nexport function createIdentitySession(): IdentitySession {\n const session = Object.freeze({}) as IdentitySession;\n sessions.set(session, createExtensionAdapter());\n let stamp = Symbol();\n views.set(session, {\n stamp: () => stamp,\n invalidate() {\n stamp = Symbol();\n }\n });\n return session;\n}\nfunction mapIdentitySnapshot(snapshot: ExtensionSnapshot): IdentitySnapshot {\n if (snapshot.state !== 'connected') return { ...snapshot };\n const state: IdentitySnapshot = {\n state:\n snapshot.messaging === 'capable' && snapshot.signingCandidate\n ? 'messaging_capable'\n : snapshot.signingCandidate\n ? 'signing_only'\n : 'connected',\n publicKey: snapshot.publicKey,\n messaging: snapshot.messaging\n };\n return snapshot.admission === 'busy'\n ? { ...state, admission: 'busy' }\n : state;\n}\nexport function identitySessionSnapshot(\n session: IdentitySession\n): IdentitySnapshot {\n const adapter = sessions.get(session);\n return adapter\n ? mapIdentitySnapshot(extensionSnapshot(adapter))\n : { state: 'guest', reason: 'unavailable' };\n}\nexport async function connectIdentity(\n session: IdentitySession\n): Promise<IdentitySnapshot> {\n const adapter = sessions.get(session);\n if (adapter)\n return mapIdentitySnapshot(await connectExtensionAdapter(adapter));\n return identitySessionSnapshot(session);\n}\nexport async function recheckIdentityOwner(\n session: IdentitySession\n): Promise<IdentitySnapshot> {\n const adapter = sessions.get(session);\n if (adapter)\n return mapIdentitySnapshot(await recheckExtensionAdapter(adapter));\n return identitySessionSnapshot(session);\n}\nexport async function probeIdentityMessaging(\n session: IdentitySession,\n review: unknown\n): Promise<IdentitySnapshot> {\n const adapter = sessions.get(session);\n if (adapter)\n return mapIdentitySnapshot(await probeExtensionAdapter(adapter, review));\n return identitySessionSnapshot(session);\n}\nexport function disconnectIdentity(session: IdentitySession): void {\n views.get(session)?.invalidate();\n const adapter = sessions.get(session);\n if (adapter) disconnectExtensionAdapter(adapter);\n}\n// Internal messaging lifecycle ports. Captured observation is not an inbox\n// configuration, AUTH, private store or publication permission.\nexport function identityMessagingOwnership(\n session: IdentitySession\n): PublicEffectCapture | undefined {\n const adapter = sessions.get(session);\n return adapter && extensionMessagingOwnershipCapture(adapter);\n}\nexport function subscribeIdentityInvalidation(\n session: IdentitySession,\n listener: () => void\n): () => void {\n const adapter = sessions.get(session);\n return adapter ? subscribeExtensionInvalidation(adapter, listener) : () => {};\n}\n// Explicit route/input lifecycle event. No draft, DB, reconnect or SDK effect.\nexport function invalidateIdentityOperations(session: IdentitySession): void {\n views.get(session)?.invalidate();\n}\n// Internal public operation capability, never an unrestricted UI template signer.\n// Current-head/inbox/IDB preparation and publication retain their typed owners.\nexport function captureIdentityPublicOperation(\n session: IdentitySession,\n record: PublicRecordHandle,\n id: unknown,\n review: unknown\n): IdentityPublicOperation | undefined {\n const adapter = sessions.get(session),\n view = views.get(session);\n const captured = adapter && extensionOwnershipCapture(adapter);\n if (!adapter || !view || !captured) return undefined;\n const row = publicRecordSnapshot(record, captured.owner, id),\n recordWire = publicRecordWire(record, captured.owner, id);\n const approval = approveCapturedPublicSigning(\n record,\n captured.owner,\n id,\n review\n );\n if (\n !row ||\n !recordWire ||\n !approval ||\n row.family === 'public_draft' ||\n row.revision !== 0\n )\n return undefined;\n const owner = row.owner,\n command = row.id,\n epoch = view.stamp(),\n originalSession = captured.session;\n let stopped = false,\n pending = false;\n let lease: PublicEffectLease | undefined,\n late: LatePublicArtifact | undefined;\n let outcome: ApprovedSignResult['status'] | 'not_started' | 'pending' =\n 'not_started';\n const current = () =>\n !stopped && view.stamp() === epoch && captured.current();\n const token = Object.freeze({}) as IdentityPublicOperation;\n operations.set(token, {\n session,\n ownership: () =>\n current() ? { owner, session: originalSession, current } : undefined,\n async sign(originalLease) {\n if (pending) return { status: 'busy' };\n if (!current()) return { status: 'stale' };\n pending = true;\n lease = originalLease;\n outcome = 'pending';\n try {\n let result = await signApprovedExtensionAdapter(\n adapter,\n approval,\n originalLease\n );\n // The adapter's promise can settle before this continuation runs.\n // Recheck this view before disclosing a normal signed result.\n if (result.status === 'signed' && !current()) {\n const artifact = capturedArtifactSnapshot(result.artifact);\n const originalLate =\n artifact &&\n bindLatePublicResponse(\n approval,\n JSON.parse(artifact.wire),\n originalSession\n );\n result = originalLate\n ? { status: 'unknown', late: originalLate }\n : { status: 'unknown' };\n }\n outcome = result.status;\n if (result.status === 'unknown' && result.late) {\n const original = latePublicResultIdentity(result.late);\n if (\n original?.owner === owner &&\n original.id === command &&\n original.recordWire === recordWire &&\n original.session === originalSession\n )\n late = result.late;\n }\n // Only disclosure/explicit original-operation review can obtain a late\n // artifact. A normal signing result never returns it after invalidation.\n return result.status === 'unknown' ? { status: 'unknown' } : result;\n } finally {\n pending = false;\n lease = undefined;\n }\n },\n stop(expired) {\n stopped = true;\n if (lease) {\n if (expired) markApprovedSigningWaitExpired(adapter, approval, lease);\n stopPublicEffect(lease);\n }\n },\n snapshot: () => ({\n owner,\n id: command,\n revision: row.revision,\n hash: row.capture.hash,\n current: current(),\n lateAvailable: late !== undefined,\n outcome\n }),\n review(original, consent) {\n const observed = extensionSnapshot(adapter);\n return late &&\n observed.state === 'connected' &&\n observed.publicKey === owner\n ? reviewLatePublicArtifact(late, original, owner, command, consent)\n : undefined;\n }\n });\n return token;\n}\nfunction operationOf(session: IdentitySession, token: IdentityPublicOperation) {\n const operation = operations.get(token);\n return operation?.session === session ? operation : undefined;\n}\nexport function identityPublicOperationOwnership(\n session: IdentitySession,\n operation: IdentityPublicOperation\n): PublicEffectCapture | undefined {\n return operationOf(session, operation)?.ownership();\n}\nexport function identityPublicOperationSnapshot(\n session: IdentitySession,\n operation: IdentityPublicOperation\n) {\n return operationOf(session, operation)?.snapshot();\n}\nexport function signIdentityPublicOperation(\n session: IdentitySession,\n operation: IdentityPublicOperation,\n lease: PublicEffectLease\n): Promise<ApprovedSignResult> {\n return (\n operationOf(session, operation)?.sign(lease) ??\n Promise.resolve({ status: 'invalid_approval' })\n );\n}\nexport function stopIdentityPublicOperation(\n session: IdentitySession,\n operation: IdentityPublicOperation\n): void {\n operationOf(session, operation)?.stop(false);\n}\n// UI supplies expiry; existing scheduler owns its actual pending promise.\nexport function expireIdentityPublicOperationWait(\n session: IdentitySession,\n operation: IdentityPublicOperation\n): void {\n operationOf(session, operation)?.stop(true);\n}\n// Pure same-author original review, not fresh author/CAS/resume/publish proof.\nexport function reviewIdentityLatePublicArtifact(\n session: IdentitySession,\n operation: IdentityPublicOperation,\n original: PublicRecordHandle,\n review: unknown\n): CapturedArtifact | undefined {\n return operationOf(session, operation)?.review(original, review);\n}\n", 245 sha256: 246 '0efc6bfdea0bbcb4e6b22e2b5b9008db2b78df259d751f3557e92eedaf245274' 247 }, 248 'src/lib/runtime/public-runtime.ts': { 249 source: 250 "import { deploymentRelayPolicy } from '../config/deployment-relays.ts';\nimport type { RelayPolicy } from '../config/relays.ts';\nimport { qualifiedNip50Sources } from '../nostr/search-sources.ts';\nimport {\n getPublicPool,\n subscribePublicPool,\n closePublicPool,\n type PublicPool\n} from '../nostr/public-pool.ts';\nimport {\n getPublicStore,\n insertPublicEnvelope,\n closePublicStore,\n publicStoreRetention,\n publicStoreKnownEvidence,\n publicStoreEnvelope,\n type PublicStore\n} from '../nostr/public-store.ts';\nimport {\n createPublicScheduler,\n createPublicRun,\n openPublicRequest,\n openInboxRequest,\n disposePublicRun,\n closePublicScheduler,\n publicRunSnapshot,\n type PublicScheduler,\n type PublicRun,\n type PublicRequest,\n type RequestKind,\n type RequestClock\n} from '../nostr/request-scope.ts';\nimport type { PublicFilter } from '../nostr/exports.ts';\nimport { inboxPreferenceQueries } from '../nostr/inbox-queries.ts';\nimport {\n publicHeadEnvelope,\n publicHeadSnapshot,\n type PublicHead\n} from '../catalog/heads.ts';\nimport type { KnownPublicEvidence } from '../catalog/retention.ts';\nimport type { VerifiedEnvelope } from '../nostr/verified-envelope.ts';\ndeclare const contextBrand: unique symbol;\ndeclare const runtimeBrand: unique symbol;\ndeclare const viewBrand: unique symbol;\nexport type PublicRuntimeContext = Readonly<{ readonly [contextBrand]: true }>;\nexport type PublicRuntime = Readonly<{ readonly [runtimeBrand]: true }>;\nexport type PublicView = Readonly<{ readonly [viewBrand]: true }>;\nexport const PUBLIC_RUNTIME_CONTEXT = 'harvestcircle_public_runtime';\ninterface RuntimeOwner {\n readonly pool: PublicPool;\n readonly store: PublicStore;\n readonly scheduler: PublicScheduler;\n readonly policy: RelayPolicy;\n readonly views: Map<PublicView, () => boolean>;\n readonly closed: () => boolean;\n readonly projectionValid: (retry?: boolean) => boolean;\n readonly invalidateProjection: () => void;\n readonly close: () => void;\n}\ninterface ContextOwner {\n readonly value: () => PublicRuntime | undefined;\n readonly mount: (\n policy: RelayPolicy,\n clock?: RequestClock\n ) => PublicRuntime | undefined;\n readonly ready: Promise<PublicRuntime | undefined>;\n readonly close: () => void;\n}\ninterface ViewOwner {\n readonly runtime: RuntimeOwner;\n readonly begin: () => PublicRun;\n readonly current: (run: PublicRun) => boolean;\n readonly settling: () => boolean;\n readonly settleWith: (refresh: () => void) => void;\n readonly dispose: () => boolean;\n}\nconst contexts = new WeakMap<PublicRuntimeContext, ContextOwner>(),\n runtimes = new WeakMap<PublicRuntime, RuntimeOwner>(),\n views = new WeakMap<PublicView, ViewOwner>();\nlet browserContext: PublicRuntimeContext | undefined;\nfunction contextOf(token: PublicRuntimeContext): ContextOwner {\n const owner = contexts.get(token);\n if (!owner) throw new Error('public_runtime_context_invalid');\n return owner;\n}\nfunction runtimeOf(token: PublicRuntime): RuntimeOwner {\n const owner = runtimes.get(token);\n if (!owner) throw new Error('public_runtime_invalid');\n if (owner.closed()) throw new Error('public_runtime_closed');\n return owner;\n}\nfunction viewOf(token: PublicView): ViewOwner {\n const owner = views.get(token);\n if (!owner) throw new Error('public_view_invalid');\n return owner;\n}\n// Context construction is SSR-pure. Root onMount acquires the browser lifetime;\n// children can await readiness even when their onMount runs before the root's.\nexport function createPublicRuntimeContext(): PublicRuntimeContext {\n let value: PublicRuntime | undefined,\n closed = false;\n let ready: (value: PublicRuntime | undefined) => void = () => {};\n let selectedClock: RequestClock | undefined;\n const promise = new Promise<PublicRuntime | undefined>((resolve) => {\n ready = resolve;\n });\n const owner: ContextOwner = {\n value: () => (closed ? undefined : value),\n ready: promise,\n mount(policy, clock) {\n if (closed) throw new Error('public_runtime_closed');\n if (typeof window === 'undefined') return undefined;\n if (value) {\n const prior = runtimes.get(value);\n if (!prior || prior.policy !== policy)\n throw new Error('public_runtime_policy_changed');\n if (clock !== selectedClock)\n throw new Error('public_runtime_clock_changed');\n return value;\n }\n if (browserContext && browserContext !== contextToken)\n throw new Error('public_runtime_owner_changed');\n const pool = getPublicPool(policy),\n store = getPublicStore();\n if (!pool || !store) return undefined;\n const scheduler = createPublicScheduler(clock),\n registered = new Map<PublicView, () => boolean>();\n let terminal = false,\n invalidated = false,\n invalidating = false;\n const token = Object.freeze({}) as PublicRuntime;\n const runtime: RuntimeOwner = {\n pool,\n store,\n scheduler,\n policy,\n views: registered,\n closed: () => terminal,\n projectionValid(retry = true) {\n const retained = publicStoreRetention(store);\n if (retained.stopped || (!terminal && retained.closed))\n invalidated = true;\n // A settler reads the terminal flag without recursively retrying its\n // own disposal. The outer cleanup loop keeps failed controls live.\n if (invalidated && retry) runtime.invalidateProjection();\n return !invalidated;\n },\n invalidateProjection() {\n invalidated = true;\n if (invalidating) return;\n invalidating = true;\n let failed = false;\n try {\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n } finally {\n invalidating = false;\n }\n if (failed) throw new Error('public_projection_close_failed');\n },\n close() {\n terminal = true;\n let failed = false;\n for (const dispose of registered.values())\n if (!dispose()) failed = true;\n // Reentrant or failed settlement cannot preserve a coherent projection\n // across store teardown. Terminal uncertainty clears every view.\n if (failed) invalidated = true;\n try {\n closePublicScheduler(scheduler);\n } catch {\n failed = true;\n }\n try {\n closePublicPool(pool);\n } catch {\n failed = true;\n }\n try {\n closePublicStore(store);\n } catch {\n failed = true;\n }\n if (failed) throw new Error('public_runtime_close_failed');\n }\n };\n runtimes.set(token, runtime);\n value = token;\n browserContext = contextToken;\n selectedClock = clock;\n ready(token);\n return token;\n },\n close() {\n closed = true;\n ready(undefined);\n if (value) {\n const runtime = runtimes.get(value);\n if (runtime) runtime.close();\n }\n }\n };\n const contextToken = Object.freeze({}) as PublicRuntimeContext;\n contexts.set(contextToken, owner);\n return contextToken;\n}\nexport function publicRuntime(\n context: PublicRuntimeContext\n): PublicRuntime | undefined {\n return contextOf(context).value();\n}\nexport function publicRuntimeReady(\n context: PublicRuntimeContext\n): Promise<PublicRuntime | undefined> {\n return contextOf(context).ready;\n}\n// Original runtime policy observation only, never a pool or effect capability.\nexport function publicRuntimePolicy(\n runtime: PublicRuntime\n): RelayPolicy | undefined {\n try {\n const owner = runtimeOf(runtime);\n return !owner.closed() && owner.projectionValid()\n ? owner.policy\n : undefined;\n } catch {\n return;\n }\n}\nexport function mountPublicRuntime(\n context: PublicRuntimeContext,\n policy: RelayPolicy = deploymentRelayPolicy,\n clock?: RequestClock\n): PublicRuntime | undefined {\n return contextOf(context).mount(policy, clock);\n}\nexport function closePublicRuntime(context: PublicRuntimeContext): void {\n contextOf(context).close();\n}\nexport function createPublicView(runtime: PublicRuntime): PublicView {\n const shared = runtimeOf(runtime);\n if (!shared.projectionValid())\n throw new Error('public_projection_unavailable');\n const token = Object.freeze({}) as PublicView;\n let run: PublicRun | undefined,\n disposed = false;\n let generation = 0,\n settler: (() => void) | undefined,\n settling = false;\n function settle() {\n const refresh = settler;\n settler = undefined; // Detach before any caller-controlled clock reentry.\n if (!refresh) return;\n settling = true;\n try {\n refresh?.();\n } catch (error) {\n if (!settler) settler = refresh;\n throw error;\n } finally {\n settling = false;\n }\n }\n const owner: ViewOwner = {\n runtime: shared,\n begin() {\n if (disposed || shared.closed() || !shared.projectionValid())\n throw new Error('public_view_closed');\n const operation = ++generation,\n previous = run;\n // Generation reserves the transition; keep failed old controls retryable.\n try {\n settle();\n } finally {\n if (previous) disposePublicRun(previous);\n }\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n )\n throw new Error('public_view_run_superseded');\n const candidate = createPublicRun(shared.scheduler, shared.policy);\n // Run creation samples the injected clock. It may synchronously start a\n // newer view generation before returning; never overwrite that owner.\n if (\n operation !== generation ||\n disposed ||\n shared.closed() ||\n !shared.projectionValid()\n ) {\n disposePublicRun(candidate);\n throw new Error('public_view_run_superseded');\n }\n run = candidate;\n return run;\n },\n settling: () => settling,\n settleWith(refresh) {\n const previous = settler;\n settler = refresh;\n previous?.();\n },\n current(candidate) {\n return !disposed && !shared.closed() && run === candidate;\n },\n dispose() {\n disposed = true;\n generation++;\n if (settling) return false;\n try {\n settle();\n if (run) disposePublicRun(run);\n shared.views.delete(token);\n return true;\n } catch {\n return false;\n }\n }\n };\n views.set(token, owner);\n shared.views.set(token, () => owner.dispose());\n return token;\n}\nexport function beginPublicViewRun(view: PublicView): PublicRun {\n return viewOf(view).begin();\n}\nexport function publicViewRunCurrent(\n view: PublicView,\n run: PublicRun\n): boolean {\n return viewOf(view).current(run) && publicRunSnapshot(run).active;\n}\n// Ownership survives an ordinary deadline so a foreground owner can publish\n// its terminal result once. Supersession/disposal/shared closure revoke it.\nexport function publicViewOwnsRun(view: PublicView, run: PublicRun): boolean {\n return viewOf(view).current(run);\n}\nexport function disposePublicView(view: PublicView): void {\n if (!viewOf(view).dispose()) throw new Error('public_view_close_failed');\n}\nexport function subscribePublicView(\n view: PublicView,\n run: PublicRun,\n kind: RequestKind,\n filters: readonly PublicFilter[],\n onVerified: (event: VerifiedEnvelope) => void,\n sampleSource?: string\n): PublicRequest {\n const owner = viewOf(view);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n // Copy the request template once before SDK effects; caller mutations cannot\n // retarget this request. Product filter builders remain HCP038 and later.\n const frozen = JSON.stringify(filters);\n return openPublicRequest(\n run,\n kind,\n (next) =>\n subscribePublicPool(\n owner.runtime.pool,\n JSON.parse(frozen) as PublicFilter[],\n next,\n sampleSource\n ),\n (event) => {\n if (!owner.current(run)) return;\n const result = insertPublicEnvelope(owner.runtime.store, event);\n if (result === 'limit' || result === 'rejected' || result === 'closed') {\n owner.runtime.invalidateProjection();\n return;\n }\n if (\n (result === 'accepted' || result === 'duplicate') &&\n owner.current(run)\n )\n onVerified(event);\n },\n sampleSource\n );\n}\n\nexport function publicViewNip50Sources(view: PublicView): readonly string[] {\n return qualifiedNip50Sources(viewOf(view).runtime.policy);\n}\n\n// Public metadata, dedicated ownership: no preference enters the food store.\n// Fixed anonymous origins, clocks, scheduler and aggregate ingress stay shared.\nexport function subscribeInboxPreference(\n view: PublicView,\n run: PublicRun,\n author: unknown,\n onVerified: (event: VerifiedEnvelope, inboxSource?: string) => void\n): PublicRequest {\n const owner = viewOf(view),\n filters = inboxPreferenceQueries(author);\n if (!owner.current(run)) throw new Error('public_view_run_inactive');\n return openInboxRequest(\n run,\n author,\n (next) => subscribePublicPool(owner.runtime.pool, filters, next),\n (event, inboxSource) => {\n if (owner.current(run)) onVerified(event, inboxSource);\n }\n );\n}\n\n// Capacity invalidation differs from ordinary teardown: last-known snapshots\n// remain available on normal close, while a breached working set clears all views.\nexport function publicViewProjectionAvailable(view: PublicView): boolean {\n const owner = viewOf(view);\n return owner.runtime.projectionValid(!owner.settling());\n}\nexport function publicViewKnownEvidence(\n view: PublicView,\n head: PublicHead\n): KnownPublicEvidence {\n return publicStoreKnownEvidence(viewOf(view).runtime.store, head);\n}\nexport function retainPublicViewHeads(\n view: PublicView,\n run: PublicRun,\n heads: readonly PublicHead[]\n): boolean {\n const owner = viewOf(view);\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n const active = publicRunSnapshot(run).active;\n if (!owner.current(run) || !owner.runtime.projectionValid()) return false;\n if (!active) {\n // Inactive materialization cannot install or charge another event. Require\n // every genuine head to have already passed the shared retained cache.\n for (const head of heads) {\n if (\n !publicStoreEnvelope(owner.runtime.store, publicHeadSnapshot(head).id)\n )\n throw new Error('public_view_uncached_head');\n }\n return owner.current(run) && owner.runtime.projectionValid();\n }\n for (const head of heads) {\n const result = insertPublicEnvelope(\n owner.runtime.store,\n publicHeadEnvelope(head)\n );\n if (result !== 'accepted' && result !== 'duplicate') {\n owner.runtime.invalidateProjection();\n return false;\n }\n }\n return owner.runtime.projectionValid();\n}\n\n// Trusted model binding holds only the current projection for this view.\n// Replacement/disposal settles it while retained shared lifecycle proof is live.\nexport function settlePublicViewProjection(\n view: PublicView,\n refresh: () => void\n): void {\n viewOf(view).settleWith(refresh);\n}\n", 251 sha256: 252 '8d2b840e94448b55642b1481d12785ed76d326735a4461e9795f57a98e8d2530' 253 }, 254 'src/lib/catalog/product-view.ts': { 255 source: 256 "import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';\nimport {\n decodeProductReference,\n type ProductReference\n} from '../nostr/references.ts';\nimport {\n beginPublicViewRun,\n disposePublicView,\n publicViewProjectionAvailable,\n publicViewRunCurrent,\n publicViewOwnsRun,\n publicViewKnownEvidence,\n subscribePublicView,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n publicRequestScopeSnapshot,\n publicRunSnapshot,\n closePublicRequest,\n disposePublicRun,\n type PublicRequest\n} from '../nostr/request-scope.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadSnapshot,\n publicHeadEnvelope,\n selectPublicHead,\n type PublicHead\n} from './heads.ts';\nimport {\n createPublicViewHeadResolver,\n headResolutionSnapshot,\n resolveHeads,\n closeHeadResolver\n} from './resolve-head.ts';\nimport {\n createPublisherViews,\n readPublisherPage,\n publisherSnapshot,\n type PublisherView\n} from './publishers.ts';\nimport type { FoodProjection } from '../contracts/food-availability-v1/read.ts';\nimport type { VerifiedEnvelope } from '../nostr/verified-envelope.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport type { ForegroundSchedule } from './search-view.ts';\nexport type ProductViewSnapshot = Readonly<{\n reference: ProductReference;\n outcome:\n | 'checking'\n | 'unobserved'\n | 'unavailable'\n | 'active'\n | 'sold'\n | 'withdrawn'\n | 'unsupported'\n | 'future_quarantined'\n | 'clock_unavailable';\n food: FoodProjection | undefined;\n eventId: string | undefined;\n createdAt: number | undefined;\n publisher: PublisherView;\n lastKnown: boolean;\n sources: readonly ReturnType<typeof publicRequestScopeSnapshot>[];\n}>;\ndeclare const productBrand: unique symbol;\nexport type ProductView = Readonly<{ readonly [productBrand]: true }>;\ndeclare const acknowledgementBrand: unique symbol;\nexport type ProductStatusAcknowledgement = Readonly<{\n readonly [acknowledgementBrand]: true;\n}>;\nconst acknowledgements = new WeakMap<\n ProductStatusAcknowledgement,\n { view: ProductView; current(this: void): boolean }\n>();\ninterface Owner {\n snapshot: () => ProductViewSnapshot;\n listing: (\n acknowledgement?: ProductStatusAcknowledgement\n ) => ProductListingOwnership | undefined;\n acknowledge: (review: unknown) => ProductStatusAcknowledgement | undefined;\n close: () => void;\n}\nexport type ProductListingOwnership = Readonly<{\n proof: VerifiedEnvelope;\n available: () => boolean;\n current: () => boolean;\n}>;\nconst owners = new WeakMap<ProductView, Owner>();\nfunction ownerOf(token: ProductView): Owner {\n const owner = owners.get(token);\n if (!owner) throw Error('product_view_invalid');\n return owner;\n}\nfunction foreground(callback: () => void, delay: number): () => void {\n const timer = setTimeout(() => {\n callback();\n }, delay);\n return () => {\n clearTimeout(timer);\n };\n}\n// One explicit route read, one coordinate, shared run/request budgets. No forged\n// seed, independent cache, relay hints, automatic refresh or additional deadline.\nexport function createProductView(\n view: PublicView,\n value: unknown,\n clock: WallClock,\n onUpdate: (value: ProductViewSnapshot) => void,\n schedule: ForegroundSchedule = foreground\n): ProductView {\n const decoded = decodeProductReference(value);\n if (!decoded) throw Error('product_reference_invalid');\n const reference = decoded;\n const run = beginPublicViewRun(view),\n resolver = createPublicViewHeadResolver(view, run, clock),\n publishers = createPublisherViews(view, clock);\n let closed = false,\n failed = false,\n head: PublicHead | undefined,\n cancel: (() => void) | undefined;\n const requests = new Map<PublicRequest, true>();\n const current = () => !closed && publicViewRunCurrent(view, run);\n function snapshot(): ProductViewSnapshot {\n const available =\n !closed &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n const row = available ? headResolutionSnapshot(resolver)[0] : undefined;\n let scopes = Array.from(requests.keys(), publicRequestScopeSnapshot);\n for (const scope of [row?.headSources, row?.deletionSources])\n if (\n scope &&\n !scopes.some((s) => s.result.context === scope.result.context)\n )\n scopes = scopes.concat(scope);\n const complete =\n !failed &&\n scopes.length > 0 &&\n scopes.every(\n (s) => s.state === 'eose' && s.result.coverage === 'bounded-eose'\n );\n let outcome: ProductViewSnapshot['outcome'];\n if (!available) outcome = 'unavailable';\n else if (row?.deletion.outcome === 'suppressed') outcome = 'withdrawn';\n else if (\n row?.state.display === 'future_quarantined' ||\n row?.state.display === 'clock_unavailable'\n )\n outcome = row.state.display;\n else if (row?.state.display === 'unsupported') outcome = 'unsupported';\n else if (row?.state.food) outcome = row.state.food.status;\n else if (\n !row &&\n (failed ||\n (scopes.length > 0 &&\n scopes.every(\n (scope) =>\n scope.result.sources.length > 0 &&\n scope.result.sources.every(\n (source) =>\n source.state === 'error' || source.state === 'closed'\n )\n )))\n )\n outcome = 'unavailable';\n else\n outcome =\n current() && scopes.some((s) => s.state === 'active')\n ? 'checking'\n : 'unobserved';\n const publisher = publisherSnapshot(publishers, reference.pubkey);\n const stillAvailable =\n !closed &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n return {\n reference: { ...reference },\n outcome: stillAvailable ? outcome : 'unavailable',\n food: stillAvailable ? row?.state.food : undefined,\n eventId: stillAvailable ? row?.state.head.id : undefined,\n createdAt: stillAvailable ? row?.state.head.created_at : undefined,\n publisher: stillAvailable\n ? publisher\n : {\n pubkey: reference.pubkey,\n label: reference.pubkey,\n assertedName: false\n },\n lastKnown: !stillAvailable || !complete || (row?.lastKnown ?? true),\n sources: scopes\n };\n }\n function publish() {\n const value = snapshot();\n if (!closed && publicViewOwnsRun(view, run)) onUpdate(value);\n }\n function queue() {\n if (!current() || publicRunSnapshot(run).activeRequests === 0) return;\n const next = schedule(() => {\n if (closed || !publicViewOwnsRun(view, run)) return;\n cancel = undefined;\n publish();\n queue();\n }, 250);\n if (current()) cancel = next;\n else next();\n }\n const token = Object.freeze({}) as ProductView;\n function coverageKey(observed: ProductViewSnapshot) {\n return JSON.stringify({\n runCurrent: publicViewRunCurrent(view, run),\n outcome: observed.outcome,\n eventId: observed.eventId,\n lastKnown: observed.lastKnown,\n sources: observed.sources.map((scope) => ({\n context: scope.result.context,\n state: scope.state,\n coverage: scope.result.coverage,\n sources: scope.result.sources.map(({ source, state }) => ({\n source,\n state\n }))\n }))\n });\n }\n owners.set(token, {\n snapshot,\n acknowledge(review) {\n const observed = snapshot();\n if (\n review !== 'reviewed_last_known_listing' ||\n observed.outcome !== 'active' ||\n !observed.lastKnown ||\n !observed.eventId ||\n !head ||\n closed\n )\n return;\n const key = coverageKey(observed);\n const consent = Object.freeze({}) as ProductStatusAcknowledgement;\n acknowledgements.set(consent, {\n view: token,\n current: () =>\n !closed &&\n publicViewOwnsRun(view, run) &&\n publicViewProjectionAvailable(view) &&\n coverageKey(snapshot()) === key\n });\n return consent;\n },\n listing(acknowledgement) {\n const observed = snapshot();\n const capturedConsent =\n acknowledgement && acknowledgements.get(acknowledgement);\n const consent =\n capturedConsent?.view === token ? capturedConsent.current : undefined;\n if (\n observed.outcome !== 'active' ||\n (observed.lastKnown && !consent?.()) ||\n !head\n )\n return;\n const selected = publicViewKnownEvidence(view, head).head;\n const metadata = publicHeadSnapshot(selected);\n if (\n metadata.id !== observed.eventId ||\n metadata.pubkey !== reference.pubkey ||\n metadata.identifier !== reference.identifier\n )\n return;\n return {\n proof: publicHeadEnvelope(selected),\n available: () =>\n !closed &&\n publicViewOwnsRun(view, run) &&\n publicViewProjectionAvailable(view),\n current() {\n const actual = snapshot();\n return (\n !closed &&\n actual.outcome === 'active' &&\n (!actual.lastKnown || !!consent?.()) &&\n actual.eventId === metadata.id\n );\n }\n };\n },\n close() {\n const notifyTerminal = !closed;\n closed = true;\n const previous = cancel;\n cancel = undefined;\n previous?.();\n let error = false;\n try {\n closeHeadResolver(resolver);\n } catch {\n error = true;\n }\n try {\n if (publicViewOwnsRun(view, run)) disposePublicView(view);\n else disposePublicRun(run);\n } catch {\n error = true;\n }\n if (notifyTerminal)\n try {\n onUpdate(snapshot());\n } catch {\n /* Terminal observer cannot prevent original revocation/cleanup. */\n }\n if (error) throw Error('product_view_close_failed');\n }\n });\n try {\n const filter =\n reference.identifier === ''\n ? {\n kinds: [30402],\n authors: [reference.pubkey],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n : {\n kinds: [30402],\n authors: [reference.pubkey],\n '#d': [reference.identifier],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n };\n const request = subscribePublicView(\n view,\n run,\n 'head',\n [filter],\n (proof) => {\n if (!current()) return;\n const candidate = createPublicHeadCandidate(proof);\n if (!candidate) return;\n const next = publicHeadSnapshot(candidate);\n if (\n next.kind !== 30402 ||\n next.pubkey !== reference.pubkey ||\n next.identifier !== reference.identifier\n )\n return;\n head = selectPublicHead(head, candidate).head;\n try {\n resolveHeads(resolver, [head]);\n if (current())\n for (const request of readPublisherPage(publishers, run, [\n reference.pubkey\n ]))\n requests.set(request, true);\n } catch {\n failed = true;\n }\n }\n );\n requests.set(request, true);\n if (publicRequestScopeSnapshot(request).result.sources.length === 0) {\n failed = true;\n closePublicRequest(request);\n }\n } catch {\n failed = true;\n }\n publish();\n queue();\n return token;\n}\nexport function productViewSnapshot(token: ProductView): ProductViewSnapshot {\n return ownerOf(token).snapshot();\n}\nexport function closeProductView(token: ProductView): void {\n ownerOf(token).close();\n}\n// Only the original current view resolves the observed signed proof. Detached\n// UI snapshots cannot create this witness or select another author/version.\nexport function productViewListingOwnership(\n token: ProductView,\n acknowledgement?: ProductStatusAcknowledgement\n): ProductListingOwnership | undefined {\n return owners.get(token)?.listing(acknowledgement);\n}\nexport function acknowledgeProductViewUncertainty(\n token: ProductView,\n review: unknown\n): ProductStatusAcknowledgement | undefined {\n return owners.get(token)?.acknowledge(review);\n}\n", 257 sha256: 258 'c2562d1470282c758889e9855f7e7e6c32a6b2eb090e4dace2e94fdfdb6d8363' 259 }, 260 'src/lib/catalog/search-run.ts': { 261 source: 262 "import {\n orderFoodRows,\n listingView,\n type ListingView\n} from './listing-view.ts';\nimport {\n createPublisherViews,\n readPublisherPage,\n publisherSnapshot,\n type PublisherViews\n} from './publishers.ts';\nimport {\n PUBLIC_QUERY_BUDGETS,\n PUBLIC_SEARCH_BUDGETS,\n PUBLIC_SEARCH_RUN_BUDGETS\n} from '../config/budgets.ts';\nimport type { PublicFilter } from '../nostr/exports.ts';\nimport { headResolutionQueries } from '../nostr/product-queries.ts';\nimport {\n publicRunSnapshot,\n publicRunObservations,\n publicRequestScopeSnapshot,\n closePublicRequest,\n cancelPublicRun,\n type PublicRun,\n type PublicRequest\n} from '../nostr/request-scope.ts';\nimport {\n beginPublicViewRun,\n publicViewRunCurrent,\n publicViewProjectionAvailable,\n publicViewNip50Sources,\n subscribePublicView,\n disposePublicView,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadKey,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from './heads.ts';\nimport { normalizePublicQuery } from './query-input.ts';\nimport {\n createPublicViewHeadResolver,\n resolveHeads,\n resolveKnownHeads,\n headResolutionSnapshot,\n type HeadResolver\n} from './resolve-head.ts';\nimport { searchResolvedFood } from './search-match.ts';\nimport {\n searchRefreshState,\n type SearchScope,\n type SearchSnapshot\n} from './search-state.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport { nip50SearchQuery } from '../nostr/search-query.ts';\nimport {\n chronologicalSearchQuery,\n requireChronologicalSearchQuery\n} from '../nostr/chronological-query.ts';\nimport {\n createChronologicalContinuation,\n localSearchPage,\n type ChronologicalContinuation,\n type ChronologicalWindow\n} from './continuation.ts';\ndeclare const coordinatorBrand: unique symbol;\ndeclare const generationBrand: unique symbol;\nexport type FoodSearchCoordinator = Readonly<{\n readonly [coordinatorBrand]: true;\n}>;\nexport type FoodSearchRun = Readonly<{ readonly [generationBrand]: true }>;\ninterface Coordinator {\n readonly view: PublicView;\n readonly publishers: PublisherViews;\n readonly clock: WallClock;\n readonly current: () => FoodSearchRun | undefined;\n readonly reserve: (token: FoodSearchRun) => void;\n readonly closed: () => boolean;\n readonly close: () => void;\n}\ninterface Session {\n readonly coordinator: Coordinator;\n readonly token: FoodSearchRun;\n readonly query: string;\n readonly heads: () => readonly PublicHead[];\n readonly pending: () => readonly PublicHead[];\n readonly resolved: (heads: readonly PublicHead[]) => void;\n readonly remember: (head: PublicHead) => boolean;\n readonly requests: () => readonly PublicRequest[];\n readonly track: (request: PublicRequest) => void;\n readonly reserveSource: () => void;\n readonly reserveSample: () => void;\n readonly continuation: () => ChronologicalContinuation;\n readonly bindContinuation: (value: ChronologicalContinuation) => void;\n readonly chronological: () => readonly (readonly [\n PublicRequest,\n ChronologicalWindow\n ])[];\n readonly trackChronological: (\n request: PublicRequest,\n window: ChronologicalWindow\n ) => void;\n readonly pages: () => number;\n readonly showMore: () => void;\n readonly run: () => PublicRun | undefined;\n readonly bindRun: (run: PublicRun) => void;\n readonly model: () => HeadResolver | undefined;\n readonly bindModel: (model: HeadResolver) => void;\n readonly flags: () => Readonly<{\n cancelled: boolean;\n failed: boolean;\n capped: boolean;\n }>;\n readonly cap: () => void;\n readonly fail: () => void;\n readonly cancel: () => void;\n}\nconst coordinators = new WeakMap<FoodSearchCoordinator, Coordinator>();\nconst viewCoordinators = new WeakMap<\n PublicView,\n Readonly<{ clock: WallClock; token: FoodSearchCoordinator }>\n>();\nconst sessions = new WeakMap<FoodSearchRun, Session>();\nfunction coordinatorOf(token: FoodSearchCoordinator): Coordinator {\n const owner = coordinators.get(token);\n if (!owner) throw new Error('food_search_coordinator_invalid');\n return owner;\n}\nfunction sessionOf(token: FoodSearchRun): Session {\n const session = sessions.get(token);\n if (!session) throw new Error('food_search_invalid');\n return session;\n}\nfunction current(session: Session): boolean {\n return (\n !session.coordinator.closed() &&\n session.coordinator.current() === session.token\n );\n}\nfunction requireCurrent(session: Session): void {\n if (!current(session)) throw new Error('food_search_superseded');\n}\n// All mutation stays in lexical plain-model owners; callers get opaque handles\n// and detached snapshots, never map-returned mutable records or SDK objects.\nfunction createSession(\n coordinator: Coordinator,\n token: FoodSearchRun,\n query: string,\n seed: readonly PublicHead[],\n fallback: HeadResolver | undefined\n): Session {\n const heads = new Map(seed.map((head) => [publicHeadKey(head), head]));\n const resolved = new Map<string, true>();\n const requests = new Map<PublicRequest, true>();\n let run: PublicRun | undefined,\n model = fallback;\n let cancelled = false,\n failed = false,\n capped = false;\n let attempts = 0;\n let sampleRounds = 0;\n let chronological = createChronologicalContinuation(),\n pages = 1;\n const windows = new Map<PublicRequest, ChronologicalWindow>();\n return {\n coordinator,\n token,\n query,\n heads: () => Array.from(heads.values()),\n pending: () =>\n Array.from(heads.values()).filter(\n (head) => !resolved.has(publicHeadKey(head))\n ),\n resolved: (values) => {\n for (const head of values) resolved.set(publicHeadKey(head), true);\n },\n remember(head) {\n const key = publicHeadKey(head);\n if (\n !heads.has(key) &&\n heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun\n ) {\n capped = true;\n return false;\n }\n heads.set(key, selectPublicHead(heads.get(key), head).head);\n return true;\n },\n requests: () => Array.from(requests.keys()),\n track: (request) => {\n requests.set(request, true);\n },\n reserveSource() {\n if (attempts >= PUBLIC_SEARCH_RUN_BUDGETS.primaryScopes) {\n capped = true;\n throw new Error('food_search_primary_limit');\n }\n attempts++;\n },\n reserveSample() {\n if (sampleRounds >= PUBLIC_SEARCH_RUN_BUDGETS.nip50Rounds)\n throw new Error('food_search_sample_round_limit');\n sampleRounds++;\n },\n continuation: () => chronological,\n bindContinuation: (value) => {\n chronological = value;\n },\n chronological: () => Array.from(windows.entries()),\n trackChronological: (request, window) => {\n windows.set(request, window);\n },\n pages: () => pages,\n showMore: () => {\n pages = Math.min(\n Math.ceil(\n PUBLIC_QUERY_BUDGETS.coordinatesPerRun /\n PUBLIC_SEARCH_BUDGETS.pageRows\n ),\n pages + 1\n );\n },\n run: () => run,\n bindRun: (value) => {\n run = value;\n },\n model: () => model,\n bindModel: (value) => {\n model = value;\n },\n flags: () => ({ cancelled, failed, capped }),\n cap: () => {\n capped = true;\n },\n fail: () => {\n failed = true;\n },\n cancel() {\n cancelled = true;\n if (run) cancelPublicRun(run);\n }\n };\n}\nexport function createFoodSearchCoordinator(\n view: PublicView,\n clock: WallClock\n): FoodSearchCoordinator {\n publicViewProjectionAvailable(view);\n if (typeof clock.nowSeconds !== 'function')\n throw new Error('food_search_clock_invalid');\n const existing = viewCoordinators.get(view);\n if (existing) {\n if (existing.clock !== clock) throw new Error('food_search_clock_changed');\n return existing.token;\n }\n const token = Object.freeze({}) as FoodSearchCoordinator;\n let generation: FoodSearchRun | undefined,\n closed = false;\n coordinators.set(token, {\n view,\n publishers: createPublisherViews(view, clock),\n clock,\n current: () => generation,\n reserve: (value) => {\n generation = value;\n },\n closed: () => closed,\n close() {\n closed = true;\n // Preserve failed cleanup controls; repeated disposal retries the view.\n disposePublicView(view);\n generation = undefined;\n }\n });\n viewCoordinators.set(view, { clock, token });\n return token;\n}\nexport function beginFoodSearch(\n coordinator: FoodSearchCoordinator,\n input: unknown,\n known: readonly PublicHead[] = []\n): FoodSearchRun {\n const owner = coordinatorOf(coordinator);\n if (owner.closed()) throw new Error('food_search_closed');\n const query = normalizePublicQuery(input);\n if (!query.ok) throw new Error(query.error);\n // Complete seed validation precedes clocks, cache and run effects.\n headResolutionQueries(known);\n const previousToken = owner.current();\n const previous =\n previousToken === undefined ? undefined : sessionOf(previousToken);\n const heads = new Map(\n previous?.heads().map((head) => [publicHeadKey(head), head])\n );\n for (const head of known) {\n const key = publicHeadKey(head);\n heads.set(key, selectPublicHead(heads.get(key), head).head);\n }\n if (heads.size > PUBLIC_QUERY_BUDGETS.coordinatesPerRun)\n throw new Error('head_resolver_coordinate_limit');\n const token = Object.freeze({}) as FoodSearchRun;\n const seed = Array.from(heads.values());\n const session = createSession(\n owner,\n token,\n query.text,\n seed,\n previous?.model()\n );\n sessions.set(token, session);\n owner.reserve(token); // Reserve before previous settlement or injected clocks.\n try {\n const run = beginPublicViewRun(owner.view);\n session.bindRun(run);\n requireCurrent(session);\n const model = createPublicViewHeadResolver(owner.view, run, owner.clock);\n session.bindModel(model);\n requireCurrent(session);\n session.resolved(seed);\n if (seed.length) resolveHeads(model, seed);\n requireCurrent(session);\n return token;\n } catch {\n if (!current(session)) throw new Error('food_search_superseded');\n session.fail();\n const run = session.run();\n if (run) {\n try {\n cancelPublicRun(run);\n } catch {\n /* Still owned, retryable. */\n }\n }\n throw new Error('food_search_start_failed');\n }\n}\nexport function foodSearchRequestOwner(token: FoodSearchRun): PublicRun {\n const session = sessionOf(token);\n requireCurrent(session);\n const run = session.run();\n if (!run || !publicViewRunCurrent(session.coordinator.view, run))\n throw new Error('food_search_inactive');\n requireCurrent(session);\n return run;\n}\n// Filter strategies remain separate; primary sources and all auxiliaries share\n// one genuine anonymous run rather than creating transport or budget owners.\nexport function subscribeFoodSearch(\n token: FoodSearchRun,\n filters: readonly PublicFilter[]\n): PublicRequest {\n if (filters.some((filter) => 'search' in filter))\n throw new Error('food_search_sample_required');\n const session = sessionOf(token);\n requireCurrent(session);\n refreshChronological(session);\n requireCurrent(session);\n const selected = requireChronologicalSearchQuery(\n filters,\n session.continuation().snapshot().until\n );\n let window: ChronologicalWindow;\n try {\n window = session.continuation().begin();\n } catch (error) {\n if (\n error instanceof Error &&\n error.message === 'food_search_chronological_window_limit'\n )\n session.cap();\n throw error;\n }\n try {\n const request = subscribeSearchSource(token, selected, undefined, window);\n session.trackChronological(request, window);\n return request;\n } catch (error) {\n window.finish(false, 'partial');\n throw error;\n }\n}\nfunction subscribeSearchSource(\n token: FoodSearchRun,\n filters: readonly PublicFilter[],\n sampleSource?: string,\n chronologicalWindow?: ChronologicalWindow\n): PublicRequest {\n const session = sessionOf(token),\n run = foodSearchRequestOwner(token);\n session.reserveSource(); // Reservation precedes SDK effects and never refunds.\n let request: PublicRequest;\n try {\n request = subscribePublicView(\n session.coordinator.view,\n run,\n 'search',\n filters,\n (proof) => {\n // Admission already includes a valid inclusive tail that stopped ingress.\n if (!current(session)) return;\n const head = createPublicHeadCandidate(proof);\n if (!head || publicHeadSnapshot(head).kind !== 30402) return;\n chronologicalWindow?.observe(head);\n if (!session.remember(head)) cancelPublicRun(run);\n },\n sampleSource\n );\n } catch {\n if (current(session)) session.fail();\n throw new Error('food_search_request_failed');\n }\n session.track(request);\n if (!current(session)) {\n closePublicRequest(request);\n throw new Error('food_search_superseded');\n }\n return request;\n}\n\nexport function sampleFoodSearch(\n token: FoodSearchRun\n): readonly PublicRequest[] {\n const session = sessionOf(token);\n requireCurrent(session);\n const filters = nip50SearchQuery(session.query);\n if (!filters.length) return [];\n const sources = publicViewNip50Sources(session.coordinator.view);\n if (!sources.length) return [];\n session.reserveSample(); // Failed attempts cannot recreate the relevance round.\n const samples = new Map<PublicRequest, true>();\n for (const source of sources) {\n requireCurrent(session);\n try {\n samples.set(subscribeSearchSource(token, filters, source), true);\n } catch {\n // A refused/failed source cannot discard other candidates or the fallback.\n requireCurrent(session);\n session.fail();\n }\n }\n return Array.from(samples.keys());\n}\nfunction refreshChronological(session: Session): void {\n for (const [request, window] of session.chronological()) {\n const scope = publicRequestScopeSnapshot(request);\n if (scope.state === 'active') continue;\n window.finish(\n scope.result.sources.some(\n (source) => source.candidates >= PUBLIC_QUERY_BUDGETS.requestedPerRelay\n ),\n scope.state === 'eose' && scope.result.coverage === 'bounded-eose'\n ? 'bounded-eose'\n : 'partial',\n scope.result.sources.map((source) => ({\n source: source.source,\n saturated: source.candidates >= PUBLIC_QUERY_BUDGETS.requestedPerRelay,\n eventIds: publicRunObservations(session.run()!, request)\n .filter((row) => row.source === source.source && row.kind === 30402)\n .map((row) => row.eventId)\n }))\n );\n }\n}\nexport function chronologicalFoodSearch(token: FoodSearchRun): PublicRequest {\n const session = sessionOf(token);\n requireCurrent(session);\n refreshChronological(session);\n requireCurrent(session);\n return subscribeFoodSearch(\n token,\n chronologicalSearchQuery(session.continuation().snapshot().until)\n );\n}\nexport function showMoreFoodSearch(token: FoodSearchRun): void {\n const session = sessionOf(token);\n requireCurrent(session);\n session.showMore();\n}\nexport function searchOlderFoodSearch(\n coordinator: FoodSearchCoordinator\n): FoodSearchRun {\n const owner = coordinatorOf(coordinator),\n previous = owner.current();\n if (!previous || owner.closed()) throw new Error('food_search_inactive');\n const session = sessionOf(previous);\n const snapshot = foodSearchSnapshot(coordinator);\n requireCurrent(session);\n if (!snapshot?.available) throw new Error('food_search_unavailable');\n const next = session.continuation().restart();\n const token = beginFoodSearch(coordinator, session.query);\n const successor = sessionOf(token);\n requireCurrent(successor);\n successor.bindContinuation(next);\n chronologicalFoodSearch(token);\n return token;\n}\nexport function foodSearchSnapshot(\n coordinator: FoodSearchCoordinator\n): SearchSnapshot<FoodSearchRun> | undefined {\n const owner = coordinatorOf(coordinator),\n token = owner.current();\n if (owner.closed() || token === undefined) return undefined;\n const session = sessionOf(token),\n model = session.model(),\n ownedRun = session.run();\n if (ownedRun && model) {\n const active = publicViewRunCurrent(owner.view, ownedRun);\n if (!current(session)) return undefined;\n const pending = session.pending();\n if (pending.length) {\n try {\n if (active) resolveHeads(model, pending);\n else resolveKnownHeads(model, pending);\n session.resolved(pending);\n } catch {\n session.fail();\n }\n }\n }\n refreshChronological(session);\n const raw = model ? headResolutionSnapshot(model) : [];\n const matched = model ? searchResolvedFood(model, session.query) : undefined;\n const scopes = new Map<object, SearchScope>();\n for (const request of session.requests()) {\n const scope = publicRequestScopeSnapshot(request);\n scopes.set(scope.result.context, scope);\n }\n for (const row of raw)\n for (const scope of [row.headSources, row.deletionSources])\n if (scope) scopes.set(scope.result.context, scope);\n const available =\n publicViewProjectionAvailable(owner.view) &&\n (matched?.ok ? matched.available : true);\n const run = ownedRun ? publicRunSnapshot(ownedRun) : undefined;\n // Model/run clocks may synchronously supersede or dispose this generation.\n if (!current(session)) return undefined;\n const sources = Array.from(scopes.values()),\n flags = session.flags();\n const refresh = searchRefreshState(\n available,\n run,\n sources,\n flags.cancelled,\n flags.failed,\n flags.capped\n );\n const continuation = session.continuation().snapshot(),\n page = localSearchPage(\n available && matched?.ok ? orderFoodRows(matched.rows) : [],\n session.pages()\n );\n const listings = new Map<string, ListingView>();\n for (const row of page.rows) {\n const value = listingView(\n row,\n publisherSnapshot(owner.publishers, row.state.head.pubkey)\n );\n if (value) listings.set(value.eventId, value);\n }\n if (!current(session)) return undefined;\n return {\n generation: token,\n query: session.query,\n refresh:\n continuation.gap && refresh === 'bounded-eose' ? 'partial' : refresh,\n available,\n rows: page.rows,\n listings: Array.from(listings.values()),\n hasMore: page.hasMore,\n continuation,\n scopes: sources,\n run,\n definitiveAbsence: false\n };\n}\n// Explicit auxiliary work for the current local page. Show more itself stays\n// local; snapshots never schedule profile transport or prompt a signer.\nexport function resolveFoodSearchPublishers(\n token: FoodSearchRun\n): readonly PublicRequest[] {\n const session = sessionOf(token);\n requireCurrent(session);\n const snapshot = foodSearchSnapshot(\n viewCoordinators.get(session.coordinator.view)!.token\n );\n requireCurrent(session);\n if (!snapshot?.available) throw new Error('food_search_unavailable');\n const run = foodSearchRequestOwner(token);\n const page = snapshot.rows.slice(\n (session.pages() - 1) * PUBLIC_SEARCH_BUDGETS.pageRows,\n session.pages() * PUBLIC_SEARCH_BUDGETS.pageRows\n );\n try {\n const requests = readPublisherPage(\n session.coordinator.publishers,\n run,\n page.map((row) => row.state.head.pubkey),\n session.pages()\n );\n for (const request of requests) session.track(request);\n requireCurrent(session);\n return requests;\n } catch (error) {\n if (current(session)) session.fail();\n throw error;\n }\n}\nexport function cancelFoodSearch(token: FoodSearchRun): void {\n const session = sessionOf(token);\n requireCurrent(session);\n session.cancel();\n}\nexport function closeFoodSearchCoordinator(\n coordinator: FoodSearchCoordinator\n): void {\n coordinatorOf(coordinator).close();\n}\n", 263 sha256: 264 'e625fdaa5d2a698737491566e8e30f6ba3eb5c54a2573f7d0f204f15bcd0e36b' 265 }, 266 'src/lib/catalog/search-view.ts': { 267 source: 268 "import type { PublicView } from '../runtime/public-runtime.ts';\nimport type { PublicHead } from './heads.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport type { SearchSnapshot } from './search-state.ts';\nimport {\n createFoodSearchCoordinator,\n beginFoodSearch,\n sampleFoodSearch,\n chronologicalFoodSearch,\n foodSearchSnapshot,\n resolveFoodSearchPublishers,\n showMoreFoodSearch,\n searchOlderFoodSearch,\n closeFoodSearchCoordinator,\n type FoodSearchRun\n} from './search-run.ts';\nexport type SearchViewSnapshot = SearchSnapshot<FoodSearchRun>;\nexport type ForegroundSchedule = (\n callback: () => void,\n delay: number\n) => () => void;\ndeclare const viewBrand: unique symbol;\nexport type SearchView = Readonly<{ readonly [viewBrand]: true }>;\ninterface Owner {\n readonly start: (query: unknown, known: readonly PublicHead[]) => void;\n readonly more: () => void;\n readonly older: () => void;\n readonly snapshot: () => SearchViewSnapshot | undefined;\n readonly close: () => void;\n}\nconst owners = new WeakMap<SearchView, Owner>();\nfunction ownerOf(view: SearchView): Owner {\n const owner = owners.get(view);\n if (!owner) throw Error('search_view_invalid');\n return owner;\n}\nfunction foreground(callback: () => void, delay: number): () => void {\n const timer = setTimeout(() => {\n callback();\n }, delay);\n return () => {\n clearTimeout(timer);\n };\n}\n// This owner observes a finite public run; it never creates a background poll,\n// transport, shared cache or new deadline. Explicit actions alone restart runs.\nexport function createSearchView(\n view: PublicView,\n clock: WallClock,\n onUpdate: (value: SearchViewSnapshot) => void,\n schedule: ForegroundSchedule = foreground\n): SearchView {\n const coordinator = createFoodSearchCoordinator(view, clock);\n let generation: FoodSearchRun | undefined,\n cancel: (() => void) | undefined,\n closed = false;\n function stop() {\n const previous = cancel;\n cancel = undefined;\n previous?.();\n }\n function current(token: FoodSearchRun) {\n return !closed && generation === token;\n }\n function requireOpen() {\n if (closed) throw Error('search_view_closed');\n }\n function publish(token: FoodSearchRun) {\n const value = foodSearchSnapshot(coordinator);\n if (value && current(token) && value.generation === token) onUpdate(value);\n return value;\n }\n function queue(token: FoodSearchRun) {\n if (!current(token)) return;\n const value = foodSearchSnapshot(coordinator);\n if (!value?.run?.active || !current(token)) return;\n const pending = schedule(() => {\n if (!current(token)) return;\n cancel = undefined;\n observe(token);\n }, 250);\n if (current(token)) cancel = pending;\n else pending();\n }\n function observe(token: FoodSearchRun) {\n if (!current(token)) return;\n const value = foodSearchSnapshot(coordinator);\n if (!value || !current(token)) return;\n if (value.run?.active && value.available && value.listings.length) {\n try {\n resolveFoodSearchPublishers(token);\n } catch {\n /* Failed metadata retains key fallback and source uncertainty. */\n }\n }\n if (!current(token)) return;\n const updated = publish(token);\n if (updated?.run?.active && updated.run.activeRequests > 0) queue(token);\n }\n const token = Object.freeze({}) as SearchView;\n owners.set(token, {\n start(query, known) {\n requireOpen();\n // Coordinator validates the complete query and seeds before any effects;\n // a rejected edit cannot cancel a previously accepted foreground observer.\n const next = beginFoodSearch(coordinator, query, known);\n stop();\n generation = next;\n try {\n sampleFoodSearch(next);\n } catch {\n /* Retain ordinary chronological fallback. */\n }\n if (!current(next)) return;\n try {\n chronologicalFoodSearch(next);\n } catch {\n /* Snapshot reports the actual failed source; known rows survive. */\n }\n if (current(next)) {\n publish(next);\n queue(next);\n }\n },\n more() {\n requireOpen();\n if (!generation) throw Error('search_view_inactive');\n const next = generation;\n showMoreFoodSearch(next);\n stop();\n publish(next);\n queue(next);\n },\n older() {\n requireOpen();\n const next = searchOlderFoodSearch(coordinator);\n stop();\n generation = next;\n publish(next);\n queue(next);\n },\n snapshot: () => foodSearchSnapshot(coordinator),\n close() {\n closed = true;\n stop();\n closeFoodSearchCoordinator(coordinator);\n generation = undefined;\n }\n });\n return token;\n}\nexport function startSearchView(\n view: SearchView,\n query: unknown,\n known: readonly PublicHead[] = []\n): void {\n ownerOf(view).start(query, known);\n}\nexport function moreSearchView(view: SearchView): void {\n ownerOf(view).more();\n}\nexport function olderSearchView(view: SearchView): void {\n ownerOf(view).older();\n}\nexport function searchViewSnapshot(\n view: SearchView\n): SearchViewSnapshot | undefined {\n return ownerOf(view).snapshot();\n}\nexport function closeSearchView(view: SearchView): void {\n ownerOf(view).close();\n}\n", 269 sha256: 270 '398cc2db59fb78d33df8cb8ce59d4e10a84feb3842709f2a7047033424798768' 271 }, 272 'src/lib/publishing/selling-view.ts': { 273 source: 274 "import {\n identityViewSession,\n identityViewMatchesOwner,\n subscribeIdentityView,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport { identitySessionSnapshot } from '../runtime/identity-session.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicPublicationRepository,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport { listPublicDrafts } from '../persistence/drafts.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport {\n verifyEnvelope,\n verifiedEnvelopeSnapshot\n} from '../nostr/verified-envelope.ts';\nimport { encodeProductReference } from '../nostr/references.ts';\nimport { internalHref } from '../navigation-url.ts';\nimport {\n projectFoodParts,\n type FoodProjection\n} from '../contracts/food-availability-v1/read.ts';\nimport {\n readListingOperationView,\n listingOperationSnapshot,\n closeListingOperationView,\n type ListingOperationView\n} from './listing-operation-view.ts';\nimport {\n openOwnedEditSource,\n ownedEditSourceSnapshot,\n closeOwnedEditSource\n} from './edit-source.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n subscribePublicView,\n disposePublicView,\n publicViewOwnsRun,\n publicViewProjectionAvailable,\n publicViewRunCurrent,\n type PublicRuntime,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadKey,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from '../catalog/heads.ts';\nimport {\n createPublicViewHeadResolver,\n resolveHeads,\n headResolutionSnapshot,\n closeHeadResolver,\n type HeadResolver\n} from '../catalog/resolve-head.ts';\nimport {\n publicRequestScopeSnapshot,\n publicRunSnapshot,\n type PublicRequest,\n type PublicRun\n} from '../nostr/request-scope.ts';\nimport { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';\n\ndeclare const viewBrand: unique symbol;\nexport type SellingView = Readonly<{ [viewBrand]: true }>;\nexport type SellingRow = Readonly<{\n key: string;\n title: string;\n status: string;\n provenance: string;\n href?: string;\n editHref?: string;\n draftHref?: string;\n operations: readonly ListingOperationView[];\n}>;\nexport type SellingSnapshot = Readonly<{\n attention: readonly SellingRow[];\n drafts: readonly SellingRow[];\n listings: readonly SellingRow[];\n remote: 'checking' | 'bounded' | 'partial' | 'unavailable';\n local: 'ready' | 'unavailable';\n}>;\ntype Controller = {\n snapshot(): SellingSnapshot | undefined;\n subscribe(listener: () => void): () => void;\n close(): void;\n};\ntype Group = {\n key: string;\n food: FoodProjection;\n createdAt: number;\n eventId: string;\n removal: boolean;\n operations: ListingOperationView[];\n attention: boolean;\n supportedEventId?: string;\n draftId?: string;\n};\nconst views = new WeakMap<SellingView, Controller>();\nconst active = new WeakMap<IdentityViewContext, Controller>();\n\n// Account-local presentation only. Neither a row, link nor operation disclosure\n// grants signing, delivery, adopted-source or current-head permission.\nexport async function openSellingView(\n context: IdentityViewContext,\n runtime?: PublicRuntime\n): Promise<SellingView | undefined> {\n const identity = identityViewSession(context);\n const observed = identity && identitySessionSnapshot(identity);\n const owner =\n observed && 'publicKey' in observed ? observed.publicKey : undefined;\n if (!identity || !owner || !identityViewMatchesOwner(context, owner)) return;\n active.get(context)?.close();\n let alive = true,\n database: BrowserDatabase | undefined;\n let publicView: PublicView | undefined, run: PublicRun | undefined;\n let resolver: HeadResolver | undefined, discovery: PublicRequest | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let offIdentity = () => {};\n let local: SellingSnapshot['local'] = 'unavailable';\n let remote: SellingSnapshot['remote'] = runtime ? 'checking' : 'unavailable';\n const listeners = new Map<symbol, () => void>();\n const groups = new Map<string, Group>();\n const draftRows = new Map<string, SellingRow>();\n let operationViews = Array.from<ListingOperationView>([]);\n const heads = new Map<string, PublicHead>();\n const linkedDrafts = new Map<string, true>();\n const current = () =>\n alive &&\n active.get(context) === controller &&\n identityViewSession(context) === identity &&\n identityViewMatchesOwner(context, owner);\n function notify() {\n for (const listener of listeners.values()) {\n try {\n listener();\n } catch {\n /* Presentation cannot interrupt owned cleanup. */\n }\n }\n }\n function close() {\n if (!alive) return;\n alive = false;\n offIdentity();\n if (timer !== undefined) clearTimeout(timer);\n for (const view of operationViews) closeListingOperationView(view);\n try {\n if (resolver) closeHeadResolver(resolver);\n } finally {\n try {\n if (publicView) disposePublicView(publicView);\n } finally {\n if (database) closeBrowserDatabase(database);\n }\n }\n if (active.get(context) === controller) active.delete(context);\n groups.clear();\n draftRows.clear();\n heads.clear();\n notify();\n listeners.clear();\n }\n const hrefFor = (identifier: string) => {\n const naddr = encodeProductReference({\n kind: 30402,\n pubkey: owner,\n identifier\n });\n return naddr ? internalHref(`/products/${naddr}`) : undefined;\n };\n function snapshot(): SellingSnapshot | undefined {\n if (!current()) return;\n let attention = Array.from<SellingRow>([]),\n listings = Array.from<SellingRow>([]);\n const rows =\n resolver &&\n publicView &&\n run &&\n publicViewOwnsRun(publicView, run) &&\n publicViewProjectionAvailable(publicView)\n ? headResolutionSnapshot(resolver)\n : [];\n const remoteByIdentifier = new Map(\n rows.map((row) => [row.state.head.identifier, row])\n );\n for (const group of groups.values()) {\n const known = remoteByIdentifier.get(group.food.identifier);\n const food = known?.state.food ?? group.food;\n const suppressed = known?.deletion.outcome === 'suppressed';\n const href = hrefFor(food.identifier);\n const canEdit = !!(\n href &&\n group.supportedEventId &&\n !group.removal &&\n !suppressed &&\n (!known ||\n (known.state.head.id === group.supportedEventId &&\n known.state.display === 'focused_known'))\n );\n const row: SellingRow = {\n key: group.key,\n title: food.title,\n status: group.removal\n ? 'Removal request retained locally'\n : suppressed\n ? 'Listing no longer shown; delivery records retained'\n : known?.state.food\n ? food.status === 'sold'\n ? 'Marked sold'\n : 'Marked available'\n : 'Saved public operation; current availability unconfirmed',\n provenance: 'Local publication evidence \u00b7 Remote discovery is bounded',\n ...(href ? { href } : {}),\n ...(canEdit ? { editHref: internalHref(`${href}/edit`) } : {}),\n ...(group.attention &&\n group.draftId &&\n draftRows.get(group.draftId)?.draftHref\n ? { draftHref: draftRows.get(group.draftId)?.draftHref }\n : {}),\n operations: group.operations.slice()\n };\n if (group.attention) attention = attention.concat(row);\n else listings = listings.concat(row);\n remoteByIdentifier.delete(group.food.identifier);\n }\n for (const row of remoteByIdentifier.values()) {\n if (\n !row.state.food ||\n row.state.head.pubkey !== owner ||\n row.state.display !== 'focused_known' ||\n row.deletion.outcome === 'suppressed'\n )\n continue;\n const href = hrefFor(row.state.food.identifier);\n if (!href) continue;\n listings = listings.concat({\n key: row.key,\n title: row.state.food.title,\n status:\n row.state.food.status === 'sold' ? 'Marked sold' : 'Marked available',\n provenance:\n 'Bounded remote discovery \u00b7 Read-only; no supported retained prototype source',\n href,\n operations: []\n });\n }\n return {\n attention,\n drafts: Array.from(draftRows, ([id, row]) =>\n linkedDrafts.has(id) ? undefined : row\n ).filter((row): row is SellingRow => !!row),\n listings,\n local,\n remote\n };\n }\n const controller: Controller = {\n snapshot,\n subscribe(listener) {\n const stamp = Symbol();\n listeners.set(stamp, listener);\n return () => {\n listeners.delete(stamp);\n };\n },\n close\n };\n active.set(context, controller);\n offIdentity = subscribeIdentityView(context, () => {\n if (!current()) close();\n });\n try {\n const opened = await openBrowserDatabase();\n if (opened.state !== 'ready') {\n close();\n return;\n }\n if (!current()) {\n closeBrowserDatabase(opened.owner);\n close();\n return;\n }\n database = opened.owner;\n const repository = createPublicPublicationRepository(database, owner);\n const drafts = repository && publicPublicationDraftRepository(repository);\n const quota = repository && publicPublicationQuotaRepository(repository);\n if (!repository || !drafts || !quota) {\n close();\n return;\n }\n const saved = await listPublicDrafts(drafts);\n if (!current() || !saved.ok) {\n close();\n return;\n }\n for (const draft of saved.value) {\n const href = internalHref(`/selling/drafts/${draft.id}`);\n if (href)\n draftRows.set(draft.id, {\n key: `draft:${draft.id}`,\n title: draft.form.title || 'Untitled draft',\n status: 'Saved in this browser \u00b7 Not published',\n provenance: 'Local draft',\n draftHref: href,\n operations: []\n });\n }\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) {\n close();\n return;\n }\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) {\n close();\n return;\n }\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(repository, item.id);\n if (!current() || read.status !== 'found') {\n close();\n return;\n }\n const record = publicRecordSnapshot(read.record, owner, item.id);\n if (!record || record.family !== 'public_operation') {\n close();\n return;\n }\n if (record.capture.kind !== 30402 && record.capture.kind !== 5) continue;\n const template = inspectLocalTemplate(\n record.capture.wire,\n owner,\n record.capture.kind\n );\n const base =\n record.capture.kind === 5 && record.source.type === 'public_head'\n ? verifyEnvelope(record.source.wire)\n : undefined;\n const source = base?.ok ? verifiedEnvelopeSnapshot(base.value) : template;\n const projected = source && projectFoodParts(source);\n if (!template || !projected || projected.outcome !== 'focused') continue;\n const key = JSON.stringify([\n 30402,\n owner,\n projected.projection.identifier\n ]);\n const presented = await readListingOperationView(\n repository,\n identity,\n item.id\n );\n if (!current() || presented.status !== 'found') {\n if (presented.status === 'found')\n closeListingOperationView(presented.view);\n close();\n return;\n }\n operationViews = operationViews.concat(presented.view);\n const facts = listingOperationSnapshot(presented.view);\n if (!facts) {\n close();\n return;\n }\n let group = groups.get(key);\n if (!group) {\n group = {\n key,\n food: projected.projection,\n createdAt: template.created_at,\n eventId: record.capture.hash,\n removal: template.kind === 5,\n attention: false,\n operations: [],\n ...(record.source.type === 'draft'\n ? { draftId: record.source.id }\n : {})\n };\n groups.set(key, group);\n }\n if (\n template.created_at > group.createdAt ||\n (template.created_at === group.createdAt &&\n record.capture.hash < group.eventId)\n ) {\n group = {\n ...group,\n food: projected.projection,\n createdAt: template.created_at,\n eventId: record.capture.hash,\n removal: template.kind === 5,\n ...(record.source.type === 'draft'\n ? { draftId: record.source.id }\n : {})\n };\n }\n group = {\n ...group,\n operations: group.operations.concat(presented.view),\n attention:\n group.attention ||\n facts.needsAction ||\n !record.artifact ||\n facts.targets.some(\n (target) => !target.accepted || target.readback !== 'confirmed'\n )\n };\n groups.set(key, group);\n const capturedSource = record.source;\n if (\n capturedSource.type === 'draft' &&\n saved.value.some(\n (draft) =>\n draft.id === capturedSource.id &&\n draft.revision === capturedSource.revision\n )\n )\n linkedDrafts.set(capturedSource.id, true);\n if (record.artifact && record.capture.kind === 30402) {\n const proof = verifyEnvelope(record.artifact.wire);\n const head = proof.ok && createPublicHeadCandidate(proof.value);\n if (head) {\n const prior = heads.get(publicHeadKey(head));\n heads.set(publicHeadKey(head), selectPublicHead(prior, head).head);\n }\n }\n }\n // Reuse the original retained-source verifier without starting a network\n // run or adopting a remote source. Edit's route performs its own fresh\n // independent current-head checks; this metadata grants no effect custody.\n for (const group of groups.values()) {\n if (group.attention && group.draftId && draftRows.has(group.draftId))\n linkedDrafts.set(group.draftId, true);\n const naddr = encodeProductReference({\n kind: 30402,\n pubkey: owner,\n identifier: group.food.identifier\n });\n const source =\n naddr && (await openOwnedEditSource(repository, context, naddr));\n if (!current()) {\n if (source) closeOwnedEditSource(source);\n close();\n return;\n }\n const supported = source ? ownedEditSourceSnapshot(source) : undefined;\n if (supported)\n groups.set(group.key, {\n ...group,\n supportedEventId: supported.sourceEventId\n });\n if (source) closeOwnedEditSource(source);\n }\n local = 'ready';\n if (runtime) {\n try {\n publicView = createPublicView(runtime);\n run = beginPublicViewRun(publicView);\n resolver = createPublicViewHeadResolver(publicView, run, {\n nowSeconds: () => Math.floor(Date.now() / 1000)\n });\n discovery = subscribePublicView(\n publicView,\n run,\n 'head',\n [\n {\n kinds: [30402],\n authors: [owner],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n ],\n (proof) => {\n if (!current()) return;\n const head = createPublicHeadCandidate(proof);\n if (!head || publicHeadSnapshot(head).pubkey !== owner) return;\n const key = publicHeadKey(head);\n if (\n !heads.has(key) &&\n heads.size >= PUBLIC_QUERY_BUDGETS.coordinatesPerRun\n )\n return;\n heads.set(key, selectPublicHead(heads.get(key), head).head);\n }\n );\n function observe() {\n if (!current()) return;\n if (\n !publicView ||\n !run ||\n !resolver ||\n !discovery ||\n !publicViewOwnsRun(publicView, run) ||\n !publicViewProjectionAvailable(publicView)\n ) {\n remote = 'unavailable';\n notify();\n return;\n }\n try {\n if (publicViewRunCurrent(publicView, run))\n resolveHeads(\n resolver,\n Array.from(heads.values()).slice(\n 0,\n PUBLIC_QUERY_BUDGETS.coordinatesPerRun\n )\n );\n const rows = headResolutionSnapshot(resolver);\n const source = publicRequestScopeSnapshot(discovery);\n remote =\n source.state === 'eose' &&\n source.result.coverage === 'bounded-eose' &&\n rows.every((row) => row.coverage === 'bounded-eose')\n ? 'bounded'\n : publicRunSnapshot(run).activeRequests > 0\n ? 'checking'\n : 'partial';\n } catch {\n remote = 'partial';\n }\n notify();\n if (\n current() &&\n publicRunSnapshot(run).active &&\n publicRunSnapshot(run).activeRequests > 0\n )\n timer = setTimeout(observe, 250);\n }\n observe();\n } catch {\n remote = 'unavailable';\n }\n }\n if (!current()) {\n close();\n return;\n }\n const token = Object.freeze({}) as SellingView;\n views.set(token, controller);\n return token;\n } catch {\n close();\n return;\n }\n}\nexport function sellingViewSnapshot(\n view: SellingView\n): SellingSnapshot | undefined {\n return views.get(view)?.snapshot();\n}\nexport function subscribeSellingView(\n view: SellingView,\n listener: () => void\n): () => void {\n return views.get(view)?.subscribe(listener) ?? (() => {});\n}\nexport function closeSellingView(view: SellingView): void {\n views.get(view)?.close();\n}\n", 275 sha256: 276 'a9e896db6f0485699c069ee31eb20a6c5476095d0ffef1160aa76cc64a364dc2' 277 }, 278 'src/routes/+layout.svelte': { 279 source: 280 "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';\n import { onMount, setContext, type Snippet } from 'svelte';\n import {\n createPublicRuntimeContext,\n mountPublicRuntime,\n closePublicRuntime,\n PUBLIC_RUNTIME_CONTEXT\n } from '../lib/runtime/public-runtime.ts';\n import { page } from '$app/state';\n import AppShell from '../lib/components/AppShell.svelte';\n import {\n createIdentityViewContext,\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n mountIdentityView,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n closeIdentityView,\n invalidateIdentityView\n } from '../lib/runtime/view-context.ts';\n const identityContext = createIdentityViewContext();\n setContext(IDENTITY_VIEW_CONTEXT, identityContext);\n let identityView = $state(identityViewSnapshot(identityContext));\n $effect(() => {\n if (page.url.pathname) invalidateIdentityView(identityContext);\n });\n function connect() {\n return connectIdentityView(identityContext);\n }\n function disconnect() {\n disconnectIdentityView(identityContext);\n }\n const shellIdentity = $derived(\n identityView.identity.state === 'guest' ||\n identityView.identity.state === 'pending'\n ? {\n kind: 'guest' as const,\n onconnect: identityView.mounted ? connect : undefined\n }\n : {\n kind: 'connected' as const,\n publicKey: identityView.identity.publicKey,\n ondisconnect: disconnect\n }\n );\n\n const publicContext = createPublicRuntimeContext();\n setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);\n onMount(() => {\n mountPublicRuntime(publicContext);\n return () => closePublicRuntime(publicContext);\n });\n onMount(() => {\n const off = subscribeIdentityView(identityContext, (next) => {\n identityView = next;\n });\n mountIdentityView(identityContext);\n return () => {\n off();\n closeIdentityView(identityContext);\n };\n });\n\n let { children }: { children: Snippet } = $props();\n</script>\n\n<AppShell\n identity={shellIdentity}\n capability={identityView.identity}\n ondisconnect={disconnect}\n currentPath={page.url.pathname}\n availableRoutes={[\n '/search',\n '/sell',\n '/selling',\n '/messages',\n '/about',\n '/privacy'\n ]}\n>\n {@render children()}\n</AppShell>\n", 281 sha256: 282 'b935e9c00c736107139d37020cf9590f2e51440991ac89c2eb47bba1aabe13a2' 283 }, 284 'src/routes/products/[naddr=naddr]/+page.svelte': { 285 source: 286 "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import { page } from '$app/state';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n createPublicView,\n disposePublicView,\n type PublicView,\n type PublicRuntime,\n type PublicRuntimeContext\n } from '../../../lib/runtime/public-runtime.ts';\n import {\n createProductView,\n closeProductView,\n type ProductView,\n type ProductViewSnapshot\n } from '../../../lib/catalog/product-view.ts';\n import { decodeProductReference } from '../../../lib/nostr/references.ts';\n import { readPublicContact } from '../../../lib/contracts/food-availability-v1/contact-read.ts';\n import { copyProductReference } from '../../../lib/navigation-copy.ts';\n import { internalHref, navigationHref } from '../../../lib/navigation-url.ts';\n import ListingFacts from '../../../lib/components/ListingFacts.svelte';\n import PublisherIdentity from '../../../lib/components/PublisherIdentity.svelte';\n import Disclosure from '../../../lib/components/primitives/Disclosure.svelte';\n import Button from '../../../lib/components/primitives/Button.svelte';\n import ProductEnquiry from '../../../lib/components/ProductEnquiry.svelte';\n const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);\n let runtime = $state.raw<PublicRuntime | undefined>(),\n result = $state.raw<ProductViewSnapshot | undefined>(),\n error = $state<string | undefined>(),\n copyNotice = $state<string | undefined>();\n let productOwner = $state.raw<ProductView | undefined>();\n const reference = $derived(decodeProductReference(page.params.naddr));\n const contact = $derived(readPublicContact(result?.food?.content));\n let disposed = false;\n onMount(() => {\n const unavailable = () => {\n if (!disposed) error = 'Food sources are unavailable.';\n };\n try {\n void publicRuntimeReady(context)\n .then((value) => {\n if (!disposed) {\n runtime = value;\n if (!value) unavailable();\n }\n })\n .catch(unavailable);\n } catch {\n unavailable();\n }\n return () => {\n disposed = true;\n };\n });\n $effect(() => {\n const selected = reference,\n shared = runtime;\n result = undefined;\n productOwner = undefined;\n copyNotice = undefined;\n if (!selected || !shared) return;\n let active = true,\n acquired: PublicView | undefined,\n owner: ProductView | undefined;\n try {\n acquired = createPublicView(shared);\n owner = createProductView(\n acquired,\n selected.naddr,\n { nowSeconds: () => Math.floor(Date.now() / 1000) },\n (value) => {\n if (active && !disposed) result = value;\n }\n );\n productOwner = owner;\n error = undefined;\n } catch {\n error = 'Food sources are unavailable.';\n if (acquired)\n try {\n disposePublicView(acquired);\n } catch {\n /* Shared runtime keeps a failed disposer retryable. */\n }\n }\n return () => {\n active = false;\n if (owner) closeProductView(owner);\n };\n });\n async function copyLink() {\n const selected = reference;\n if (!selected) return;\n const copied = await copyProductReference(selected.naddr, page.url.origin);\n if (!disposed && reference?.naddr === selected.naddr)\n copyNotice = copied\n ? 'Link copied.'\n : 'Copy was unavailable. Select the public link below.';\n }\n</script>\n\n<svelte:head\n ><title>{result?.food?.title ?? 'Food'} \u2014 HarvestCircle</title></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a href={internalHref('/search')}>Search food</a>\n <h1>{result?.food?.title ?? 'Food'}</h1>\n {#if !reference}<p class=\"notice\">This food reference is invalid.</p>\n {:else if error || result?.outcome === 'unavailable'}<p class=\"notice\">\n Food sources are unavailable.\n </p>\n {:else if !result || result.outcome === 'checking'}<p>\n Checking food sources\u2026\n </p>\n {:else if result.outcome === 'unobserved'}<p class=\"notice\">\n This listing was not observed in the sources checked. It may be\n unavailable or missing from these sources.\n </p>\n {:else if result.outcome === 'withdrawn'}<p class=\"notice\">\n This listing was withdrawn by its publisher.\n </p>\n {:else if result.outcome === 'unsupported'}<p class=\"notice\">\n The latest known listing uses an unsupported food format.\n </p>\n {:else if result.outcome === 'future_quarantined' || result.outcome === 'clock_unavailable'}<p\n class=\"notice\"\n >\n Listing time could not be confirmed. Food details are unavailable.\n </p>{/if}\n {#if result}\n <PublisherIdentity publisher={result.publisher} />\n {#if result.lastKnown}<p class=\"notice\">\n This is last-known information. The listing status check is incomplete.\n </p>{/if}\n {#if result.food && result.createdAt !== undefined}<ListingFacts\n food={result.food}\n createdAt={result.createdAt}\n />{/if}\n {#if result.outcome === 'sold'}<p class=\"notice\">\n The seller marked this listing sold.\n </p>{/if}\n {#if result.outcome === 'active'}<p>\n Confirm availability with the seller.\n </p>\n {/if}\n {#if productOwner}<ProductEnquiry\n view={productOwner}\n observation={result}\n />{/if}\n <Disclosure summary=\"Listing and source details\">\n {#if result.eventId}<p>\n Listing version: <code>{result.eventId}</code>\n </p>{/if}\n {#each result.sources as source (source.result.context)}<p>\n {source.kind}: {source.state}. Coverage: {source.result.coverage}.\n </p>\n {#each source.result.sources as relay (relay.source)}<p>\n {relay.source}: {relay.state}.\n </p>{/each}{/each}\n <p>\n These bounded checks do not prove complete coverage or current stock.\n </p>\n </Disclosure>\n {#if contact && result.outcome === 'active'}<Disclosure\n summary=\"Other contact details\"\n ><a href={navigationHref(contact.href)}>{contact.href}</a></Disclosure\n >{/if}\n {/if}\n {#if reference}<Button label=\"Copy link\" onclick={copyLink} /><a\n href={internalHref(`/products/${reference.naddr}`)}>Public food link</a\n >{/if}\n {#if copyNotice}<p role=\"status\">{copyNotice}</p>{/if}\n</div>\n", 287 sha256: 288 'e63a2c8b3833966a36e4d97aef7726ff3d087703cc9b475e7f52f5478fed5ce7' 289 }, 290 'src/routes/privacy/+page.svelte': { 291 source: 292 '<svelte:head><title>Privacy \u2014 HarvestCircle</title></svelte:head>\n<div class="page page--reading stack">\n <h1>Privacy</h1>\n <p class="notice">Privacy information is unavailable during development.</p>\n</div>\n', 293 sha256: 294 '1766ce7a732264f24a82b3a7a1e999a3496cc57af8ce3f9624a32c8c37527454' 295 } 296 }, 297 ...{ 298 'src/lib/messaging/decryption-queue.ts': { 299 source: 300 "import { planDecryptBatch } from './inbox-state.ts';\nimport { canonicalPublicKey } from '../contracts/public-key.ts';\nimport { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts';\nimport {\n privateSessionOwnership,\n subscribePrivateSessionClose,\n type PrivateSession\n} from '../runtime/private-session.ts';\nimport {\n identityMessagingOwnership,\n type IdentitySession\n} from '../runtime/identity-session.ts';\nimport {\n getPrivateVisibilityScope,\n privateVisibilitySnapshot\n} from '../runtime/dispose.ts';\nimport {\n listPrivateReceivedRecords,\n type PrivateStorageRepository\n} from '../persistence/private-storage.ts';\nimport { privateRecordIdentity } from '../persistence/private-records.ts';\nimport {\n captureReceivedUnwrap,\n unwrapReceivedEnvelope,\n stopReceivedUnwrap,\n expireReceivedUnwrapWait,\n type ReceivedUnwrap\n} from '../nostr/unwrap-admission.ts';\nimport {\n admitReceivedConversation,\n conversationSnapshot,\n type AdmittedConversation\n} from './admit-conversation.ts';\nimport {\n unlockedSessionOwnership,\n subscribeUnlockedSessionClose,\n acceptUnlockedConversation,\n type UnlockedSession\n} from './unlocked-session.ts';\ndeclare const queueBrand: unique symbol;\nexport type DecryptionQueue = Readonly<{ [queueBrand]: true }>;\ntype View = Readonly<{\n state: string;\n reason: string | null;\n queued: number;\n attempted: number;\n blocked: number;\n admitted: number;\n invalid: number;\n busy: boolean;\n}>;\ntype Controller = {\n refresh(): Promise<boolean>;\n run(review: unknown, blocked: readonly string[]): Promise<boolean>;\n snapshot(): View;\n rooms(): readonly AdmittedConversation[];\n stop(): void;\n expire(): void;\n};\nconst controllers = new WeakMap<DecryptionQueue, Controller>(),\n sessions = new WeakMap<PrivateSession, DecryptionQueue>();\n// Only original current owner-generation and actual explicit Messages unlock\n// admit a controller. Construction/refresh never invoke an extension operation.\nexport function captureDecryptionQueue(\n repository: PrivateStorageRepository,\n session: PrivateSession,\n identity: IdentitySession,\n unlocked: UnlockedSession,\n review: unknown\n): DecryptionQueue | undefined {\n if (typeof window === 'undefined' || review !== 'reviewed_inbox_unlock')\n return undefined;\n const observed = privateSessionOwnership(session),\n owner = identityMessagingOwnership(identity),\n cache = unlockedSessionOwnership(unlocked);\n if (\n !observed?.current() ||\n !owner?.current() ||\n !cache?.current() ||\n observed.owner !== owner.owner ||\n observed.owner !== cache.owner ||\n observed.session !== owner.session ||\n observed.session !== cache.session\n )\n return undefined;\n const capture = observed,\n identityOwner = owner,\n unlockedOwner = cache;\n let visibility;\n try {\n visibility = getPrivateVisibilityScope(session);\n } catch {\n return undefined;\n }\n if (!visibility || !privateVisibilitySnapshot(visibility).active)\n return undefined;\n const visible = visibility;\n const prior = sessions.get(session);\n if (prior) return prior;\n const token = Object.freeze({}) as DecryptionQueue;\n let stopped = false,\n busy = false,\n paused = false,\n state = 'ready',\n reason: string | null = null,\n attempted = 0,\n blocked = 0,\n admitted = 0,\n invalid = 0;\n let pending = Array.from<string>([]),\n processed = Array.from<string>([]),\n accepted = Array.from<AdmittedConversation>([]),\n readers = Array.from<ReceivedUnwrap>([]);\n let active: ReceivedUnwrap | undefined,\n off = () => {},\n unlockOff = () => {};\n function current() {\n return (\n !stopped &&\n capture.current() &&\n identityOwner.current() &&\n unlockedOwner.current() &&\n privateVisibilitySnapshot(visible).active\n );\n }\n function stop() {\n if (stopped) return;\n stopped = true;\n state = 'stopped';\n reason = 'stopped';\n if (active) stopReceivedUnwrap(active);\n for (const reader of readers) stopReceivedUnwrap(reader);\n readers = [];\n accepted = [];\n pending = [];\n processed = [];\n off();\n unlockOff();\n if (sessions.get(session) === token) sessions.delete(session);\n // Actual pending SDK promise retains the shared slot until its settlement.\n }\n function expire() {\n if (stopped || !busy) return;\n paused = true;\n state = 'paused';\n reason = 'wait_expired';\n if (active) expireReceivedUnwrapWait(active);\n }\n function pause(why: string) {\n paused = true;\n state = 'paused';\n reason = why;\n }\n async function load() {\n if (!current()) {\n stop();\n return false;\n }\n const result = await listPrivateReceivedRecords(repository);\n if (!current()) {\n stop();\n return false;\n }\n if (!result.ok) {\n pause(result.reason);\n return false;\n }\n let ids = Array.from<string>([]);\n for (const handle of result.value) {\n const record = privateRecordIdentity(handle);\n if (record?.owner !== capture.owner) {\n pause('invalid_scope');\n return false;\n }\n if (!processed.includes(record.id)) ids = ids.concat(record.id);\n }\n pending = ids;\n return true;\n }\n const controller: Controller = {\n snapshot: () => ({\n state,\n reason,\n queued: pending.length,\n attempted,\n blocked,\n admitted,\n invalid,\n busy\n }),\n rooms: () => (current() ? accepted.slice() : []),\n stop,\n expire,\n async refresh() {\n if (busy || !current()) return false;\n try {\n return await load();\n } catch {\n pause('unavailable');\n return false;\n }\n },\n async run(reviewed, blockedPeers) {\n if (reviewed !== 'reviewed_decrypt_batch' || busy || !current())\n return false;\n // Detached block values can only suppress an already authenticated inner\n // peer's local projection; they never bypass envelope cost or confer SDK access.\n if (\n !Array.isArray(blockedPeers) ||\n blockedPeers.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes\n )\n return false;\n const exclusions = blockedPeers.slice();\n for (const peer of exclusions)\n if (canonicalPublicKey(peer) !== peer) return false;\n busy = true;\n paused = false;\n state = 'running';\n reason = null;\n attempted = 0;\n blocked = 0;\n admitted = 0;\n invalid = 0;\n try {\n if (!(await load()) || paused || !current()) return false;\n const plan = planDecryptBatch(pending);\n for (const id of plan.selected) {\n if (!current()) {\n stop();\n return false;\n }\n if (paused) return false;\n // Cost reservation occurs before unwrap/admission/dedup/blocked sender.\n attempted++;\n active = captureReceivedUnwrap(\n repository,\n identity,\n id,\n 'reviewed_inbox_unlock'\n );\n if (!active) {\n pause('unavailable');\n return false;\n }\n const reader = active,\n result = await unwrapReceivedEnvelope(reader);\n if (!current()) {\n stopReceivedUnwrap(reader);\n stop();\n return false;\n }\n if (paused) {\n stopReceivedUnwrap(reader);\n return false;\n }\n if (result.status === 'authenticated') {\n const room =\n admitReceivedConversation(result.envelope, 'inbound') ??\n admitReceivedConversation(result.envelope, 'self_archive');\n const message = room && conversationSnapshot(room);\n if (!room || !message) {\n invalid++;\n stopReceivedUnwrap(reader);\n } else if (exclusions.includes(message.peer)) {\n blocked++;\n stopReceivedUnwrap(reader);\n } else {\n const projection = acceptUnlockedConversation(unlocked, room);\n if (projection === 'added') {\n accepted = accepted.concat(room);\n readers = readers.concat(reader);\n admitted++;\n } else if (projection === 'duplicate') {\n admitted++;\n stopReceivedUnwrap(reader);\n } else {\n stopReceivedUnwrap(reader);\n pause(projection);\n return false;\n }\n }\n } else if (\n result.status === 'mismatch' ||\n result.status === 'invalid'\n ) {\n invalid++;\n stopReceivedUnwrap(reader);\n } else {\n stopReceivedUnwrap(reader);\n pause(result.status);\n return false;\n }\n active = undefined;\n if (!current() || paused) return false;\n processed = processed.concat(id);\n pending = pending.filter((next) => next !== id);\n }\n if (!(await load()) || paused || !current()) return false;\n state = pending.length ? 'needs_action' : 'idle';\n return true;\n } catch {\n if (current() && !paused) pause('unavailable');\n return false;\n } finally {\n active = undefined;\n busy = false;\n }\n }\n };\n controllers.set(token, controller);\n sessions.set(session, token);\n off = subscribePrivateSessionClose(session, stop);\n unlockOff = subscribeUnlockedSessionClose(unlocked, stop);\n if (!current()) {\n stop();\n return undefined;\n }\n return token;\n}\nexport function refreshDecryptionQueue(\n token: DecryptionQueue\n): Promise<boolean> {\n return controllers.get(token)?.refresh() ?? Promise.resolve(false);\n}\nexport function runDecryptionBatch(\n token: DecryptionQueue,\n review: unknown,\n blockedPeers: readonly string[] = []\n): Promise<boolean> {\n return (\n controllers.get(token)?.run(review, blockedPeers) ?? Promise.resolve(false)\n );\n}\nexport function decryptionQueueSnapshot(token: DecryptionQueue): View {\n return (\n controllers.get(token)?.snapshot() ?? {\n state: 'stopped',\n reason: 'invalid',\n queued: 0,\n attempted: 0,\n blocked: 0,\n admitted: 0,\n invalid: 0,\n busy: false\n }\n );\n}\nexport function decryptionQueueConversations(\n token: DecryptionQueue\n): readonly AdmittedConversation[] {\n return controllers.get(token)?.rooms() ?? [];\n}\nexport function stopDecryptionQueue(token: DecryptionQueue): void {\n controllers.get(token)?.stop();\n}\nexport function expireDecryptionQueueWait(token: DecryptionQueue): void {\n controllers.get(token)?.expire();\n}\n", 301 sha256: 302 '07661a883ee360e9fd7bd411893d637fd6b4b70aecb20101b826fe41b7ca4810' 303 }, 304 'src/lib/messaging/inbox-view.ts': { 305 source: 306 "import {\n projectConversationThread,\n unavailableThread,\n type ThreadSnapshot,\n type ThreadMessage\n} from './conversation-thread.ts';\nimport type { PrivateRecordHandle } from '../persistence/private-records.ts';\nimport { canonicalPublicKey } from '../contracts/public-key.ts';\nimport {\n groupInboxMessages,\n type InboxListSnapshot,\n type InboxListRow\n} from './inbox-list.ts';\nimport {\n captureMessageMetadata,\n messageMetadataSnapshot,\n markDisplayedMessage,\n type MessageMetadata\n} from '../persistence/message-metadata.ts';\nimport {\n captureConversationDirectory,\n rememberAdmittedConversation,\n closeConversationDirectory,\n resolveLocalConversation,\n type ConversationDirectory\n} from './conversation-directory.ts';\nimport {\n conversationSnapshot,\n type AdmittedConversation\n} from './admit-conversation.ts';\nimport { decryptionQueueConversations } from './decryption-queue.ts';\nimport {\n captureOlderInbox,\n loadOlderInbox,\n stopOlderInbox,\n olderInboxSnapshot,\n type OlderInbox\n} from './history-pagination.ts';\nimport {\n identityMessagingOwnership,\n identitySessionSnapshot,\n subscribeIdentityInvalidation,\n type IdentitySession,\n type IdentitySnapshot\n} from '../runtime/identity-session.ts';\nimport {\n privateSessionOwnership,\n subscribePrivateSessionClose,\n closePrivateSession,\n type PrivateSession\n} from '../runtime/private-session.ts';\nimport {\n inboxSetupViewOwnership,\n inboxSetupViewSnapshot,\n subscribeInboxSetupView,\n closeInboxSetupView,\n unlockInboxSetupView,\n observeInboxSetupView,\n type InboxSetupView\n} from './inbox-setup-view.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPrivateStorageRepository,\n listPrivateSendRecords,\n type PrivateStorageRepository\n} from '../persistence/private-storage.ts';\nimport {\n captureUnlockedSession,\n closeUnlockedSession,\n readUnlockedMessages,\n unlockedConversationCurrent,\n type UnlockedSession\n} from './unlocked-session.ts';\nimport {\n captureDecryptionQueue,\n refreshDecryptionQueue,\n runDecryptionBatch,\n decryptionQueueSnapshot,\n stopDecryptionQueue,\n type DecryptionQueue\n} from './decryption-queue.ts';\nimport {\n captureInboxSync,\n startInboxSync,\n refreshInboxSync,\n inboxSyncSnapshot,\n inboxSyncHistoryOwnership,\n stopInboxSync,\n type InboxSync\n} from './inbox-sync.ts';\nimport { messagingReadinessSnapshot } from './readiness.ts';\nimport {\n selfRecoveryAcknowledgementSnapshot,\n verifySelfRecoveryAcknowledgement,\n type SelfRecoveryAcknowledgement\n} from '../persistence/private-sends.ts';\ndeclare const inboxViewBrand: unique symbol;\nexport type InboxView = Readonly<{ [inboxViewBrand]: true }>;\nexport type InboxViewSnapshot = Readonly<{\n state: string;\n reason: string | null;\n busy: boolean;\n owner?: string;\n identity: IdentitySnapshot;\n queued: number;\n count: number;\n lastCheckedAt: number | null;\n historyComplete: false;\n cleanupRequired: boolean;\n}>;\ntype Inputs = Readonly<{\n identity: IdentitySession;\n setup: InboxSetupView;\n conversationId?: string;\n}>;\nexport type InboxReplyOwnership = Readonly<{\n owner: string;\n identity: IdentitySession;\n session: PrivateSession;\n database: BrowserDatabase;\n repository: PrivateStorageRepository;\n unlocked: UnlockedSession;\n room: AdmittedConversation;\n setup: InboxSetupView;\n peer: string;\n parent: string;\n current(): boolean;\n acceptLocalReply(\n receipt: SelfRecoveryAcknowledgement,\n review: unknown\n ): Promise<boolean>;\n}>;\ntype Controller = {\n reply(id: unknown, rumor: unknown): InboxReplyOwnership | undefined;\n snapshot(): InboxViewSnapshot;\n thread(id: unknown): ThreadSnapshot;\n threadRevision(): number;\n message(id: unknown, rumor: unknown): ThreadMessage | undefined;\n resolve(id: unknown, review: unknown): Promise<boolean>;\n displayed(\n id: unknown,\n rumors: readonly string[],\n review: unknown\n ): Promise<boolean>;\n setup(): InboxSetupView | undefined;\n list(): InboxListSnapshot;\n row(peer: unknown): InboxListRow | undefined;\n revision(): number;\n open(peer: unknown, review: unknown): Promise<string | undefined>;\n older(review: unknown): Promise<boolean>;\n olderAvailable(): boolean;\n subscribe(listener: (view: InboxViewSnapshot) => void): () => void;\n unlock(review: unknown): Promise<boolean>;\n check(review: unknown): Promise<boolean>;\n read(review: unknown): Promise<boolean>;\n stop(): void;\n close(): boolean;\n};\nconst views = new WeakMap<InboxView, Controller>();\nconst unavailable = (): InboxViewSnapshot => ({\n state: 'unavailable',\n reason: null,\n busy: false,\n identity: { state: 'guest', reason: 'unavailable' },\n queued: 0,\n count: 0,\n lastCheckedAt: null,\n historyComplete: false,\n cleanupRequired: false\n});\n// The original setup/identity objects, not their copied readiness projections,\n// own this per-page orchestration. Mounting/subscribing never prompts or sends.\nexport function createInboxView(input: Inputs): InboxView | undefined {\n if (typeof window === 'undefined') return;\n const original = identityMessagingOwnership(input.identity),\n setup = inboxSetupViewOwnership(input.setup);\n if (\n !original?.current() ||\n !setup?.current() ||\n setup.identity !== input.identity\n )\n return;\n const capture = original,\n token = Object.freeze({}) as InboxView;\n let closed = false,\n busy = false,\n epoch = 0,\n reason: string | null = null,\n lastCheckedAt: number | null = null,\n checkPending = false,\n sampling = false,\n refreshedRetained = -1;\n let session: PrivateSession | undefined,\n database: BrowserDatabase | undefined,\n repository: PrivateStorageRepository | undefined,\n unlocked: UnlockedSession | undefined,\n queue: DecryptionQueue | undefined,\n sync: InboxSync | undefined;\n let metadata: MessageMetadata | undefined,\n directory: ConversationDirectory | undefined,\n older: OlderInbox | undefined;\n let list: InboxListSnapshot = groupInboxMessages('', [], []);\n let threadId: string | undefined,\n threadPeer: string | undefined,\n threadEpoch = 0;\n let threadModel: ThreadSnapshot = unavailableThread();\n const threadProofs = new Map<\n string,\n Readonly<{ room: AdmittedConversation; message: ThreadMessage }>\n >();\n let sendRecords: readonly PrivateRecordHandle[] =\n Array.from<PrivateRecordHandle>([]);\n let listReason: string | null = null;\n let repliedPeers = Array.from<string>([]);\n let listRevision = 0;\n const rowProofs = new Map<\n string,\n Readonly<{ data: InboxListRow; room: AdmittedConversation }>\n >();\n let off = () => {},\n privateOff = () => {},\n setupOff = () => {},\n pendingCleanup = Array.from<() => void>([]);\n const listeners = new Map<symbol, (view: InboxViewSnapshot) => void>();\n function current(generation = epoch) {\n const owner = inboxSetupViewOwnership(input.setup);\n return (\n !closed &&\n generation === epoch &&\n capture.current() &&\n owner?.identity === input.identity &&\n owner.current()\n );\n }\n function privateCurrent() {\n const owner = session && privateSessionOwnership(session);\n return (\n !!owner?.current() &&\n owner.owner === capture.owner &&\n owner.session === capture.session &&\n current()\n );\n }\n function threadRooms(id: unknown) {\n if (\n id !== threadId ||\n !threadPeer ||\n !privateCurrent() ||\n !unlocked ||\n !queue\n )\n return;\n const rooms = decryptionQueueConversations(queue).filter((room) => {\n const data = conversationSnapshot(room);\n return (\n data?.owner === capture.owner &&\n data.peer === threadPeer &&\n unlockedConversationCurrent(unlocked!, room)\n );\n });\n return rooms;\n }\n function refreshThread() {\n threadProofs.clear();\n threadModel = unavailableThread();\n const rooms = threadRooms(threadId);\n if (!rooms || !threadPeer) return;\n const data = rooms.map(conversationSnapshot);\n if (data.some((row) => !row)) return;\n threadModel = projectConversationThread(\n capture.owner,\n threadPeer,\n data.filter((row) => row !== undefined),\n sendRecords\n );\n if (threadModel.status !== 'ready') return;\n const byRumor = new Map<string, AdmittedConversation>();\n for (const room of rooms) {\n const row = conversationSnapshot(room);\n if (row) byRumor.set(row.rumorId, room);\n }\n for (const message of threadModel.messages) {\n const room = byRumor.get(message.data.rumorId);\n if (room) threadProofs.set(message.data.rumorId, { room, message });\n }\n }\n function messageSnapshot(\n id: unknown,\n rumor: unknown\n ): ThreadMessage | undefined {\n if (\n id !== threadId ||\n typeof rumor !== 'string' ||\n !privateCurrent() ||\n !unlocked ||\n threadModel.status !== 'ready'\n )\n return;\n const proof = threadProofs.get(rumor);\n if (!proof || !unlockedConversationCurrent(unlocked, proof.room)) return;\n const actual = conversationSnapshot(proof.room);\n if (\n !actual ||\n actual.owner !== capture.owner ||\n actual.peer !== threadPeer ||\n actual.rumorId !== rumor\n )\n return;\n return {\n data: { ...actual },\n citations: proof.message.citations.map((row) => ({ ...row })),\n parent: proof.message.parent,\n delivery: proof.message.delivery?.slice() ?? null\n };\n }\n function threadSnapshot(id: unknown): ThreadSnapshot {\n if (id !== threadId || !privateCurrent() || threadModel.status !== 'ready')\n return unavailableThread();\n const messages = threadModel.messages.map((row) =>\n messageSnapshot(id, row.data.rumorId)\n );\n return messages.some((row) => !row)\n ? unavailableThread()\n : {\n status: 'ready',\n messages: messages.filter((row) => row !== undefined)\n };\n }\n function replyOwnership(\n id: unknown,\n rumor: unknown\n ): InboxReplyOwnership | undefined {\n if (\n typeof rumor !== 'string' ||\n !messageSnapshot(id, rumor) ||\n !session ||\n !database ||\n !repository ||\n !unlocked\n )\n return;\n const proof = threadProofs.get(rumor);\n if (!proof) return;\n const data = conversationSnapshot(proof.room);\n if (!data) return;\n const generation = epoch,\n selection = threadEpoch,\n originalSession = session,\n originalRepository = repository,\n originalCache = unlocked,\n originalDatabase = database;\n const admitted = () =>\n current(generation) &&\n privateCurrent() &&\n selection === threadEpoch &&\n id === threadId &&\n threadPeer === data.peer &&\n session === originalSession &&\n repository === originalRepository &&\n unlocked === originalCache &&\n !!messageSnapshot(id, rumor) &&\n unlockedConversationCurrent(originalCache, proof.room);\n if (!admitted()) return;\n return {\n owner: capture.owner,\n identity: input.identity,\n session: originalSession,\n database: originalDatabase,\n repository: originalRepository,\n unlocked: originalCache,\n room: proof.room,\n setup: input.setup,\n peer: data.peer,\n parent: data.rumorId,\n current: admitted,\n async acceptLocalReply(receipt, review) {\n const saved = selfRecoveryAcknowledgementSnapshot(receipt);\n if (\n review !== 'reviewed_local_reply' ||\n !admitted() ||\n saved?.owner !== capture.owner ||\n saved.peer !== data.peer ||\n !(await verifySelfRecoveryAcknowledgement(\n originalRepository,\n receipt\n )) ||\n !admitted()\n )\n return false;\n // Presentation in this unlocked view only, backed by the actual native\n // self receipt. No order/notification or persistent acceptance field.\n if (!repliedPeers.includes(data.peer))\n repliedPeers = repliedPeers.concat(data.peer);\n listRevision++;\n await refreshList(generation);\n if (!admitted()) return false;\n notify();\n return true;\n }\n };\n }\n async function resolve(id: unknown, review: unknown) {\n if (review !== 'reviewed_conversation_navigation') return false;\n const selection = ++threadEpoch,\n generation = epoch;\n threadId = undefined;\n threadPeer = undefined;\n threadProofs.clear();\n threadModel = unavailableThread();\n notify();\n if (!directory || !privateCurrent()) return false;\n const result = await resolveLocalConversation(directory, id);\n if (\n selection !== threadEpoch ||\n !current(generation) ||\n !privateCurrent() ||\n result.status !== 'resolved' ||\n result.owner !== capture.owner\n )\n return false;\n threadId = result.conversationId;\n threadPeer = result.peer;\n refreshThread();\n notify();\n return true;\n }\n async function displayed(\n id: unknown,\n rumors: readonly string[],\n review: unknown\n ) {\n if (\n review !== 'reviewed_displayed_conversation' ||\n !Array.isArray(rumors) ||\n !metadata\n )\n return false;\n const rooms = threadRooms(id),\n selection = threadEpoch,\n generation = epoch,\n originalMetadata = metadata;\n if (!rooms || rumors.length > 2000) return false;\n for (const rumor of rumors) {\n const room = rooms.find(\n (value) => conversationSnapshot(value)?.rumorId === rumor\n );\n if (\n !room ||\n selection !== threadEpoch ||\n !current(generation) ||\n !privateCurrent() ||\n id !== threadId\n )\n return false;\n const result = await markDisplayedMessage(\n originalMetadata,\n room,\n 'displayed_message'\n );\n if (result.status !== 'saved' && result.status !== 'existing')\n return false;\n }\n if (selection !== threadEpoch || !current(generation) || !privateCurrent())\n return false;\n await refreshList(generation);\n return selection === threadEpoch && current(generation) && privateCurrent();\n }\n function rowSnapshot(peer: unknown): InboxListRow | undefined {\n if (\n typeof peer !== 'string' ||\n !privateCurrent() ||\n !unlocked ||\n !queue ||\n list.status !== 'ready'\n )\n return;\n const proof = rowProofs.get(peer);\n if (!proof || !unlockedConversationCurrent(unlocked, proof.room)) return;\n const actual = conversationSnapshot(proof.room);\n if (\n !actual ||\n actual.owner !== capture.owner ||\n actual.peer !== peer ||\n actual.rumorId !== proof.data.latest.rumorId\n )\n return;\n return { ...proof.data, latest: { ...actual } };\n }\n function listSnapshot(): InboxListSnapshot {\n if (!privateCurrent() || !unlocked || !queue)\n return { status: 'locked', requests: [], conversations: [] };\n if (list.status !== 'ready')\n return { status: list.status, requests: [], conversations: [] };\n const requests = list.requests.map((row) => rowSnapshot(row.peer)),\n conversations = list.conversations.map((row) => rowSnapshot(row.peer));\n if (requests.some((row) => !row) || conversations.some((row) => !row))\n return { status: 'unavailable', requests: [], conversations: [] };\n return {\n status: 'ready',\n requests: requests\n .filter((row) => row !== undefined)\n .filter((row) => !repliedPeers.includes(row.peer)),\n conversations: conversations\n .filter((row) => row !== undefined)\n .concat(\n requests\n .filter((row) => row !== undefined)\n .filter((row) => repliedPeers.includes(row.peer))\n )\n .sort(\n (a, b) =>\n b.latest.createdAt - a.latest.createdAt ||\n b.latest.rumorId.localeCompare(a.latest.rumorId) ||\n a.peer.localeCompare(b.peer)\n )\n };\n }\n async function refreshList(generation = epoch) {\n if (!privateCurrent() || !unlocked || !metadata) return false;\n try {\n const local = await messageMetadataSnapshot(metadata);\n const sends = repository && (await listPrivateSendRecords(repository));\n if (!current(generation) || !privateCurrent() || !unlocked) return false;\n sendRecords = sends?.ok ? sends.value : [];\n const cached = readUnlockedMessages(unlocked);\n if (\n local.status !== 'ready' ||\n local.owner !== capture.owner ||\n cached.status !== 'ready'\n ) {\n list = { status: 'unavailable', requests: [], conversations: [] };\n rowProofs.clear();\n listRevision++;\n listReason = 'storage_unavailable';\n return false;\n }\n list = groupInboxMessages(\n capture.owner,\n cached.messages,\n local.readRumors\n );\n rowProofs.clear();\n const rooms = queue && decryptionQueueConversations(queue),\n byRumor = new Map<string, AdmittedConversation>();\n for (const room of rooms ?? []) {\n const observed = conversationSnapshot(room);\n if (observed) byRumor.set(observed.rumorId, room);\n }\n for (const row of list.requests.concat(list.conversations)) {\n const room = byRumor.get(row.latest.rumorId);\n if (room) rowProofs.set(row.peer, { data: row, room });\n }\n refreshThread();\n listRevision++;\n listReason = list.status === 'ready' ? null : 'unavailable';\n return list.status === 'ready';\n } catch {\n if (current(generation) && privateCurrent()) {\n list = { status: 'unavailable', requests: [], conversations: [] };\n rowProofs.clear();\n listRevision++;\n listReason = 'storage_unavailable';\n }\n return false;\n }\n }\n function olderAvailable() {\n if (busy || !privateCurrent() || !unlocked || !repository || !sync)\n return false;\n const transport = inboxSyncSnapshot(sync),\n ownership = inboxSyncHistoryOwnership(sync),\n own = inboxSetupViewOwnership(input.setup),\n original = session && privateSessionOwnership(session);\n if (\n !own?.current() ||\n !own.resolver ||\n !original?.current() ||\n !ownership?.current() ||\n transport?.backfill !== 'complete' ||\n transport.pending !== 0\n )\n return false;\n return (\n messagingReadinessSnapshot(\n input.identity,\n session,\n own.policy,\n own.resolver,\n undefined,\n own.observeAccess\n ).ownAccess === 'qualified_exercised'\n );\n }\n async function open(peer: unknown, review: unknown) {\n if (\n review !== 'reviewed_admitted_conversation_navigation' ||\n busy ||\n !privateCurrent() ||\n !queue ||\n !directory ||\n !canonicalPublicKey(peer)\n )\n return;\n const room = decryptionQueueConversations(queue).find(\n (value) => conversationSnapshot(value)?.peer === peer\n );\n if (!room) return;\n const generation = epoch;\n busy = true;\n notify();\n try {\n const result = await rememberAdmittedConversation(\n directory,\n room,\n review\n );\n if (!current(generation) || !privateCurrent()) return;\n if (result.status !== 'saved' && result.status !== 'existing') {\n reason = 'unavailable';\n return;\n }\n await refreshList(generation);\n if (!current(generation) || !privateCurrent()) return;\n return '/messages/' + result.conversationId;\n } catch {\n if (current(generation)) reason = 'unavailable';\n return;\n } finally {\n if (current(generation)) {\n busy = false;\n notify();\n }\n }\n }\n async function loadOlder(review: unknown) {\n if (\n review !== 'reviewed_load_older' ||\n !olderAvailable() ||\n !sync ||\n !queue\n )\n return false;\n older ??= captureOlderInbox(sync, review);\n if (!older) return false;\n const generation = epoch;\n busy = true;\n notify();\n try {\n const result = await loadOlderInbox(older, review);\n if (!current(generation) || !privateCurrent() || !queue) return false;\n await refreshDecryptionQueue(queue);\n if (!current(generation) || !privateCurrent()) return false;\n await refreshList(generation);\n return current(generation) && privateCurrent() && result;\n } catch {\n if (current(generation)) reason = 'unavailable';\n return false;\n } finally {\n if (current(generation)) {\n busy = false;\n notify();\n }\n }\n }\n function snapshot(): InboxViewSnapshot {\n if (!current())\n return { ...unavailable(), cleanupRequired: pendingCleanup.length > 0 };\n const identity = identitySessionSnapshot(input.identity),\n setupState = inboxSetupViewSnapshot(input.setup);\n if (!privateCurrent() || !unlocked || !queue)\n return {\n ...unavailable(),\n owner: capture.owner,\n identity,\n state: busy\n ? 'unlocking'\n : [\n 'compatible',\n 'compatible_existing',\n 'access_unavailable',\n 'verified'\n ].includes(setupState.status)\n ? 'locked'\n : 'setup',\n reason,\n busy: busy || setupState.busy\n };\n const cached = readUnlockedMessages(unlocked),\n decrypt = decryptionQueueSnapshot(queue),\n paging = older && olderInboxSnapshot(older),\n transport = sync && inboxSyncSnapshot(sync);\n const scope = inboxSetupViewOwnership(input.setup);\n const exercised =\n !!scope?.resolver &&\n messagingReadinessSnapshot(\n input.identity,\n session,\n scope.policy,\n scope.resolver,\n undefined,\n scope.observeAccess\n ).ownAccess === 'qualified_exercised';\n if (!privateCurrent()) return unavailable();\n const partial =\n reason !== null ||\n !exercised ||\n cached.status !== 'ready' ||\n list.status === 'unavailable' ||\n !!paging?.reason ||\n decrypt.state === 'paused' ||\n transport?.state === 'needs_action' ||\n transport?.state === 'stopped';\n const checked =\n lastCheckedAt !== null && !!sync && !!inboxSyncHistoryOwnership(sync);\n return {\n state:\n busy || decrypt.busy\n ? 'unlocking'\n : partial\n ? 'partial'\n : checked && decrypt.queued === 0 && cached.messages.length === 0\n ? 'empty'\n : 'ready',\n reason:\n reason ??\n listReason ??\n paging?.reason ??\n decrypt.reason ??\n transport?.reason ??\n (!exercised ? 'access_unavailable' : null),\n busy: busy || decrypt.busy || setupState.busy,\n owner: capture.owner,\n identity,\n queued: decrypt.queued,\n count: cached.messages.length,\n lastCheckedAt,\n historyComplete: false,\n cleanupRequired: pendingCleanup.length > 0\n };\n }\n function notify() {\n for (const listener of listeners.values())\n try {\n listener(snapshot());\n } catch {\n /* Isolate presentation. */\n }\n }\n function releasePrivate() {\n privateOff();\n privateOff = () => {};\n const originalQueue = queue,\n originalSync = sync,\n originalUnlocked = unlocked,\n originalSession = session,\n originalDatabase = database,\n originalDirectory = directory,\n originalOlder = older;\n const tasks = pendingCleanup.concat([\n () => {\n if (originalOlder) stopOlderInbox(originalOlder);\n },\n () => {\n if (originalDirectory) closeConversationDirectory(originalDirectory);\n },\n () => {\n if (originalQueue) stopDecryptionQueue(originalQueue);\n },\n () => {\n if (originalSync) stopInboxSync(originalSync);\n },\n () => {\n if (originalUnlocked) closeUnlockedSession(originalUnlocked);\n },\n () => {\n if (originalSession && !closePrivateSession(originalSession))\n throw Error('private_cleanup_required');\n },\n () => {\n if (originalDatabase) closeBrowserDatabase(originalDatabase);\n }\n ]);\n pendingCleanup = [];\n for (const cleanup of tasks)\n try {\n cleanup();\n } catch {\n pendingCleanup = pendingCleanup.concat(cleanup);\n }\n if (pendingCleanup.length > 0) reason = 'cleanup_required';\n threadEpoch++;\n threadProofs.clear();\n threadModel = unavailableThread();\n threadId = undefined;\n threadPeer = undefined;\n sendRecords = [];\n repliedPeers = [];\n metadata = undefined;\n directory = undefined;\n older = undefined;\n list = { status: 'locked', requests: [], conversations: [] };\n listReason = null;\n rowProofs.clear();\n listRevision++;\n queue = undefined;\n sync = undefined;\n unlocked = undefined;\n session = undefined;\n repository = undefined;\n database = undefined;\n lastCheckedAt = null;\n checkPending = false;\n }\n function stop() {\n epoch++;\n reason = 'stopped';\n releasePrivate();\n busy = false;\n notify();\n }\n async function sample() {\n if (sampling || closed) return;\n if (!current()) {\n notify();\n return;\n }\n observeInboxSetupView(input.setup);\n if (!queue || !privateCurrent()) {\n notify();\n return;\n }\n sampling = true;\n const generation = epoch;\n try {\n const transport = sync && inboxSyncSnapshot(sync);\n // Read native ciphertext only after actual ingress changes, never on\n // every idle presentation tick and never as automatic SDK decryption.\n if (\n transport &&\n transport.pending === 0 &&\n transport.retained !== refreshedRetained &&\n !decryptionQueueSnapshot(queue).busy\n ) {\n const retained = transport.retained;\n const refreshed = await refreshDecryptionQueue(queue);\n if (!current(generation) || !privateCurrent()) return;\n refreshedRetained = retained;\n if (!refreshed) {\n notify();\n return;\n }\n }\n if (!current(generation) || !privateCurrent()) return;\n if (\n checkPending &&\n sync &&\n transport?.backfill === 'complete' &&\n transport.pending === 0 &&\n inboxSyncHistoryOwnership(sync)?.current()\n ) {\n const checked = Date.now();\n if (\n current(generation) &&\n privateCurrent() &&\n inboxSyncHistoryOwnership(sync)?.current()\n ) {\n lastCheckedAt = checked;\n checkPending = false;\n }\n }\n notify();\n } catch {\n if (current(generation)) {\n reason = 'unavailable';\n notify();\n }\n } finally {\n sampling = false;\n }\n }\n async function read(reviewed: unknown) {\n if (\n reviewed !== 'reviewed_decrypt_batch' ||\n (input.conversationId !== undefined &&\n (threadId !== input.conversationId || !threadPeer)) ||\n busy ||\n !queue ||\n !privateCurrent()\n )\n return false;\n busy = true;\n reason = null;\n const generation = epoch;\n notify();\n try {\n const result = await runDecryptionBatch(queue, reviewed);\n if (!current(generation) || !privateCurrent()) return false;\n await refreshList(generation);\n return current(generation) && privateCurrent() && result;\n } finally {\n if (current(generation)) {\n busy = false;\n notify();\n }\n }\n }\n async function unlock(reviewed: unknown) {\n if (reviewed !== 'reviewed_messages_unlock' || busy || !current())\n return false;\n if (queue && privateCurrent()) return await read('reviewed_decrypt_batch');\n const setupState = inboxSetupViewSnapshot(input.setup);\n if (\n ![\n 'compatible',\n 'compatible_existing',\n 'access_unavailable',\n 'verified'\n ].includes(setupState.status)\n )\n return false;\n busy = true;\n reason = null;\n const generation = epoch;\n notify();\n try {\n await unlockInboxSetupView(input.setup);\n if (!current(generation)) return false;\n const original = inboxSetupViewOwnership(input.setup),\n acquired = original?.session,\n owner = acquired && privateSessionOwnership(acquired);\n if (\n !original?.resolver ||\n !acquired ||\n !owner?.current() ||\n owner.owner !== capture.owner ||\n owner.session !== capture.session ||\n !original.current()\n )\n return false;\n session = acquired;\n const opened = await openBrowserDatabase();\n if (!current(generation) || !privateCurrent()) {\n if (opened.state === 'ready') closeBrowserDatabase(opened.owner);\n return false;\n }\n if (opened.state !== 'ready') {\n reason = 'storage_unavailable';\n return false;\n }\n database = opened.owner;\n repository = createPrivateStorageRepository(database, capture.owner);\n unlocked = captureUnlockedSession(session, reviewed);\n queue =\n repository &&\n unlocked &&\n captureDecryptionQueue(\n repository,\n session,\n input.identity,\n unlocked,\n 'reviewed_inbox_unlock'\n );\n if (!queue || !unlocked) {\n reason = 'unavailable';\n return false;\n }\n metadata = captureMessageMetadata(\n database,\n session,\n unlocked,\n 'reviewed_local_message_metadata'\n );\n directory =\n metadata &&\n captureConversationDirectory(\n session,\n metadata,\n 'reviewed_conversation_directory'\n );\n if (!metadata || !directory) {\n reason = 'storage_unavailable';\n return false;\n }\n privateOff = subscribePrivateSessionClose(session, () => {\n epoch++;\n releasePrivate();\n busy = false;\n notify();\n if (pendingCleanup.length > 0)\n queueMicrotask(() => {\n releasePrivate();\n notify();\n });\n });\n if (!privateCurrent()) return false;\n if (\n input.conversationId !== undefined &&\n !(await resolve(\n input.conversationId,\n 'reviewed_conversation_navigation'\n ))\n ) {\n reason = 'unavailable';\n return false;\n }\n const result = await runDecryptionBatch(queue, 'reviewed_decrypt_batch');\n if (!current(generation) || !privateCurrent()) return false;\n await refreshList(generation);\n return current(generation) && privateCurrent() && result;\n } catch {\n if (current(generation)) reason = 'unavailable';\n return false;\n } finally {\n if (current(generation)) {\n busy = false;\n notify();\n }\n }\n }\n async function check(reviewed: unknown) {\n if (\n reviewed !== 'reviewed_foreground_inbox' ||\n busy ||\n !privateCurrent() ||\n !session ||\n !repository ||\n !unlocked\n )\n return false;\n const scope = inboxSetupViewOwnership(input.setup);\n if (!scope?.resolver || !scope.current() || !scope.observeAccess) {\n reason = 'access_unavailable';\n notify();\n return false;\n }\n const generation = epoch;\n reason = null;\n if (sync) {\n if (\n !refreshInboxSync(\n sync,\n reviewed,\n lastCheckedAt === null ? undefined : Math.floor(lastCheckedAt / 1000)\n )\n ) {\n reason = inboxSyncSnapshot(sync)?.reason ?? 'check_incomplete';\n notify();\n return false;\n }\n } else {\n sync = captureInboxSync(\n repository,\n session,\n scope.policy,\n scope.resolver,\n unlocked,\n scope.observeAccess,\n reviewed\n );\n if (!sync || !startInboxSync(sync, reviewed)) {\n reason = 'access_unavailable';\n notify();\n return false;\n }\n }\n checkPending = true;\n notify();\n await sample();\n if (current(generation) && privateCurrent()) await refreshList(generation);\n return current(generation) && privateCurrent();\n }\n views.set(token, {\n reply: replyOwnership,\n snapshot,\n thread: threadSnapshot,\n threadRevision: () => (privateCurrent() ? listRevision + threadEpoch : -1),\n message: messageSnapshot,\n resolve,\n displayed,\n list: listSnapshot,\n row: rowSnapshot,\n revision: () => (privateCurrent() ? listRevision : -1),\n open,\n older: loadOlder,\n olderAvailable,\n setup: () => (current() ? input.setup : undefined),\n subscribe(listener) {\n const key = Symbol();\n listeners.set(key, listener);\n listener(snapshot());\n return () => {\n listeners.delete(key);\n };\n },\n unlock,\n check,\n read,\n stop,\n close() {\n // Retain this first terminal fanout before cleanup can reenter Close or\n // unsubscribe another observer. Authority is revoked before callbacks.\n const terminalListeners = closed ? [] : Array.from(listeners.values());\n if (!closed) {\n closed = true;\n epoch++;\n clearInterval(timer);\n off();\n setupOff();\n }\n releasePrivate();\n // Cleanup retains the original genuine setup independently of current\n // admission. Logout hides effect access, while disposal still closes\n // its identity observer, database and runtime public-view owner.\n try {\n closeInboxSetupView(input.setup);\n } catch {\n pendingCleanup = pendingCleanup.concat(() =>\n closeInboxSetupView(input.setup)\n );\n }\n listeners.clear();\n for (const listener of terminalListeners)\n try {\n listener(snapshot());\n } catch {\n /* Isolate terminal presentation without stranding other observers. */\n }\n return pendingCleanup.length === 0;\n }\n });\n off = subscribeIdentityInvalidation(input.identity, () => {\n if (!capture.current()) {\n epoch++;\n releasePrivate();\n busy = false;\n notify();\n }\n });\n setupOff = subscribeInboxSetupView(input.setup, notify);\n const timer = setInterval(() => {\n void sample();\n }, 200);\n if (!current()) {\n views.get(token)?.close();\n return;\n }\n return token;\n}\nexport function inboxViewSnapshot(\n token: InboxView | undefined\n): InboxViewSnapshot {\n return (token && views.get(token)?.snapshot()) || unavailable();\n}\nexport function inboxViewSetup(\n token: InboxView | undefined\n): InboxSetupView | undefined {\n return token && views.get(token)?.setup();\n}\nexport function subscribeInboxView(\n token: InboxView | undefined,\n listener: (view: InboxViewSnapshot) => void\n): () => void {\n return (token && views.get(token)?.subscribe(listener)) || (() => {});\n}\nexport function unlockInboxView(\n token: InboxView,\n review: unknown\n): Promise<boolean> {\n return views.get(token)?.unlock(review) ?? Promise.resolve(false);\n}\nexport function checkInboxView(\n token: InboxView,\n review: unknown\n): Promise<boolean> {\n return views.get(token)?.check(review) ?? Promise.resolve(false);\n}\nexport function readNewInboxView(\n token: InboxView,\n review: unknown\n): Promise<boolean> {\n return views.get(token)?.read(review) ?? Promise.resolve(false);\n}\nexport function stopInboxView(token: InboxView): void {\n views.get(token)?.stop();\n}\nexport function closeInboxView(token: InboxView): boolean {\n return views.get(token)?.close() ?? true;\n}\n\n// Fresh genuine original cache observation. Returned rows are detached and\n// never replace the original room/native authority used by explicit Open.\nexport function inboxListSnapshot(\n token: InboxView | undefined\n): InboxListSnapshot {\n return (\n (token && views.get(token)?.list()) || {\n status: 'unavailable',\n requests: [],\n conversations: []\n }\n );\n}\nexport function openInboxConversation(\n token: InboxView,\n peer: unknown,\n review: unknown\n): Promise<string | undefined> {\n return views.get(token)?.open(peer, review) ?? Promise.resolve(undefined);\n}\nexport function loadOlderInboxView(\n token: InboxView,\n review: unknown\n): Promise<boolean> {\n return views.get(token)?.older(review) ?? Promise.resolve(false);\n}\nexport function inboxViewOlderAvailable(token: InboxView | undefined): boolean {\n return !!token && !!views.get(token)?.olderAvailable();\n}\n\nexport function inboxConversationRow(\n token: InboxView | undefined,\n peer: unknown\n): InboxListRow | undefined {\n return token ? views.get(token)?.row(peer) : undefined;\n}\nexport function inboxListRevision(token: InboxView | undefined): number {\n return token ? (views.get(token)?.revision() ?? -1) : -1;\n}\n\nexport function inboxThreadSnapshot(\n token: InboxView | undefined,\n id: unknown\n): ThreadSnapshot {\n return (token && views.get(token)?.thread(id)) || unavailableThread();\n}\nexport function inboxMessageSnapshot(\n token: InboxView,\n id: unknown,\n rumor: unknown\n): ThreadMessage | undefined {\n return views.get(token)?.message(id, rumor);\n}\nexport function resolveInboxConversation(\n token: InboxView,\n id: unknown,\n review: unknown\n): Promise<boolean> {\n return views.get(token)?.resolve(id, review) ?? Promise.resolve(false);\n}\nexport function markInboxConversationDisplayed(\n token: InboxView,\n id: unknown,\n rumors: readonly string[],\n review: unknown\n): Promise<boolean> {\n return (\n views.get(token)?.displayed(id, rumors, review) ?? Promise.resolve(false)\n );\n}\n\nexport function inboxThreadRevision(token: InboxView | undefined): number {\n return token ? (views.get(token)?.threadRevision() ?? -1) : -1;\n}\n\nexport function inboxReplyOwnership(\n token: InboxView,\n id: unknown,\n rumor: unknown\n): InboxReplyOwnership | undefined {\n return views.get(token)?.reply(id, rumor);\n}\n", 307 sha256: 308 'f725d1e122550232efa52b26139d3047d3bbfd6d3d11b1ef0a110b5e4b4410dc' 309 }, 310 'src/lib/messaging/cited-product.ts': { 311 source: 312 "import { includedProductVersion } from '../nostr/enquiry-references.ts';\nimport { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';\nimport { decodeProductReference } from '../nostr/references.ts';\nimport {\n inboxMessageSnapshot,\n inboxReplyOwnership,\n inboxThreadSnapshot,\n type InboxReplyOwnership,\n type InboxView\n} from './inbox-view.ts';\nimport {\n createPublicView,\n beginPublicViewRun,\n disposePublicView,\n publicViewRunCurrent,\n publicViewOwnsRun,\n publicViewProjectionAvailable,\n subscribePublicView,\n type PublicView,\n type PublicRuntime\n} from '../runtime/public-runtime.ts';\nimport {\n publicRequestScopeSnapshot,\n type PublicRequest\n} from '../nostr/request-scope.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from '../catalog/heads.ts';\nimport {\n createPublicViewHeadResolver,\n headResolutionSnapshot,\n resolveHeads,\n closeHeadResolver\n} from '../catalog/resolve-head.ts';\nimport { subscribePrivateSessionClose } from '../runtime/private-session.ts';\nimport { subscribeIdentityInvalidation } from '../runtime/identity-session.ts';\nimport type { FoodProjection } from '../contracts/food-availability-v1/read.ts';\n\ndeclare const citedBrand: unique symbol;\nexport type CitedProduct = Readonly<{ [citedBrand]: true }>;\ntype Snapshot = Readonly<{\n outcome: 'checking' | 'unresolved' | 'active' | 'sold' | 'withdrawn';\n food?: FoodProjection;\n lastKnownFood?: FoodProjection;\n includedVersion: 'none' | 'unverified' | 'matched' | 'different';\n}>;\nconst owners = new WeakMap<\n CitedProduct,\n { snapshot(): Snapshot | undefined; close(): void }\n>();\n\nexport function conversationOptionsSnapshot(\n view: InboxView,\n id: string\n): Readonly<{ peer: string }> | undefined {\n const thread = inboxThreadSnapshot(view, id);\n for (const row of thread.messages) {\n const original = inboxReplyOwnership(view, id, row.data.rumorId);\n if (original?.current()) return { peer: original.peer };\n }\n return undefined;\n}\nexport function requestConversationOption(\n view: InboxView,\n id: string,\n action: 'block' | 'report',\n invoke: (peer: string) => void,\n review: unknown\n): boolean {\n if (\n review !== 'reviewed_conversation_option' ||\n (action !== 'block' && action !== 'report')\n )\n return false;\n const actual = conversationOptionsSnapshot(view, id);\n if (!actual) return false;\n invoke(actual.peer);\n return true;\n}\n\n// Neither a copied row nor a body pointer is authority. Resolve the selector\n// against the current original private room before allocating an anonymous view.\nexport function captureCitedProduct(\n inbox: InboxView,\n id: string,\n rumor: string,\n value: unknown,\n runtime: PublicRuntime,\n review: unknown\n): CitedProduct | undefined {\n if (typeof window === 'undefined' || review !== 'reviewed_product_citation')\n return undefined;\n const original = inboxReplyOwnership(inbox, id, rumor),\n message = inboxMessageSnapshot(inbox, id, rumor),\n decoded = decodeProductReference(value);\n if (\n !original?.current() ||\n !message ||\n !decoded ||\n !message.citations.some((row) => row.naddr === decoded.naddr) ||\n ![original.owner, original.peer].includes(decoded.pubkey)\n )\n return undefined;\n const reference = decoded;\n const privateIds = inboxThreadSnapshot(inbox, id).messages.flatMap((row) => [\n row.data.rumorId,\n ...(row.data.replyTo ? [row.data.replyTo] : [])\n ]);\n if (privateIds.includes(reference.identifier)) return undefined;\n let versions = Array.from<string>([]);\n for (const match of message.data.content.matchAll(\n /\\b(nevent1[023456789acdefghjklmnpqrstuvwxyz]+)\\b/gi\n )) {\n const version = includedProductVersion(match[1], reference.pubkey);\n if (version && !privateIds.includes(version) && !versions.includes(version))\n versions = versions.concat(version);\n }\n const exactId = versions.length === 1 ? versions[0] : undefined;\n let view: PublicView;\n try {\n view = createPublicView(runtime);\n } catch {\n return undefined;\n }\n const run = beginPublicViewRun(view),\n resolver = createPublicViewHeadResolver(view, run, {\n nowSeconds: () => Math.floor(Date.now() / 1000)\n });\n let closed = false,\n failed = false,\n head: PublicHead | undefined,\n exact: string | undefined;\n let privateScope: InboxReplyOwnership | undefined = original;\n const requests = new Map<PublicRequest, true>();\n let offPrivate = () => {},\n offIdentity = () => {};\n function close() {\n if (closed) return;\n closed = true;\n privateScope = undefined;\n offPrivate();\n offIdentity();\n try {\n closeHeadResolver(resolver);\n } finally {\n disposePublicView(view);\n }\n }\n const owned = () =>\n !closed &&\n !!privateScope?.current() &&\n !!inboxMessageSnapshot(inbox, id, rumor) &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n const current = () => owned() && publicViewRunCurrent(view, run);\n const token = Object.freeze({}) as CitedProduct;\n owners.set(token, {\n close,\n snapshot() {\n if (!owned()) {\n close();\n return undefined;\n }\n const row = headResolutionSnapshot(resolver)[0],\n scopes = Array.from(requests.keys(), publicRequestScopeSnapshot);\n const pending =\n current() &&\n [\n ...scopes,\n ...(row?.headSources ? [row.headSources] : []),\n ...(row?.deletionSources ? [row.deletionSources] : [])\n ].some((scope) => scope.state === 'active');\n const suppressed = row?.deletion.outcome === 'suppressed';\n // A retained signed head is not a completed coordinate/withdrawal read.\n // Original source coverage must remain honest after ordinary run expiry.\n const complete =\n row?.coverage === 'bounded-eose' &&\n !row.lastKnown &&\n scopes.length > 0 &&\n scopes.every(\n (scope) =>\n scope.state === 'eose' && scope.result.coverage === 'bounded-eose'\n );\n const food =\n !suppressed && !pending && !failed && complete\n ? row?.state.food\n : undefined;\n return {\n outcome: suppressed\n ? 'withdrawn'\n : pending\n ? 'checking'\n : food\n ? food.status\n : 'unresolved',\n food,\n lastKnownFood:\n !suppressed && !pending && !food ? row?.state.food : undefined,\n includedVersion: !exactId\n ? 'none'\n : !exact || !food\n ? 'unverified'\n : exact === row?.state.head.id\n ? 'matched'\n : 'different'\n };\n }\n });\n offPrivate = subscribePrivateSessionClose(original.session, close);\n offIdentity = subscribeIdentityInvalidation(original.identity, close);\n function admit(\n proof: Parameters<typeof createPublicHeadCandidate>[0],\n exactOnly: boolean\n ) {\n if (!current()) return;\n const candidate = createPublicHeadCandidate(proof);\n if (!candidate) return;\n const data = publicHeadSnapshot(candidate);\n if (\n data.kind !== 30402 ||\n data.pubkey !== reference.pubkey ||\n data.identifier !== reference.identifier\n )\n return;\n if (exactOnly) {\n if (data.id === exactId) exact = data.id;\n return;\n }\n head = selectPublicHead(head, candidate).head;\n try {\n resolveHeads(resolver, [head]);\n } catch {\n failed = true;\n }\n }\n try {\n const request = subscribePublicView(\n view,\n run,\n 'head',\n [\n {\n kinds: [30402],\n authors: [reference.pubkey],\n '#d': [reference.identifier],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n ],\n (proof) => admit(proof, false)\n );\n requests.set(request, true);\n if (exactId && current())\n requests.set(\n subscribePublicView(\n view,\n run,\n 'head',\n [\n {\n kinds: [30402],\n authors: [reference.pubkey],\n ids: [exactId],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n ],\n (proof) => admit(proof, true)\n ),\n true\n );\n } catch {\n failed = true;\n }\n return token;\n}\nexport function citedProductSnapshot(\n token: CitedProduct\n): Snapshot | undefined {\n return owners.get(token)?.snapshot();\n}\nexport function closeCitedProduct(token: CitedProduct): void {\n owners.get(token)?.close();\n}\n", 313 sha256: 314 'b4a43fad9b020cf647350350e5d0195df9a80d772ab6910e0e9fb8c11b4b0e48' 315 }, 316 'src/lib/components/ConversationOptions.svelte': { 317 source: 318 "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import {\n subscribeInboxView,\n type InboxView\n } from '../messaging/inbox-view.ts';\n import {\n conversationOptionsSnapshot,\n requestConversationOption\n } from '../messaging/cited-product.ts';\n let {\n controller,\n conversationId,\n onblock,\n onreport\n }: {\n controller: InboxView;\n conversationId: string;\n onblock?: (peer: string) => void;\n onreport?: (peer: string) => void;\n } = $props();\n let revision = $state(0);\n const actual = $derived.by(() => {\n void revision;\n return conversationOptionsSnapshot(controller, conversationId);\n });\n onMount(() =>\n subscribeInboxView(controller, () => {\n revision++;\n })\n );\n</script>\n\n{#if actual}\n <details>\n <summary>Identity and conversation options</summary>\n <p>Authenticated conversation peer: {actual.peer}</p>\n {#if onblock}<button\n type=\"button\"\n onclick={() => {\n if (onblock)\n requestConversationOption(\n controller,\n conversationId,\n 'block',\n onblock,\n 'reviewed_conversation_option'\n );\n }}>Block person</button\n >{/if}\n {#if onreport}<button\n type=\"button\"\n onclick={() => {\n if (onreport)\n requestConversationOption(\n controller,\n conversationId,\n 'report',\n onreport,\n 'reviewed_conversation_option'\n );\n }}>Report conversation</button\n >{/if}\n </details>\n{/if}\n", 319 sha256: 320 'a33d9ffb13e28ce985799fa69342c8fa63816da70e1f9383d4e8e82f5a393c6d' 321 }, 322 'src/lib/components/ConversationThread.svelte': { 323 source: 324 "<script lang=\"ts\">\n import { getContext, onMount, tick } from 'svelte';\n import InboxStatus from './InboxStatus.svelte';\n import Button from './primitives/Button.svelte';\n import MessageItem from './MessageItem.svelte';\n import ConversationOptions from './ConversationOptions.svelte';\n import MessageComposer from './MessageComposer.svelte';\n import {\n createReplyController,\n createRuntimeReplyController,\n selectReplyParent,\n replySnapshot,\n closeReplyController,\n type ReplyController\n } from '../messaging/reply-controller.ts';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSession,\n subscribeIdentityView,\n type IdentityViewContext\n } from '../runtime/view-context.ts';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n type PublicRuntimeContext,\n type PublicRuntime\n } from '../runtime/public-runtime.ts';\n import {\n createRuntimeInboxSetupView,\n closeInboxSetupView\n } from '../messaging/inbox-setup-view.ts';\n import {\n createInboxView,\n inboxViewSnapshot,\n inboxViewSetup,\n subscribeInboxView,\n closeInboxView,\n inboxThreadSnapshot,\n inboxThreadRevision,\n markInboxConversationDisplayed,\n type InboxView\n } from '../messaging/inbox-view.ts';\n let {\n controller,\n conversationId\n }: { controller?: InboxView; conversationId: string } = $props();\n const identity = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT),\n publicContext = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);\n let owned = $state.raw<InboxView | undefined>(),\n reply = $state.raw<ReplyController | undefined>(),\n model = $state(inboxThreadSnapshot(undefined, '')),\n announcement = $state(''),\n readProblem = $state(false),\n retryRevision = $state(0),\n displayedPending = $state(false);\n let runtime = $state.raw<PublicRuntime | undefined>();\n let off = () => {},\n initialized = false,\n previous = Array.from<string>([]),\n attempted = Array.from<string>([]),\n disposed = false;\n function captureReply(parent: string) {\n if (!owned) return;\n return runtime\n ? createRuntimeReplyController(owned, conversationId, parent, runtime)\n : createReplyController(owned, conversationId, parent);\n }\n function replyTo(parent: string) {\n if (reply && replySnapshot(reply)?.dirty) {\n selectReplyParent(reply, parent, 'reviewed_reply_parent');\n return;\n }\n if (reply) closeReplyController(reply);\n reply = captureReply(parent);\n }\n onMount(() => {\n let observedRevision = -2,\n observedMode = '';\n function acquire() {\n if (disposed) return;\n if (owned && inboxViewSnapshot(owned).owner) return;\n off();\n if (owned && !controller) closeInboxView(owned);\n owned = controller;\n if (!owned && runtime) {\n const session = identityViewSession(identity),\n setup = createRuntimeInboxSetupView(identity, runtime);\n if (session && setup) {\n owned = createInboxView({ identity: session, setup, conversationId });\n if (!owned) closeInboxSetupView(setup);\n }\n }\n observedRevision = -2;\n off = subscribeInboxView(owned, (panel) => {\n const revision = inboxThreadRevision(owned),\n mode = panel.state + ':' + panel.count + ':' + (panel.reason ?? '');\n if (revision === observedRevision && mode === observedMode) return;\n observedRevision = revision;\n observedMode = mode;\n const next = inboxThreadSnapshot(owned, conversationId);\n if (next.status !== 'ready') {\n if (reply) closeReplyController(reply);\n reply = undefined;\n model = next;\n announcement = '';\n readProblem = false;\n initialized = false;\n previous = [];\n attempted = [];\n return;\n }\n const ids = next.messages.map((row) => row.data.rumorId),\n added = ids.filter((id) => !previous.includes(id)).length;\n if (ids.length > 0 && initialized && added)\n announcement =\n added + (added === 1 ? ' message added.' : ' messages added.');\n if (ids.length > 0) initialized = true;\n previous = ids;\n model = next;\n if (!reply && ids.length) reply = captureReply(ids[ids.length - 1]);\n });\n }\n const identityOff = identity\n ? subscribeIdentityView(identity, acquire)\n : () => {};\n acquire();\n if (!controller && publicContext)\n void publicRuntimeReady(publicContext)\n .then((value) => {\n if (!disposed) {\n runtime = value;\n acquire();\n }\n })\n .catch(() => {});\n return () => {\n disposed = true;\n identityOff();\n off();\n if (reply) closeReplyController(reply);\n if (owned && !controller) {\n const setup = inboxViewSetup(owned);\n closeInboxView(owned);\n if (setup) closeInboxSetupView(setup);\n }\n };\n });\n $effect(() => {\n const original = owned,\n selected = conversationId,\n rows = model.messages;\n void retryRevision;\n if (!original || model.status !== 'ready' || displayedPending) return;\n const ids = rows\n .map((row) => row.data.rumorId)\n .filter((id) => !attempted.includes(id));\n if (!ids.length) return;\n attempted = attempted.concat(ids);\n displayedPending = true;\n void tick()\n .then(async () => {\n if (disposed || owned !== original || conversationId !== selected)\n return;\n const actual = inboxThreadSnapshot(original, selected);\n if (\n actual.status !== 'ready' ||\n ids.some(\n (id) => !actual.messages.some((row) => row.data.rumorId === id)\n )\n )\n return;\n const result = await markInboxConversationDisplayed(\n original,\n selected,\n ids,\n 'reviewed_displayed_conversation'\n );\n if (!disposed && owned === original && conversationId === selected)\n readProblem = !result;\n })\n .finally(() => {\n displayedPending = false;\n });\n });\n</script>\n\n{#if owned}<InboxStatus\n controller={owned}\n showLists={false}\n manageController={false}\n />{:else}<InboxStatus showLists={false} manageController={false} />{/if}\n<div class=\"page page--reading stack\">\n <h2>Conversation</h2>\n {#if owned && model.status === 'ready'}\n <ConversationOptions controller={owned} {conversationId} />\n {#each model.messages as message (message.data.rumorId)}<MessageItem\n controller={owned}\n {conversationId}\n {message}\n {runtime}\n onreply={replyTo}\n />{/each}\n {#if reply}{#key reply}<MessageComposer\n controller={reply}\n focusScope=\"conversation\"\n />{/key}{/if}\n {:else}<p>\n This conversation is unavailable until it is unlocked in the matching\n browser and account.\n </p>{/if}\n {#if readProblem}<p class=\"notice\">\n Local read status could not be confirmed. Encrypted copies are preserved.\n </p>\n <Button\n label=\"Retry local read status\"\n disabled={displayedPending}\n onclick={() => {\n attempted = [];\n readProblem = false;\n retryRevision++;\n }}\n />{/if}\n <p role=\"status\" aria-live=\"polite\" data-thread-announcement>\n {announcement}\n </p>\n <a href=\"/messages\">Back to messages</a>\n</div>\n", 325 sha256: 326 'ae59e6c06c0c5a86a58f49abed0ac9702631a694605b2c6686dfa65db0359080' 327 }, 328 'src/lib/components/InboxStatus.svelte': { 329 source: 330 "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import { goto } from '$app/navigation';\n import { internalHref } from '../navigation-url.ts';\n import ConversationRow from './ConversationRow.svelte';\n import CapabilityGate from './CapabilityGate.svelte';\n import InboxSetup from './InboxSetup.svelte';\n import Button from './primitives/Button.svelte';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n identityViewSession,\n subscribeIdentityView,\n connectIdentityView,\n probeIdentityViewMessaging,\n disconnectIdentityView,\n type IdentityViewContext\n } from '../runtime/view-context.ts';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n type PublicRuntimeContext,\n type PublicRuntime\n } from '../runtime/public-runtime.ts';\n import {\n createRuntimeInboxSetupView,\n closeInboxSetupView\n } from '../messaging/inbox-setup-view.ts';\n import {\n createInboxView,\n inboxViewSnapshot,\n inboxListSnapshot,\n inboxListRevision,\n openInboxConversation,\n loadOlderInboxView,\n inboxViewOlderAvailable,\n inboxViewSetup,\n subscribeInboxView,\n unlockInboxView,\n checkInboxView,\n readNewInboxView,\n stopInboxView,\n closeInboxView,\n type InboxView\n } from '../messaging/inbox-view.ts';\n let {\n controller,\n showLists = true,\n manageController = true\n }: {\n controller?: InboxView;\n showLists?: boolean;\n manageController?: boolean;\n } = $props();\n const identityContext = getContext<IdentityViewContext>(\n IDENTITY_VIEW_CONTEXT\n ),\n publicContext = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);\n let identity = $state(identityViewSnapshot(identityContext)),\n panel = $state(inboxViewSnapshot(undefined)),\n list = $state(inboxListSnapshot(undefined)),\n olderAvailable = $state(false),\n owned = $state.raw<InboxView | undefined>();\n let runtime: PublicRuntime | undefined,\n off = () => {};\n const setup = $derived(inboxViewSetup(owned));\n onMount(() => {\n let observedRevision = -2,\n observedMode = '';\n function updateList() {\n const revision = inboxListRevision(owned),\n mode = panel.state + ':' + panel.count + ':' + (panel.reason ?? '');\n if (revision !== observedRevision || mode !== observedMode) {\n list = inboxListSnapshot(owned);\n observedRevision = revision;\n observedMode = mode;\n }\n }\n let disposed = false;\n function acquire() {\n if (disposed) return;\n identity = identityViewSnapshot(identityContext);\n if (owned && inboxViewSnapshot(owned).owner) return;\n off();\n if (owned && !controller) {\n const oldSetup = inboxViewSetup(owned);\n closeInboxView(owned);\n if (oldSetup) closeInboxSetupView(oldSetup);\n }\n owned = controller;\n if (\n !owned &&\n runtime &&\n identity.identity.state === 'messaging_capable'\n ) {\n const session = identityViewSession(identityContext),\n originalSetup = createRuntimeInboxSetupView(identityContext, runtime);\n if (session && originalSetup) {\n owned = createInboxView({ identity: session, setup: originalSetup });\n if (!owned) closeInboxSetupView(originalSetup);\n }\n }\n panel = inboxViewSnapshot(owned);\n observedRevision = -2;\n updateList();\n olderAvailable = inboxViewOlderAvailable(owned);\n off = subscribeInboxView(owned, (next) => {\n panel = next;\n updateList();\n olderAvailable = inboxViewOlderAvailable(owned);\n });\n }\n const identityOff = identityContext\n ? subscribeIdentityView(identityContext, acquire)\n : () => {};\n acquire();\n if (manageController && !controller && publicContext)\n void publicRuntimeReady(publicContext)\n .then((value) => {\n if (disposed) return;\n runtime = value;\n acquire();\n })\n .catch(() => {\n /* Keep genuine unavailable state. */\n });\n return () => {\n disposed = true;\n identityOff();\n off();\n if (owned && !controller) {\n const originalSetup = inboxViewSetup(owned);\n closeInboxView(owned);\n if (originalSetup) closeInboxSetupView(originalSetup);\n }\n };\n });\n async function openConversation(peer: string) {\n const original = owned;\n if (!original) return;\n const result = await openInboxConversation(\n original,\n peer,\n 'reviewed_admitted_conversation_navigation'\n );\n const href = internalHref(result);\n if (owned !== original || inboxListSnapshot(original).status !== 'ready')\n return;\n if (href) void goto(href);\n }\n const effectiveIdentity = $derived(\n panel.owner ? panel.identity : identity.identity\n );\n const reasons: Record<string, string> = {\n access_unavailable:\n 'Inbox access has not been qualified and exercised. Unlocked local copies do not prove a successful relay check.',\n storage_unavailable:\n 'Browser storage is unavailable. Your inbox has not been checked.',\n unavailable:\n 'The message check could not complete. Existing encrypted copies are preserved.',\n elapsed:\n 'The bounded inbox check reached its active work limit. Existing encrypted copies are preserved.',\n budget:\n 'The bounded inbox check reached its item or size limit. Continue only after reviewing the limit.',\n declined:\n 'Your extension did not approve decryption. Choose Read new messages to try another explicit batch.',\n refused:\n 'Your extension did not approve decryption. Choose Read new messages to try another explicit batch.',\n stopped: 'Messages are locked. Existing encrypted copies are preserved.',\n wait_expired:\n 'Decryption is paused. Wait for the original extension request to settle before another explicit batch.'\n };\n const checked = $derived(\n panel.lastCheckedAt === null\n ? null\n : new Date(panel.lastCheckedAt).toLocaleTimeString()\n );\n</script>\n\n<svelte:head\n ><title>HarvestCircle</title><meta\n name=\"robots\"\n content=\"noindex\"\n /></svelte:head\n>\n<div class=\"page page--reading stack\">\n <h1>\n {effectiveIdentity.state === 'guest' ||\n effectiveIdentity.state === 'pending'\n ? 'Connect or unlock'\n : 'Messages'}\n </h1>\n {#if panel.cleanupRequired}<p class=\"notice\">\n Private resource cleanup is incomplete. Wait before reconnecting or\n starting another message action.\n </p>{/if}\n <CapabilityGate\n identity={effectiveIdentity}\n required=\"messaging\"\n focusTarget=\"protected\"\n onconnect={identity.mounted\n ? () => connectIdentityView(identityContext)\n : undefined}\n onprobe={identity.mounted\n ? () => probeIdentityViewMessaging(identityContext, 'reviewed_self_copy')\n : undefined}\n ondisconnect={() => disconnectIdentityView(identityContext)}\n />\n {#if panel.state === 'locked' || panel.state === 'unlocking'}\n <h2>Unlock your messages</h2>\n <p>\n Your extension will be asked to decrypt your messages. Each explicit batch\n checks up to 20 encrypted envelopes and may require two decryption\n approvals for each envelope. Further batches need another explicit action.\n </p>\n <Button\n label=\"Unlock messages\"\n disabled={!owned || panel.busy}\n onclick={() => {\n if (owned) void unlockInboxView(owned, 'reviewed_messages_unlock');\n }}\n />\n {/if}\n {#if panel.state === 'partial' || panel.state === 'ready' || panel.state === 'empty' || panel.state === 'unlocking'}\n <p role=\"status\" aria-live=\"polite\">\n {panel.state === 'unlocking'\n ? 'Waiting for your explicit extension approvals.'\n : panel.state === 'empty'\n ? 'No messages found in the checked inbox history.'\n : panel.state === 'partial'\n ? 'Your unlocked local messages are available with limitations.'\n : 'Messages are unlocked. Check here for replies.'}\n </p>\n {#if panel.reason}<p class=\"notice\">\n {reasons[panel.reason] ??\n 'The check is partial. Existing encrypted copies are preserved; review the limitation before continuing.'}\n </p>{/if}\n <Button\n label=\"Check for messages\"\n disabled={!owned || panel.busy}\n onclick={() => {\n if (owned) void checkInboxView(owned, 'reviewed_foreground_inbox');\n }}\n />\n {#if checked}<p>\n Last checked at {checked}. This was a bounded foreground check, not\n complete inbox history.\n </p>{/if}\n {#if panel.queued > 0}\n <p>\n {panel.queued} encrypted envelopes await an explicit decryption batch. Your\n extension will be asked to decrypt them; up to 20 envelopes are attempted\n per batch.\n </p>\n <Button\n label={'Read new messages (' + panel.queued + ')'}\n disabled={!owned || panel.busy}\n onclick={() => {\n if (owned) void readNewInboxView(owned, 'reviewed_decrypt_batch');\n }}\n />\n {/if}\n {#if showLists && owned && list.status === 'ready'}\n {#if list.requests.length > 0}<section\n class=\"stack\"\n aria-label=\"Message requests\"\n >\n <h2>Message requests</h2>\n {#each list.requests as row (row.peer)}<ConversationRow\n controller={owned}\n {row}\n onopen={openConversation}\n />{/each}\n </section>{/if}\n {#if list.conversations.length > 0}<section\n class=\"stack\"\n aria-label=\"Conversations\"\n >\n <h2>Conversations</h2>\n {#each list.conversations as row (row.peer)}<ConversationRow\n controller={owned}\n {row}\n onopen={openConversation}\n />{/each}\n </section>{/if}\n <p class=\"text-small\">\n New means locally unread in this browser. No remote read receipt or\n background message awareness is implied.\n </p>\n {/if}\n <Button\n label=\"Load older messages\"\n disabled={!owned || panel.busy || !olderAvailable}\n onclick={() => {\n if (owned) void loadOlderInboxView(owned, 'reviewed_load_older');\n }}\n />\n <Button\n label=\"Lock messages\"\n disabled={!owned}\n onclick={() => {\n if (owned) stopInboxView(owned);\n }}\n />\n {/if}\n {#key setup}<InboxSetup controller={setup} />{/key}\n <p>\n Check here for replies. This prototype does not send push or email\n notifications.\n </p>\n</div>\n", 331 sha256: 332 '29f17df1ccece671ea2ba57578dc028fa541ce924e1cdc4b3e7753da500da53f' 333 } 334 }, 335 ...historicalPublicProducerClosure, 336 ...historicalWithdrawalProducerClosure, 337 'src/routes/selling/+page.svelte': { 338 source: 339 '<script lang="ts">\n import AccountGate from \'../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', 340 sha256: 341 '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a' 342 } 343 })) { 344 assert.equal( 345 createHash('sha256').update(value.source).digest('hex'), 346 value.sha256 347 ); 348 await writeFile(path.join(web, name), value.source); 349 } 350 } 351 // Frozen public-only HCP055 producers, source6023db01169aa82cb6fe68ca94e1a73750247e72. 352 // Compatibility evidence only; runtime tests never require ancestor Git history. 353 /** @type {Record<string, {source:string, sha256:string}>} */ 354 const historicalPublicOnly = { 355 'src/routes/+layout.svelte': { 356 source: 357 "<script lang=\"ts\">\n import '../theme.css';\n import '../app.css';\n import { onMount, setContext, type Snippet } from 'svelte';\n import {\n createPublicRuntimeContext,\n mountPublicRuntime,\n closePublicRuntime,\n PUBLIC_RUNTIME_CONTEXT\n } from '../lib/runtime/public-runtime.ts';\n import { page } from '$app/state';\n import AppShell from '../lib/components/AppShell.svelte';\n\n const publicContext = createPublicRuntimeContext();\n setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);\n onMount(() => {\n mountPublicRuntime(publicContext);\n return () => closePublicRuntime(publicContext);\n });\n\n let { children }: { children: Snippet } = $props();\n</script>\n\n<AppShell\n currentPath={page.url.pathname}\n availableRoutes={[\n '/search',\n '/sell',\n '/selling',\n '/messages',\n '/about',\n '/privacy'\n ]}\n>\n {@render children()}\n</AppShell>\n", 358 sha256: '956da247f23ad9695c3c6f8bff42801aceaa5b84a2606a1a8a5263fd0c637dc7' 359 }, 360 'src/lib/components/AppShell.svelte': { 361 source: 362 "<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import { internalHref } from '../navigation-url';\n import Button from './primitives/Button.svelte';\n import Disclosure from './primitives/Disclosure.svelte';\n\n type ShellRoute =\n '/search' | '/sell' | '/selling' | '/messages' | '/about' | '/privacy';\n type Identity =\n | { kind: 'guest'; onconnect?: () => void }\n | { kind: 'connected'; publicKey: string; ondisconnect?: () => void };\n let {\n children,\n currentPath = '/',\n availableRoutes = [],\n identity = { kind: 'guest' }\n }: {\n children: Snippet;\n currentPath?: string;\n availableRoutes?: readonly ShellRoute[];\n identity?: Identity;\n } = $props();\n\n const unavailable = $derived(\n !availableRoutes.includes('/search') ||\n !availableRoutes.includes('/about') ||\n !availableRoutes.includes('/privacy') ||\n (identity.kind === 'guest'\n ? !availableRoutes.includes('/sell') || !identity.onconnect\n : !availableRoutes.includes('/selling') ||\n !availableRoutes.includes('/messages') ||\n !identity.ondisconnect)\n );\n\n function available(href: string) {\n return (\n href === '/' ||\n availableRoutes.some((route) => route === href.split('#')[0])\n );\n }\n</script>\n\n{#snippet navigation(label: string, href: string, brand = false)}\n {#if available(href) && internalHref(href)}\n <a\n href={internalHref(href)}\n class=\"shell-link\"\n class:brand\n aria-current={currentPath === href ? 'page' : undefined}>{label}</a\n >\n {:else}\n <span\n class=\"shell-link text-muted\"\n aria-disabled=\"true\"\n aria-describedby=\"shell-availability\"\n aria-current={currentPath === href ? 'page' : undefined}>{label}</span\n >\n {/if}\n{/snippet}\n\n<a href={internalHref('#main-content')} class=\"skip-link visually-hidden\"\n >Skip to main content</a\n>\n<header class=\"navbar\">\n <nav aria-label=\"Primary\" class=\"page navbar__inner\">\n <div class=\"cluster\">\n {@render navigation('HarvestCircle', '/', true)}\n {@render navigation('Search', '/search')}\n {#if identity.kind === 'guest'}\n {@render navigation('List food', '/sell')}\n <Button\n label=\"Connect extension\"\n disabled={!identity.onconnect}\n onclick={identity.onconnect}\n />\n {:else}\n {@render navigation('Messages', '/messages')}\n {@render navigation('Selling', '/selling')}\n <Disclosure summary=\"Identity\">\n <p class=\"key\">{identity.publicKey}</p>\n <Button\n label=\"Disconnect\"\n disabled={!identity.ondisconnect}\n onclick={identity.ondisconnect}\n />\n </Disclosure>\n {/if}\n </div>\n {#if unavailable}\n <p id=\"shell-availability\" class=\"text-small text-muted\">\n Unavailable during development: disabled navigation and actions.\n </p>\n {/if}\n </nav>\n</header>\n<main id=\"main-content\" tabindex=\"-1\" class=\"page\">\n {@render children()}\n</main>\n<footer class=\"footer\">\n <nav aria-label=\"Footer\" class=\"page cluster\">\n {@render navigation('About', '/about')}\n {@render navigation('Privacy', '/privacy')}\n {@render navigation('Help / report', '/about#help')}\n </nav>\n</footer>\n", 363 sha256: 'c8afbb1ee62a16ad47558829518b347fe3e2a312e490312ded812a8b538d828f' 364 }, 365 'src/lib/components/AccountGate.svelte': { 366 source: 367 '<script lang="ts">\n import Button from \'./primitives/Button.svelte\';\n</script>\n\n<svelte:head>\n <title>HarvestCircle</title>\n <meta name="robots" content="noindex" />\n</svelte:head>\n<div class="page page--reading stack">\n <h1>Connect or unlock</h1>\n <p>Connect an extension and unlock your account to continue.</p>\n <p class="notice">Account access is unavailable during development.</p>\n <div class="cluster">\n <Button label="Connect extension" disabled />\n <Button label="Unlock" disabled />\n </div>\n</div>\n', 368 sha256: 'd5f90fb4b9af50037ed19dde626552e82df67017a39408bdbdeff1e712c10fbd' 369 }, 370 // Exact predecessor AccountGate route bytes, historical compatibility only. 371 'src/routes/sell/+page.svelte': { 372 source: 373 '<script lang="ts">\n import AccountGate from \'../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', 374 sha256: '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a' 375 }, 376 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte': { 377 source: 378 '<script lang="ts">\n import AccountGate from \'../../../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', 379 sha256: '465852393264789ceae4133e8d79416ebf37d5485b08fb54c61056fa3714dc5d' 380 }, 381 'src/routes/products/[naddr=naddr]/edit/+page.svelte': { 382 source: 383 '<script lang="ts">\n import AccountGate from \'../../../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', 384 sha256: '465852393264789ceae4133e8d79416ebf37d5485b08fb54c61056fa3714dc5d' 385 }, 386 // Historical public-only variants must also restore their original private 387 // shell. The successor route imports owned identity context, which those 388 // historical roots never provided. Current actual-output cases retain it. 389 'src/routes/messages/+page.svelte': { 390 source: 391 '<script lang="ts">\n import AccountGate from \'../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', 392 sha256: '23547dcfa10e85865e31b66c31ea0d043592e3c316c94da2d74bdf2dd419b38a' 393 }, 394 'src/routes/messages/[conversationId=local_id]/+page.svelte': { 395 source: 396 '<script lang="ts">\n import AccountGate from \'../../../lib/components/AccountGate.svelte\';\n</script>\n\n<AccountGate />\n', 397 sha256: '93e21d162901af304f2a142acc7ddce87f7826421735d8a3af4ae281744ab3a0' 398 } 399 }; 400 // Exact accepted HCP105 public product producers, frozen before enquiry. 401 // Restore only this public-only graph; current output retains HCP106 source. 402 const historicalPublicProduct = { 403 'src/routes/products/[naddr=naddr]/+page.svelte': { 404 source: 405 "<script lang=\"ts\">\n import { getContext, onMount } from 'svelte';\n import { page } from '$app/state';\n import {\n PUBLIC_RUNTIME_CONTEXT,\n publicRuntimeReady,\n createPublicView,\n disposePublicView,\n type PublicView,\n type PublicRuntime,\n type PublicRuntimeContext\n } from '../../../lib/runtime/public-runtime.ts';\n import {\n createProductView,\n closeProductView,\n type ProductView,\n type ProductViewSnapshot\n } from '../../../lib/catalog/product-view.ts';\n import { decodeProductReference } from '../../../lib/nostr/references.ts';\n import { readPublicContact } from '../../../lib/contracts/food-availability-v1/contact-read.ts';\n import { copyProductReference } from '../../../lib/navigation-copy.ts';\n import { internalHref, navigationHref } from '../../../lib/navigation-url.ts';\n import ListingFacts from '../../../lib/components/ListingFacts.svelte';\n import PublisherIdentity from '../../../lib/components/PublisherIdentity.svelte';\n import Disclosure from '../../../lib/components/primitives/Disclosure.svelte';\n import Button from '../../../lib/components/primitives/Button.svelte';\n const context = getContext<PublicRuntimeContext>(PUBLIC_RUNTIME_CONTEXT);\n let runtime = $state.raw<PublicRuntime | undefined>(),\n result = $state.raw<ProductViewSnapshot | undefined>(),\n error = $state<string | undefined>(),\n copyNotice = $state<string | undefined>();\n const reference = $derived(decodeProductReference(page.params.naddr));\n const contact = $derived(readPublicContact(result?.food?.content));\n let disposed = false;\n onMount(() => {\n const unavailable = () => {\n if (!disposed) error = 'Food sources are unavailable.';\n };\n try {\n void publicRuntimeReady(context)\n .then((value) => {\n if (!disposed) {\n runtime = value;\n if (!value) unavailable();\n }\n })\n .catch(unavailable);\n } catch {\n unavailable();\n }\n return () => {\n disposed = true;\n };\n });\n $effect(() => {\n const selected = reference,\n shared = runtime;\n result = undefined;\n copyNotice = undefined;\n if (!selected || !shared) return;\n let active = true,\n acquired: PublicView | undefined,\n owner: ProductView | undefined;\n try {\n acquired = createPublicView(shared);\n owner = createProductView(\n acquired,\n selected.naddr,\n { nowSeconds: () => Math.floor(Date.now() / 1000) },\n (value) => {\n if (active && !disposed) result = value;\n }\n );\n error = undefined;\n } catch {\n error = 'Food sources are unavailable.';\n if (acquired)\n try {\n disposePublicView(acquired);\n } catch {\n /* Shared runtime keeps a failed disposer retryable. */\n }\n }\n return () => {\n active = false;\n if (owner) closeProductView(owner);\n };\n });\n async function copyLink() {\n const selected = reference;\n if (!selected) return;\n const copied = await copyProductReference(selected.naddr, page.url.origin);\n if (!disposed && reference?.naddr === selected.naddr)\n copyNotice = copied\n ? 'Link copied.'\n : 'Copy was unavailable. Select the public link below.';\n }\n</script>\n\n<svelte:head\n ><title>{result?.food?.title ?? 'Food'} — HarvestCircle</title></svelte:head\n>\n<div class=\"page page--reading stack\">\n <a href={internalHref('/search')}>Search food</a>\n <h1>{result?.food?.title ?? 'Food'}</h1>\n {#if !reference}<p class=\"notice\">This food reference is invalid.</p>\n {:else if error || result?.outcome === 'unavailable'}<p class=\"notice\">\n Food sources are unavailable.\n </p>\n {:else if !result || result.outcome === 'checking'}<p>\n Checking food sources…\n </p>\n {:else if result.outcome === 'unobserved'}<p class=\"notice\">\n This listing was not observed in the sources checked. It may be\n unavailable or missing from these sources.\n </p>\n {:else if result.outcome === 'withdrawn'}<p class=\"notice\">\n This listing was withdrawn by its publisher.\n </p>\n {:else if result.outcome === 'unsupported'}<p class=\"notice\">\n The latest known listing uses an unsupported food format.\n </p>\n {:else if result.outcome === 'future_quarantined' || result.outcome === 'clock_unavailable'}<p\n class=\"notice\"\n >\n Listing time could not be confirmed. Food details are unavailable.\n </p>{/if}\n {#if result}\n <PublisherIdentity publisher={result.publisher} />\n {#if result.lastKnown}<p class=\"notice\">\n This is last-known information. The listing status check is incomplete.\n </p>{/if}\n {#if result.food && result.createdAt !== undefined}<ListingFacts\n food={result.food}\n createdAt={result.createdAt}\n />{/if}\n {#if result.outcome === 'sold'}<p class=\"notice\">\n The seller marked this listing sold.\n </p>{/if}\n {#if result.outcome === 'active'}<p>\n Confirm availability with the seller.\n </p>\n <Button label=\"Message seller\" disabled={true} />\n <p class=\"notice\">\n In-app messaging is unavailable during development.\n </p>{/if}\n <Disclosure summary=\"Listing and source details\">\n {#if result.eventId}<p>\n Listing version: <code>{result.eventId}</code>\n </p>{/if}\n {#each result.sources as source (source.result.context)}<p>\n {source.kind}: {source.state}. Coverage: {source.result.coverage}.\n </p>\n {#each source.result.sources as relay (relay.source)}<p>\n {relay.source}: {relay.state}.\n </p>{/each}{/each}\n <p>\n These bounded checks do not prove complete coverage or current stock.\n </p>\n </Disclosure>\n {#if contact && result.outcome === 'active'}<Disclosure\n summary=\"Other contact details\"\n ><a href={navigationHref(contact.href)}>{contact.href}</a></Disclosure\n >{/if}\n {/if}\n {#if reference}<Button label=\"Copy link\" onclick={copyLink} /><a\n href={internalHref(`/products/${reference.naddr}`)}>Public food link</a\n >{/if}\n {#if copyNotice}<p role=\"status\">{copyNotice}</p>{/if}\n</div>\n", 406 sha256: '1869d4dc32ea794d5ee5c1d6cc6b4aac94483482d18cff0562c0cb10087b5278' 407 }, 408 'src/lib/catalog/product-view.ts': { 409 source: 410 "import { PUBLIC_QUERY_BUDGETS } from '../config/budgets.ts';\nimport {\n decodeProductReference,\n type ProductReference\n} from '../nostr/references.ts';\nimport {\n beginPublicViewRun,\n disposePublicView,\n publicViewProjectionAvailable,\n publicViewRunCurrent,\n publicViewOwnsRun,\n subscribePublicView,\n type PublicView\n} from '../runtime/public-runtime.ts';\nimport {\n publicRequestScopeSnapshot,\n publicRunSnapshot,\n closePublicRequest,\n disposePublicRun,\n type PublicRequest\n} from '../nostr/request-scope.ts';\nimport {\n createPublicHeadCandidate,\n publicHeadSnapshot,\n selectPublicHead,\n type PublicHead\n} from './heads.ts';\nimport {\n createPublicViewHeadResolver,\n headResolutionSnapshot,\n resolveHeads,\n closeHeadResolver\n} from './resolve-head.ts';\nimport {\n createPublisherViews,\n readPublisherPage,\n publisherSnapshot,\n type PublisherView\n} from './publishers.ts';\nimport type { FoodProjection } from '../contracts/food-availability-v1/read.ts';\nimport type { WallClock } from './clock-policy.ts';\nimport type { ForegroundSchedule } from './search-view.ts';\nexport type ProductViewSnapshot = Readonly<{\n reference: ProductReference;\n outcome:\n | 'checking'\n | 'unobserved'\n | 'unavailable'\n | 'active'\n | 'sold'\n | 'withdrawn'\n | 'unsupported'\n | 'future_quarantined'\n | 'clock_unavailable';\n food: FoodProjection | undefined;\n eventId: string | undefined;\n createdAt: number | undefined;\n publisher: PublisherView;\n lastKnown: boolean;\n sources: readonly ReturnType<typeof publicRequestScopeSnapshot>[];\n}>;\ndeclare const productBrand: unique symbol;\nexport type ProductView = Readonly<{ readonly [productBrand]: true }>;\ninterface Owner {\n snapshot: () => ProductViewSnapshot;\n close: () => void;\n}\nconst owners = new WeakMap<ProductView, Owner>();\nfunction ownerOf(token: ProductView): Owner {\n const owner = owners.get(token);\n if (!owner) throw Error('product_view_invalid');\n return owner;\n}\nfunction foreground(callback: () => void, delay: number): () => void {\n const timer = setTimeout(() => {\n callback();\n }, delay);\n return () => {\n clearTimeout(timer);\n };\n}\n// One explicit route read, one coordinate, shared run/request budgets. No forged\n// seed, independent cache, relay hints, automatic refresh or additional deadline.\nexport function createProductView(\n view: PublicView,\n value: unknown,\n clock: WallClock,\n onUpdate: (value: ProductViewSnapshot) => void,\n schedule: ForegroundSchedule = foreground\n): ProductView {\n const decoded = decodeProductReference(value);\n if (!decoded) throw Error('product_reference_invalid');\n const reference = decoded;\n const run = beginPublicViewRun(view),\n resolver = createPublicViewHeadResolver(view, run, clock),\n publishers = createPublisherViews(view, clock);\n let closed = false,\n failed = false,\n head: PublicHead | undefined,\n cancel: (() => void) | undefined;\n const requests = new Map<PublicRequest, true>();\n const current = () => !closed && publicViewRunCurrent(view, run);\n function snapshot(): ProductViewSnapshot {\n const available =\n !closed &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n const row = available ? headResolutionSnapshot(resolver)[0] : undefined;\n let scopes = Array.from(requests.keys(), publicRequestScopeSnapshot);\n for (const scope of [row?.headSources, row?.deletionSources])\n if (\n scope &&\n !scopes.some((s) => s.result.context === scope.result.context)\n )\n scopes = scopes.concat(scope);\n const complete =\n !failed &&\n scopes.length > 0 &&\n scopes.every(\n (s) => s.state === 'eose' && s.result.coverage === 'bounded-eose'\n );\n let outcome: ProductViewSnapshot['outcome'];\n if (!available) outcome = 'unavailable';\n else if (row?.deletion.outcome === 'suppressed') outcome = 'withdrawn';\n else if (\n row?.state.display === 'future_quarantined' ||\n row?.state.display === 'clock_unavailable'\n )\n outcome = row.state.display;\n else if (row?.state.display === 'unsupported') outcome = 'unsupported';\n else if (row?.state.food) outcome = row.state.food.status;\n else if (\n !row &&\n (failed ||\n (scopes.length > 0 &&\n scopes.every(\n (scope) =>\n scope.result.sources.length > 0 &&\n scope.result.sources.every(\n (source) =>\n source.state === 'error' || source.state === 'closed'\n )\n )))\n )\n outcome = 'unavailable';\n else\n outcome =\n current() && scopes.some((s) => s.state === 'active')\n ? 'checking'\n : 'unobserved';\n const publisher = publisherSnapshot(publishers, reference.pubkey);\n const stillAvailable =\n !closed &&\n publicViewProjectionAvailable(view) &&\n publicViewOwnsRun(view, run);\n return {\n reference: { ...reference },\n outcome: stillAvailable ? outcome : 'unavailable',\n food: stillAvailable ? row?.state.food : undefined,\n eventId: stillAvailable ? row?.state.head.id : undefined,\n createdAt: stillAvailable ? row?.state.head.created_at : undefined,\n publisher: stillAvailable\n ? publisher\n : {\n pubkey: reference.pubkey,\n label: reference.pubkey,\n assertedName: false\n },\n lastKnown: !stillAvailable || !complete || (row?.lastKnown ?? true),\n sources: scopes\n };\n }\n function publish() {\n const value = snapshot();\n if (!closed && publicViewOwnsRun(view, run)) onUpdate(value);\n }\n function queue() {\n if (!current() || publicRunSnapshot(run).activeRequests === 0) return;\n const next = schedule(() => {\n if (closed || !publicViewOwnsRun(view, run)) return;\n cancel = undefined;\n publish();\n queue();\n }, 250);\n if (current()) cancel = next;\n else next();\n }\n const token = Object.freeze({}) as ProductView;\n owners.set(token, {\n snapshot,\n close() {\n closed = true;\n const previous = cancel;\n cancel = undefined;\n previous?.();\n let error = false;\n try {\n closeHeadResolver(resolver);\n } catch {\n error = true;\n }\n try {\n if (publicViewOwnsRun(view, run)) disposePublicView(view);\n else disposePublicRun(run);\n } catch {\n error = true;\n }\n if (error) throw Error('product_view_close_failed');\n }\n });\n try {\n const filter =\n reference.identifier === ''\n ? {\n kinds: [30402],\n authors: [reference.pubkey],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n }\n : {\n kinds: [30402],\n authors: [reference.pubkey],\n '#d': [reference.identifier],\n limit: PUBLIC_QUERY_BUDGETS.requestedPerRelay\n };\n const request = subscribePublicView(\n view,\n run,\n 'head',\n [filter],\n (proof) => {\n if (!current()) return;\n const candidate = createPublicHeadCandidate(proof);\n if (!candidate) return;\n const next = publicHeadSnapshot(candidate);\n if (\n next.kind !== 30402 ||\n next.pubkey !== reference.pubkey ||\n next.identifier !== reference.identifier\n )\n return;\n head = selectPublicHead(head, candidate).head;\n try {\n resolveHeads(resolver, [head]);\n if (current())\n for (const request of readPublisherPage(publishers, run, [\n reference.pubkey\n ]))\n requests.set(request, true);\n } catch {\n failed = true;\n }\n }\n );\n requests.set(request, true);\n if (publicRequestScopeSnapshot(request).result.sources.length === 0) {\n failed = true;\n closePublicRequest(request);\n }\n } catch {\n failed = true;\n }\n publish();\n queue();\n return token;\n}\nexport function productViewSnapshot(token: ProductView): ProductViewSnapshot {\n return ownerOf(token).snapshot();\n}\nexport function closeProductView(token: ProductView): void {\n ownerOf(token).close();\n}\n", 411 sha256: 'e3739170e3c700246a80c1358c7b96541a5cbf1e4c26905e6ca60537adfce9cf' 412 } 413 }; 414 const base = await mkdtemp(path.join(os.tmpdir(), 'hc actual output ')); 415 let setupReady = false; 416 /** @param {import('node:test').TestContext} t */ 417 function active(t) { 418 if (t.signal.aborted) throw new Error('Output fixture test aborted'); 419 } 420 /** @param {import('node:test').TestContext} t */ 421 function ready(t) { 422 active(t); 423 assert.ok(setupReady, 'Actual output setup must complete before consumers'); 424 } 425 try { 426 /** @param {string} root @param {string[]} args */ 427 const git = (root, ...args) => 428 execFileSync('git', ['-C', root, ...args], { 429 env: Object.fromEntries( 430 Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')) 431 ), 432 encoding: 'utf8' 433 }); 434 /** @param {import('node:test').TestContext} t */ 435 async function fixture(t) { 436 ready(t); 437 const root = await realpath( 438 await mkdtemp(path.join(os.tmpdir(), 'hc output mutation ')) 439 ); 440 t.after(() => rm(root, { recursive: true, force: true })); 441 // Audit consumers use actual client/prerendered/build bytes and all source 442 // inputs. Server output and generated development/type caches are not audit 443 // inputs; avoid copying them for every mutation under the fixed deadline. 444 const excluded = new Set([ 445 path.join(base, 'web/node_modules'), 446 path.join(base, 'web/.svelte-kit/output/server'), 447 path.join(base, 'web/.svelte-kit/generated'), 448 path.join(base, 'web/.svelte-kit/types') 449 ]); 450 await cp(base, root, { 451 recursive: true, 452 filter: (name) => !excluded.has(name) 453 }); 454 active(t); 455 const web = path.join(root, 'web'); 456 return { root, web, audit: () => auditOutput(web) }; 457 } 458 /** @param {{root: string, web: string}} f */ 459 async function refresh(f) { 460 git(f.root, 'add', '--', 'web/src'); 461 await generateBuildInfo(f.web); 462 const bytes = await readFile(path.join(f.web, 'static/build-info.json')); 463 for (const name of [ 464 'build/build-info.json', 465 '.svelte-kit/output/client/build-info.json' 466 ]) 467 await writeFile(path.join(f.web, name), bytes); 468 } 469 470 const sdkKey = 471 'node_modules/.pnpm/applesauce-relay@6.2.1_typescript@6.0.3/node_modules/applesauce-relay/dist/negentropy.js'; 472 /** @param {import('node:test').TestContext} t @param {string} from @param {string} web */ 473 async function copyDependencies(t, from, web) { 474 active(t); 475 const start = performance.now(); 476 await cp( 477 path.join(from, 'web/node_modules'), 478 path.join(web, 'node_modules'), 479 { 480 recursive: true, 481 verbatimSymlinks: true 482 } 483 ); 484 active(t); 485 t.diagnostic( 486 `actual dependency copy milliseconds: ${performance.now() - start}` 487 ); 488 } 489 /** @param {import('node:test').TestContext} t @param {string} web */ 490 function compile(t, web) { 491 active(t); 492 const start = performance.now(); 493 try { 494 execFileSync( 495 process.execPath, 496 [path.join(source, 'web/node_modules/vite/bin/vite.js'), 'build'], 497 { cwd: web, stdio: 'pipe', timeout: 86400000 } 498 ); 499 active(t); 500 } finally { 501 t.diagnostic( 502 `actual Vite compilation milliseconds: ${performance.now() - start}` 503 ); 504 } 505 } 506 await test( 507 'actual output fixture setup', 508 { timeout: 86400000 }, 509 async (t) => { 510 // Compile actual current source once in isolation. No install/native subprocess. 511 for (const name of git( 512 source, 513 'ls-files', 514 '--cached', 515 '--others', 516 '--exclude-standard', 517 '-z', 518 '--', 519 'web', 520 '.gitignore', 521 'core/Cargo.lock', 522 'radroots.lib.source-lock.v1.toml' 523 ) 524 .split('\0') 525 .filter(Boolean)) { 526 const stat = await lstat(path.join(source, name)); 527 assert.ok( 528 stat.isFile() && stat.nlink === 1 && stat.size <= 8 * 1024 * 1024, 529 'Only safe actual source fixture inputs' 530 ); 531 await mkdir(path.dirname(path.join(base, name)), { recursive: true }); 532 await writeFile( 533 path.join(base, name), 534 await readFile(path.join(source, name)) 535 ); 536 } 537 git(base, 'init', '-q'); 538 git(base, 'add', '.'); 539 git( 540 base, 541 '-c', 542 'user.name=Output Test', 543 '-c', 544 'user.email=output@example.invalid', 545 'commit', 546 '-qm', 547 'actual inputs' 548 ); 549 await copyDependencies(t, source, path.join(base, 'web')); 550 await generateBuildInfo(path.join(base, 'web')); 551 compile(t, path.join(base, 'web')); 552 setupReady = true; 553 } 554 ); 555 await test( 556 'HCP115 exact shared-editor predecessor remains independently compilable', 557 { timeout: 86400000 }, 558 async (t) => { 559 const f = await fixture(t); 560 await restoreHistoricalPublicProducers(f.web); 561 const historical = { 562 'src/routes/sell/+page.svelte': { 563 source: 564 "<script lang=\"ts\">\n import ListingEditor from '../../lib/components/ListingEditor.svelte';\n</script>\n\n<ListingEditor route={{ mode: 'new' }} />\n", 565 sha256: 566 '3e99a6121e9ea317d30e631d9edfb05e6596301678f9ae0538e446f0438ae3f4' 567 }, 568 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte': { 569 source: 570 "<script lang=\"ts\">\n import { page } from '$app/state';\n import ListingEditor from '../../../../lib/components/ListingEditor.svelte';\n import type { ListingEditorRoute } from '../../../../lib/publishing/listing-editor.ts';\n const route = $derived({\n mode: 'draft',\n draftId: page.params.draftId ?? ''\n } satisfies ListingEditorRoute);\n</script>\n\n<ListingEditor {route} />\n", 571 sha256: 572 '98935ebb01f950aee5da850758801c28303b042ba219759c4fb04c4974376a76' 573 }, 574 'src/routes/products/[naddr=naddr]/edit/+page.svelte': { 575 source: 576 "<script lang=\"ts\">\n import { page } from '$app/state';\n import ListingEditor from '../../../../lib/components/ListingEditor.svelte';\n import type { ListingEditorRoute } from '../../../../lib/publishing/listing-editor.ts';\n const route = $derived({\n mode: 'edit',\n naddr: page.params.naddr ?? ''\n } satisfies ListingEditorRoute);\n</script>\n\n<ListingEditor {route} />\n", 577 sha256: 578 '5c50dc2ba4c5734ffe4bd1c2e406e6699581b374fab3849d5c5a0072d9bad1e6' 579 }, 580 'src/lib/components/ListingEditor.svelte': { 581 source: 582 '<script lang="ts">\n import { getContext, onMount } from \'svelte\';\n import CapabilityGate from \'./CapabilityGate.svelte\';\n import Notice from \'./Notice.svelte\';\n import { foodUnits } from \'../contracts/food-availability-v1/values.ts\';\n import type { PublicDraftForm } from \'../contracts/local-records.ts\';\n import {\n IDENTITY_VIEW_CONTEXT,\n identityViewSnapshot,\n subscribeIdentityView,\n connectIdentityView,\n disconnectIdentityView,\n type IdentityViewContext\n } from \'../runtime/view-context.ts\';\n import {\n openListingEditor,\n listingEditorSnapshot,\n editListingEditor,\n closeListingEditor,\n subscribeListingEditor,\n type ListingEditor as Editor,\n type ListingEditorRoute,\n type ListingEditorSnapshot\n } from \'../publishing/listing-editor.ts\';\n import { internalHref } from \'../navigation-url.ts\';\n let { route }: { route: ListingEditorRoute } = $props();\n const context = getContext<IdentityViewContext>(IDENTITY_VIEW_CONTEXT);\n let identity = $state(identityViewSnapshot(context)),\n mounted = $state(false),\n editor = $state.raw<Editor | undefined>(),\n snapshot = $state<ListingEditorSnapshot>(),\n unavailable = $state(false);\n type Form = {\n -readonly [Key in keyof PublicDraftForm]: PublicDraftForm[Key];\n };\n const blankForm = (): Form => ({\n title: \'\',\n description: \'\',\n location: \'\',\n amount: \'\',\n currency: \'\',\n unit: \'\',\n quantity: \'\',\n contactType: \'\',\n contactValue: \'\'\n });\n let form = $state<Form>(blankForm());\n const admittedAuthor = $derived(\n identity.identity.state !== \'guest\' && identity.identity.state !== \'pending\'\n ? identity.identity.publicKey\n : undefined\n );\n const active = $derived(mounted && identity.mounted);\n const visible = $derived(\n snapshot &&\n editor &&\n identity.mounted &&\n identity.identity.state !== \'guest\' &&\n identity.identity.state !== \'pending\' &&\n identity.identity.publicKey === snapshot.owner &&\n listingEditorSnapshot(editor)\n );\n onMount(() => {\n mounted = true;\n const off = subscribeIdentityView(context, (next) => {\n identity = next;\n });\n return () => {\n mounted = false;\n off();\n };\n });\n $effect(() => {\n const resource = route,\n author = admittedAuthor;\n if (!active || !author) {\n editor = undefined;\n snapshot = undefined;\n form = blankForm();\n unavailable = false;\n return;\n }\n const cancellation = new AbortController();\n let alive = true,\n owned: Editor | undefined,\n off = () => {};\n editor = undefined;\n snapshot = undefined;\n form = blankForm();\n unavailable = false;\n void openListingEditor(context, resource, cancellation.signal).then(\n (result) => {\n if (!alive) {\n if (result.status === \'ready\') closeListingEditor(result.editor);\n return;\n }\n if (result.status !== \'ready\') {\n unavailable = true;\n return;\n }\n owned = result.editor;\n editor = owned;\n const next = listingEditorSnapshot(owned);\n if (!next) {\n unavailable = true;\n return;\n }\n snapshot = next;\n form = { ...next.form };\n off = subscribeListingEditor(owned, () => {\n snapshot = owned && listingEditorSnapshot(owned);\n if (!snapshot) {\n unavailable = true;\n form = blankForm();\n }\n });\n }\n );\n return () => {\n alive = false;\n cancellation.abort();\n off();\n if (owned) closeListingEditor(owned);\n form = blankForm();\n };\n });\n function changed() {\n const original = editor;\n if (!original || !listingEditorSnapshot(original)?.editable) return;\n void editListingEditor(original, { ...form });\n }\n function connect() {\n return connectIdentityView(context);\n }\n function disconnect() {\n disconnectIdentityView(context);\n }\n const title = $derived(\n route.mode === \'new\'\n ? \'New listing\'\n : route.mode === \'draft\'\n ? \'Continue draft\'\n : \'Edit listing\'\n );\n</script>\n\n<svelte:head\n ><title>{title} \u00b7 HarvestCircle</title><meta\n name="robots"\n content="noindex"\n /></svelte:head\n>\n<div class="page page--reading stack">\n <a\n href={internalHref(\n route.mode === \'edit\' ? `/products/${route.naddr}` : \'/selling\'\n )}>{route.mode === \'edit\' ? \'Back to listing\' : \'Back to Selling\'}</a\n >\n <h1>{title}</h1>\n {#if !visible}\n <CapabilityGate\n identity={identity.identity}\n required="connection"\n focusTarget="protected"\n onconnect={mounted ? connect : undefined}\n ondisconnect={disconnect}\n />\n {#if unavailable}<Notice\n tone="warning"\n text={route.mode === \'draft\'\n ? \'This draft is not available here.\'\n : route.mode === \'edit\'\n ? \'Supported local listing values are not available for editing. Keep this listing read-only.\'\n : \'Browser storage is unavailable. Your existing local data has not been reset.\'}\n />{:else if identity.identity.state !== \'guest\' && identity.identity.state !== \'pending\'}<p\n role="status"\n >\n Loading local values.\n </p>{/if}\n {:else}\n {#if !visible.editable}<Notice\n tone="info"\n text="These retained local values are read-only until the current listing is checked."\n />{:else}<p>\n Changes are saved in this browser. Browser storage is not a backup.\n </p>{/if}\n <form class="stack" onsubmit={(event) => event.preventDefault()} novalidate>\n <div class="field">\n <label class="label" for="listing-title">Product name</label><input\n id="listing-title"\n type="text"\n value={form.title}\n oninput={(event) => {\n form = { ...form, title: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n </div>\n <div class="field">\n <label class="label" for="listing-description">Description</label\n ><textarea\n id="listing-description"\n rows="6"\n value={form.description}\n oninput={(event) => {\n form = { ...form, description: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}></textarea>\n </div>\n <div class="field">\n <label class="label" for="listing-location">Public area</label>\n <p id="listing-location-hint" class="text-small">\n A town or collection area is enough.\n </p>\n <input\n id="listing-location"\n type="text"\n aria-describedby="listing-location-hint"\n value={form.location}\n oninput={(event) => {\n form = { ...form, location: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n </div>\n <div class="cluster">\n <div class="field">\n <label class="label" for="listing-amount">Price</label><input\n id="listing-amount"\n type="text"\n inputmode="decimal"\n value={form.amount}\n oninput={(event) => {\n form = { ...form, amount: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n </div>\n <div class="field">\n <label class="label" for="listing-currency">Currency</label><input\n id="listing-currency"\n type="text"\n maxlength="3"\n value={form.currency}\n oninput={(event) => {\n form = { ...form, currency: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n </div>\n <div class="field">\n <label class="label" for="listing-unit">Per</label><select\n id="listing-unit"\n value={form.unit}\n onchange={(event) => {\n form = { ...form, unit: event.currentTarget.value };\n changed();\n }}\n disabled={!visible.editable}\n ><option value="">Choose a unit</option\n >{#each foodUnits as unit (unit)}<option value={unit}>{unit}</option\n >{/each}</select\n >\n </div>\n </div>\n <div class="field">\n <label class="label" for="listing-quantity"\n >Advertised quantity (optional)</label\n >\n <p id="listing-quantity-unit">\n {form.unit || \'Uses the selected price unit\'}\n </p>\n <input\n id="listing-quantity"\n type="text"\n inputmode="decimal"\n aria-describedby="listing-quantity-unit"\n value={form.quantity}\n oninput={(event) => {\n form = { ...form, quantity: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n </div>\n <details>\n <summary>Add public contact details (optional)</summary>\n <div class="stack">\n <p>Only add contact details you want to include publicly.</p>\n <div class="field">\n <label class="label" for="listing-contact-type"\n >Public contact type</label\n ><select\n id="listing-contact-type"\n value={form.contactType}\n onchange={(event) => {\n const value = event.currentTarget.value;\n if (\n value === \'\' ||\n value === \'email\' ||\n value === \'phone\' ||\n value === \'https\'\n ) {\n form = { ...form, contactType: value };\n changed();\n }\n }}\n disabled={!visible.editable}\n ><option value="">No public contact</option><option value="email"\n >Email</option\n ><option value="phone">Phone</option><option value="https"\n >Website</option\n ></select\n >\n </div>\n <div class="field">\n <label class="label" for="listing-contact-value"\n >Public contact details</label\n ><input\n id="listing-contact-value"\n type="text"\n value={form.contactValue}\n oninput={(event) => {\n form = { ...form, contactValue: event.currentTarget.value };\n changed();\n }}\n readonly={!visible.editable}\n />\n </div>\n </div>\n </details>\n </form>\n {#if visible.editable}<p role="status">\n {visible.state === \'saved\'\n ? \'Saved in this browser.\'\n : visible.state === \'saving\'\n ? \'Saving in this browser.\'\n : visible.state === \'failed\'\n ? \'Not saved. Keep your current input here.\'\n : \'Not yet saved.\'}\n </p>\n {#if visible.failure}<Notice\n tone="warning"\n text="Saving did not complete. Keep your current input. Existing local data has not been reset."\n />{/if}{/if}\n {/if}\n</div>\n', 583 sha256: 584 'fed47cd7257ab3fe1878ef5779b74a4a3e01404d93956806477943190ffb2b18' 585 }, 586 'src/lib/publishing/listing-editor.ts': { 587 source: 588 "import {\n exactLocalFields,\n type PublicDraftForm\n} from '../contracts/local-records.ts';\nimport { canonicalLocalId } from '../private-handles.ts';\nimport { decodeProductReference } from '../nostr/references.ts';\nimport { inspectLocalTemplate } from '../nostr/local-template.ts';\nimport { projectFoodParts } from '../contracts/food-availability-v1/read.ts';\nimport { buildFoodTemplate } from '../contracts/food-availability-v1/write.ts';\nimport {\n openBrowserDatabase,\n closeBrowserDatabase,\n type BrowserDatabase\n} from '../persistence/database.ts';\nimport {\n createPublicPublicationRepository,\n publicPublicationDraftRepository,\n publicPublicationQuotaRepository,\n readPublicListingIntent\n} from '../persistence/public-publications.ts';\nimport {\n inspectPublicStorage,\n publicInventorySnapshot\n} from '../persistence/quota.ts';\nimport { publicRecordSnapshot } from '../persistence/records.ts';\nimport {\n readPublicDraft,\n publicDraftRepositoryOwner,\n type PublicDraftRepository\n} from '../persistence/drafts.ts';\nimport {\n createPublicDraftController,\n publicDraftControllerSnapshot,\n editPublicDraft,\n flushPublicDraft,\n closePublicDraftController,\n type PublicDraftController\n} from './draft-controller.ts';\nimport {\n identityViewSession,\n identityViewMatchesOwner,\n type IdentityViewContext\n} from '../runtime/view-context.ts';\nimport {\n identitySessionSnapshot,\n subscribeIdentityInvalidation\n} from '../runtime/identity-session.ts';\n\ndeclare const editorBrand: unique symbol;\nexport type ListingEditor = Readonly<{ [editorBrand]: true }>;\nexport type ListingEditorRoute =\n | Readonly<{ mode: 'new' }>\n | Readonly<{ mode: 'draft'; draftId: string }>\n | Readonly<{ mode: 'edit'; naddr: string }>;\nexport type ListingEditorSnapshot = Readonly<{\n mode: ListingEditorRoute['mode'];\n owner: string;\n form: PublicDraftForm;\n editable: boolean;\n draftId: string | null;\n state: 'editing' | 'saving' | 'saved' | 'failed' | 'read-only';\n failure: string | null;\n coordinate: string | null;\n sourceEventId: string | null;\n}>;\ntype Editor = Readonly<{\n current(): boolean;\n retire(): void;\n snapshot(): ListingEditorSnapshot | undefined;\n edit(form: unknown): Promise<boolean>;\n flush(): Promise<boolean>;\n subscribe(listener: () => void): () => void;\n}>;\nconst editors = new WeakMap<ListingEditor, Editor>();\nconst active = new WeakMap<\n IdentityViewContext,\n Readonly<{ stamp: symbol; retire(): void }>\n>();\nconst emptyForm: PublicDraftForm = {\n title: '',\n description: '',\n location: '',\n amount: '',\n currency: '',\n unit: '',\n quantity: '',\n contactType: '',\n contactValue: ''\n};\nfunction routeSnapshot(value: unknown): ListingEditorRoute | undefined {\n try {\n if (exactLocalFields(value, ['mode']) && value.mode === 'new')\n return { mode: 'new' };\n if (\n exactLocalFields(value, ['mode', 'draftId']) &&\n value.mode === 'draft'\n ) {\n const draftId = canonicalLocalId(value.draftId);\n return draftId ? { mode: 'draft', draftId } : undefined;\n }\n if (exactLocalFields(value, ['mode', 'naddr']) && value.mode === 'edit') {\n const reference = decodeProductReference(value.naddr);\n return reference ? { mode: 'edit', naddr: reference.naddr } : undefined;\n }\n } catch {\n return;\n }\n}\n// Owner admission precedes database opening and all protected hydration. Edit\n// mode presents validated local values; independent head authorization is later.\nexport async function openListingEditor(\n context: IdentityViewContext,\n input: unknown,\n signal?: AbortSignal\n): Promise<\n | Readonly<{ status: 'ready'; editor: ListingEditor }>\n | Readonly<{\n status: 'unavailable';\n reason: 'owner' | 'resource' | 'storage' | 'source';\n }>\n> {\n const session = identityViewSession(context),\n route = routeSnapshot(input);\n if (!session || signal?.aborted)\n return { status: 'unavailable', reason: 'owner' };\n const identity = identitySessionSnapshot(session),\n owner = 'publicKey' in identity ? identity.publicKey : undefined;\n if (!owner || !identityViewMatchesOwner(context, owner))\n return { status: 'unavailable', reason: 'owner' };\n if (\n !route ||\n (route.mode === 'edit' &&\n decodeProductReference(route.naddr)?.pubkey !== owner)\n )\n return { status: 'unavailable', reason: 'resource' };\n if (typeof window === 'undefined' || !navigator.locks?.request)\n return { status: 'unavailable', reason: 'storage' };\n active.get(context)?.retire();\n const stamp = Symbol(),\n listeners = new Map<symbol, () => void>(),\n cancellation = new AbortController();\n let alive = true,\n unsubscribe = () => {},\n database: BrowserDatabase | undefined,\n repository: PublicDraftRepository | undefined,\n controller: PublicDraftController | undefined;\n function current() {\n return (\n alive &&\n active.get(context)?.stamp === stamp &&\n identityViewSession(context) === session &&\n identityViewMatchesOwner(context, owner) &&\n (!repository || publicDraftRepositoryOwner(repository) === owner)\n );\n }\n let notifying = false;\n function notify() {\n if (notifying) return;\n notifying = true;\n try {\n for (const [key, listener] of Array.from(listeners.entries()))\n if (listeners.get(key) === listener) {\n try {\n listener();\n } catch {\n /*Presentation observers cannot authorize or retain ownership.*/\n }\n }\n } finally {\n notifying = false;\n }\n }\n function retire() {\n if (!alive) return;\n alive = false;\n unsubscribe();\n signal?.removeEventListener('abort', retire);\n cancellation.abort();\n if (controller) closePublicDraftController(controller);\n if (database) closeBrowserDatabase(database);\n if (active.get(context)?.stamp === stamp) active.delete(context);\n notify();\n listeners.clear();\n }\n active.set(context, { stamp, retire });\n unsubscribe = subscribeIdentityInvalidation(session, retire);\n signal?.addEventListener('abort', retire, { once: true });\n if (signal?.aborted) retire();\n function unavailable(reason: 'resource' | 'storage' | 'source') {\n retire();\n return { status: 'unavailable' as const, reason };\n }\n try {\n const opened = await openBrowserDatabase(cancellation.signal);\n if (opened.state !== 'ready') return unavailable('storage');\n if (!current()) {\n closeBrowserDatabase(opened.owner);\n return unavailable('storage');\n }\n database = opened.owner;\n const publications = createPublicPublicationRepository(database, owner);\n repository = publications && publicPublicationDraftRepository(publications);\n if (!publications || !repository || !current())\n return unavailable('storage');\n const drafts = repository;\n let sourceForm: PublicDraftForm | undefined,\n coordinate: string | null = null,\n sourceEventId: string | null = null;\n if (route.mode === 'edit') {\n const reference = decodeProductReference(route.naddr),\n quota = publicPublicationQuotaRepository(publications);\n if (!reference || !quota) return unavailable('source');\n const inspected = await inspectPublicStorage(quota);\n if (!current() || !inspected.ok) return unavailable('source');\n const inventory = publicInventorySnapshot(quota, inspected.value);\n if (!inventory) return unavailable('source');\n let matching:\n Readonly<{ form: PublicDraftForm; eventId: string }> | undefined;\n for (const item of inventory.rows) {\n if (item.family !== 'public_operation') continue;\n const read = await readPublicListingIntent(publications, item.id);\n if (!current()) return unavailable('source');\n const row =\n read.status === 'found' &&\n publicRecordSnapshot(read.record, owner, item.id);\n if (\n !row ||\n row.family !== 'public_operation' ||\n row.capture.kind !== 30402 ||\n !row.artifact ||\n row.source.type !== 'draft'\n )\n continue;\n const template = inspectLocalTemplate(row.capture.wire, owner, 30402);\n if (!template) continue;\n const projected = projectFoodParts(template);\n if (\n projected.outcome !== 'focused' ||\n projected.projection.identifier !== reference.identifier\n )\n continue;\n const source = await readPublicDraft(drafts, row.source.id);\n if (!current()) return unavailable('source');\n if (!source.ok || source.value.revision !== row.source.revision)\n continue;\n const value = source.value.form,\n p = projected.projection;\n if (value.contactType === '' && value.contactValue !== '') continue;\n const built = buildFoodTemplate({\n identifier: p.identifier,\n title: value.title,\n description: value.description,\n location: value.location,\n amount: value.amount,\n currency: value.currency,\n unit: value.unit,\n ...(value.quantity === '' ? {} : { quantity: value.quantity }),\n published_at: p.published_at,\n created_at: template.created_at,\n status: p.status,\n ...(value.contactType === ''\n ? {}\n : {\n contact: {\n type: value.contactType,\n value: value.contactValue,\n public: true as const\n }\n })\n });\n if (\n !built.ok ||\n JSON.stringify({\n pubkey: owner,\n kind: 30402,\n created_at: template.created_at,\n tags: built.wire_parts.tags,\n content: built.wire_parts.content\n }) !== row.capture.wire\n )\n continue;\n if (matching) return unavailable('source');\n matching = { form: value, eventId: row.artifact.eventId };\n }\n if (!matching) return unavailable('source');\n sourceForm = matching.form;\n coordinate = route.naddr;\n sourceEventId = matching.eventId;\n } else {\n const acquired = await createPublicDraftController(\n drafts,\n emptyForm,\n route.mode === 'draft' ? route.draftId : undefined\n );\n if (!current()) {\n if (acquired) closePublicDraftController(acquired);\n return unavailable('resource');\n }\n controller = acquired;\n if (!controller) return unavailable('resource');\n }\n if (!current()) return unavailable('source');\n const value: Editor = {\n current,\n retire,\n snapshot() {\n if (!current()) {\n retire();\n return;\n }\n const local = controller && publicDraftControllerSnapshot(controller);\n return {\n mode: route.mode,\n owner,\n form: local ? local.form : { ...(sourceForm ?? emptyForm) },\n editable: route.mode !== 'edit',\n draftId: local?.draft?.id ?? null,\n state: local\n ? local.state === 'closed'\n ? 'failed'\n : local.state\n : 'read-only',\n failure: local?.failure ?? null,\n coordinate,\n sourceEventId\n };\n },\n async edit(input) {\n if (!current()) {\n retire();\n return false;\n }\n if (!controller || route.mode === 'edit') return false;\n if (!editPublicDraft(controller, input)) return false;\n notify();\n const pending = flushPublicDraft(controller);\n await Promise.resolve();\n if (!current()) {\n retire();\n return false;\n }\n notify();\n const saved = await pending;\n if (!current()) {\n retire();\n return false;\n }\n notify();\n return saved;\n },\n async flush() {\n if (!current()) {\n retire();\n return false;\n }\n if (!controller || route.mode === 'edit') return false;\n const pending = flushPublicDraft(controller);\n await Promise.resolve();\n if (!current()) {\n retire();\n return false;\n }\n notify();\n const saved = await pending;\n if (!current()) {\n retire();\n return false;\n }\n notify();\n return saved;\n },\n subscribe(listener) {\n if (!current()) return () => {};\n const key = Symbol();\n listeners.set(key, listener);\n return () => {\n listeners.delete(key);\n };\n }\n };\n const editor = Object.freeze({}) as ListingEditor;\n editors.set(editor, value);\n return { status: 'ready', editor };\n } catch {\n return unavailable('storage');\n }\n}\nexport function listingEditorSnapshot(\n editor: ListingEditor\n): ListingEditorSnapshot | undefined {\n return editors.get(editor)?.snapshot();\n}\nexport function editListingEditor(\n editor: ListingEditor,\n form: unknown\n): Promise<boolean> {\n return editors.get(editor)?.edit(form) ?? Promise.resolve(false);\n}\nexport function flushListingEditor(editor: ListingEditor): Promise<boolean> {\n return editors.get(editor)?.flush() ?? Promise.resolve(false);\n}\nexport function closeListingEditor(editor: ListingEditor): void {\n editors.get(editor)?.retire();\n}\nexport function subscribeListingEditor(\n editor: ListingEditor,\n listener: () => void\n): () => void {\n return editors.get(editor)?.subscribe(listener) ?? (() => {});\n}\n", 589 sha256: 590 'f2f1be3c614c861f50293f33f5bf1d3ae1851f4b4452fb9e2f3a7b8963a1d1f9' 591 } 592 }; 593 for (const [name, value] of Object.entries(historical)) { 594 assert.equal( 595 createHash('sha256').update(value.source).digest('hex'), 596 value.sha256 597 ); 598 await writeFile(path.join(f.web, name), value.source); 599 } 600 await copyDependencies(t, base, f.web); 601 await refresh(f); 602 compile(t, f.web); 603 const manifest = JSON.parse( 604 await readFile( 605 path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), 606 'utf8' 607 ) 608 ); 609 assert.equal(Object.keys(manifest).length, 43); 610 assert.ok( 611 Object.values(manifest).some((row) => row.name === 'view-context') 612 ); 613 assert.ok((await f.audit()).length > 0); 614 for (const producer of [ 615 'src/lib/persistence/private-storage.ts', 616 'src/lib/persistence/inbox-probes.ts', 617 'src/lib/persistence/inbox-envelope-repository.ts', 618 'src/lib/nostr/inbox-ingress.ts', 619 'src/lib/messaging/inbox-sync.ts', 620 'src/lib/messaging/history-pagination.ts', 621 'src/lib/persistence/inbox-probe-cleanup.ts', 622 'src/lib/messaging/inbox-access-qualification.ts', 623 'src/lib/messaging/inbox-access-controller.ts', 624 'src/lib/messaging/inbox-access-check.ts', 625 'src/lib/persistence/private-records.ts' 626 ]) { 627 for (const change of ['changed', 'missing']) { 628 await t.test( 629 'HCP115 shared probe storage rejects ' + change + ' ' + producer, 630 async () => { 631 const file = path.join(f.web, producer), 632 original = await readFile(file); 633 try { 634 if (change === 'changed') 635 await writeFile( 636 file, 637 Buffer.concat([original, Buffer.from('\n')]) 638 ); 639 else await rm(file); 640 await refresh(f); 641 await assert.rejects( 642 f.audit, 643 // This shared producer is already guarded by exact inbox 644 // presentation identity before probe-storage admission. 645 producer === 'src/lib/messaging/inbox-sync.ts' 646 ? /Invalid owned (?:probe storage|inbox presentation) source|ENOENT/ 647 : /Invalid owned probe storage source|ENOENT/ 648 ); 649 } finally { 650 await writeFile(file, original); 651 await refresh(f); 652 } 653 assert.ok((await f.audit()).length > 0); 654 } 655 ); 656 } 657 } 658 const handles = Object.values(manifest).find( 659 (row) => row.name === 'private-handles' 660 ); 661 assert.ok( 662 handles, 663 'Historical HCP115 keeps its exact private-handles compiler role' 664 ); 665 handles.imports = ['forged-compiler-edge']; 666 await writeFile( 667 path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), 668 JSON.stringify(manifest) 669 ); 670 await assert.rejects(f.audit, /compiler/); 671 } 672 ); 673 await test( 674 'public-only owned lifecycle remains independently compilable', 675 { timeout: 86400000 }, 676 async (t) => { 677 const f = await fixture(t); 678 await restoreHistoricalPublicProducers(f.web); 679 for (const [name, value] of Object.entries(historicalPublicOnly)) { 680 assert.equal( 681 createHash('sha256').update(value.source).digest('hex'), 682 value.sha256 683 ); 684 await writeFile(path.join(f.web, name), value.source); 685 } 686 for (const [name, value] of Object.entries(historicalPublicProduct)) { 687 assert.equal( 688 createHash('sha256').update(value.source).digest('hex'), 689 value.sha256 690 ); 691 await writeFile(path.join(f.web, name), value.source); 692 } 693 await copyDependencies(t, base, f.web); 694 await refresh(f); 695 compile(t, f.web); 696 const manifest = JSON.parse( 697 await readFile( 698 path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), 699 'utf8' 700 ) 701 ); 702 assert.ok( 703 !Object.values(manifest).some( 704 (record) => 705 record.name === 'view-context' || record.name === 'CapabilityGate' 706 ) 707 ); 708 assert.ok( 709 Object.values(manifest).some((record) => record.name === 'budgets') 710 ); 711 assert.equal((await f.audit()).length, 47); 712 const manifestFile = path.join( 713 f.web, 714 '.svelte-kit/output/client/.vite/manifest.json' 715 ); 716 const originalManifest = await readFile(manifestFile); 717 for (const mutation of ['shared-edge', 'button-import']) { 718 await t.test( 719 `public-only listing compatibility rejects extra ${mutation}`, 720 { timeout: 86400000 }, 721 async () => { 722 const changed = JSON.parse(originalManifest.toString()); 723 const records = Object.entries(changed); 724 const additional = records.find( 725 ([, record]) => record.name === 'entry/payload' 726 ); 727 const target = records.find( 728 ([, record]) => 729 record.name === 730 (mutation === 'shared-edge' ? 'Disclosure' : 'Button') 731 ); 732 assert.ok(additional); 733 assert.ok(target); 734 target[1].imports.push(additional[0]); 735 try { 736 await writeFile(manifestFile, JSON.stringify(changed)); 737 await assert.rejects( 738 f.audit(), 739 mutation === 'shared-edge' 740 ? /Invalid owned shared compiler dependencies/ 741 : /Invalid owned public-only Button compiler dependencies/ 742 ); 743 } finally { 744 await writeFile(manifestFile, originalManifest); 745 } 746 } 747 ); 748 } 749 } 750 ); 751 await test( 752 'predecessor SDK graph remains qualified with the historical search form fixture', 753 { timeout: 86400000 }, 754 async (t) => { 755 const f = await fixture(t); 756 await restoreHistoricalPublicProducers(f.web); 757 // This historical graph predates identity activation. Restore its 758 // immutable public-only producers before compiling the former routes. 759 for (const [name, value] of Object.entries(historicalPublicOnly)) 760 await writeFile(path.join(f.web, name), value.source); 761 // Immutable former route bytes are a labelled verification variant only. 762 const historical = 763 "<script lang=\"ts\">\n import { page } from '$app/state';\n import SearchForm from '../../lib/components/SearchForm.svelte';\n import {\n normalizePublicQuery,\n queryErrorMessage,\n readPublicQuery\n } from '../../lib/catalog/query-input';\n import type { PublicQuery } from '../../lib/catalog/query-input';\n import { searchHref } from '../../lib/routes';\n import { internalHref } from '../../lib/navigation-url';\n let query = $state<PublicQuery>(normalizePublicQuery(''));\n let error = $state<string | undefined>();\n $effect(() => {\n query = readPublicQuery(page.url);\n error = undefined;\n });\n function search(input: string) {\n const next = normalizePublicQuery(input);\n if (!next.ok) {\n error = queryErrorMessage(next.error);\n return;\n }\n error = undefined;\n const target = internalHref(searchHref(next.text));\n if (target === undefined) {\n error = queryErrorMessage('invalid_query');\n return;\n }\n globalThis.location.assign(target);\n }\n</script>\n\n<svelte:head><title>Search food \u2014 HarvestCircle</title></svelte:head>\n<div class=\"page page--reading stack\">\n <h1>Search food</h1>\n <SearchForm\n onsubmit={search}\n initialValue={query.ok ? query.text : ''}\n error={error ?? (query.ok ? undefined : queryErrorMessage(query.error))}\n />\n <p class=\"notice\">Search data is unavailable during development.</p>\n</div>\n"; 764 await writeFile( 765 path.join(f.web, 'src/routes/search/+page.svelte'), 766 historical 767 ); 768 await writeFile( 769 path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), 770 historicalProduct 771 ); 772 await refresh(f); 773 await copyDependencies(t, base, f.web); 774 compile(t, f.web); 775 const manifest = JSON.parse( 776 await readFile( 777 path.join(f.web, '.svelte-kit/output/client/.vite/manifest.json'), 778 'utf8' 779 ) 780 ); 781 assert.ok( 782 Object.values(manifest).some((record) => record.name === 'dist') 783 ); 784 assert.ok( 785 !Object.values(manifest).some( 786 (record) => 787 record.name === 'Disclosure' || record.name === 'navigation' 788 ) 789 ); 790 assert.equal((await f.audit()).length, 45); 791 } 792 ); 793 await test( 794 'HCP043 search graph remains qualified with the exact historical product shell', 795 { timeout: 86400000 }, 796 async (t) => { 797 const f = await fixture(t); 798 await restoreHistoricalPublicProducers(f.web); 799 for (const [name, value] of Object.entries(historicalPublicOnly)) 800 await writeFile(path.join(f.web, name), value.source); 801 await writeFile( 802 path.join(f.web, 'src/routes/products/[naddr=naddr]/+page.svelte'), 803 historicalProduct 804 ); 805 await refresh(f); 806 await copyDependencies(t, base, f.web); 807 compile(t, f.web); 808 assert.equal((await f.audit()).length, 46); 809 } 810 ); 811 await test( 812 'actual output qualification', 813 { timeout: 86400000 }, 814 async (t) => { 815 /** @param {string} name @param {(context: import('node:test').TestContext) => Promise<void>} run @param {number} [timeout] */ 816 const check = (name, run, timeout = 86400000) => 817 t.test(name, { timeout }, run); 818 const originalCompilerManifest = JSON.parse( 819 await readFile( 820 path.join( 821 base, 822 'web/.svelte-kit/output/client/.vite/manifest.json' 823 ), 824 'utf8' 825 ) 826 ); 827 const compiledAccountGate = Object.values( 828 originalCompilerManifest 829 ).some((row) => row.name === 'AccountGate'); 830 const gateRole = compiledAccountGate ? 'AccountGate' : 'nodes/4'; 831 const unrelatedRole = compiledAccountGate ? 'AccountGate' : 'nodes/11'; 832 await check( 833 'actual compiled payload passes and build dispatch invokes the guard last', 834 async (t) => { 835 const f = await fixture(t); 836 const files = await f.audit(); 837 // Exact eleven-route module/page/static admission; CSS stays once-imported. 838 assert.equal(files.length, 58); 839 // The actual SDK payload crosses the reader scratch boundary; a reused 840 // scratch buffer must still preserve every compiler/static byte exactly. 841 const sizes = await Promise.all( 842 files 843 .filter((name) => name.endsWith('.js')) 844 .map( 845 async (name) => 846 (await lstat(path.join(f.web, 'build', name))).size 847 ) 848 ); 849 assert.ok(sizes.some((bytes) => bytes > 64 * 1024)); 850 assert.ok(files.includes('search.html')); 851 assert.equal( 852 files.filter((name) => name.endsWith('.css')).length, 853 1 854 ); 855 assert.ok( 856 files.some((name) => 857 /^_app\/immutable\/assets\/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.css$/.test( 858 name 859 ) 860 ) 861 ); 862 assert.ok(files.includes('200.html')); 863 const pkg = JSON.parse( 864 await readFile(path.join(f.web, 'package.json'), 'utf8') 865 ); 866 assert.match( 867 pkg.scripts.build, 868 /vite build && node tools\/check-output\.mjs$/ 869 ); 870 } 871 ); 872 873 for (const sourceName of [ 874 'src/routes/messages/+page.svelte', 875 'src/lib/components/InboxStatus.svelte', 876 'src/lib/messaging/inbox-view.ts', 877 'src/lib/messaging/inbox-sync.ts', 878 'src/lib/messaging/decryption-queue.ts', 879 'src/lib/components/ConversationRow.svelte', 880 'src/lib/messaging/inbox-list.ts', 881 'src/lib/components/ConversationThread.svelte', 882 'src/lib/components/MessageItem.svelte', 883 'src/lib/components/ConversationOptions.svelte', 884 'src/lib/messaging/cited-product.ts', 885 'src/lib/nostr/enquiry-references.ts', 886 'src/lib/components/MessageComposer.svelte', 887 'src/lib/messaging/reply-controller.ts', 888 'src/lib/messaging/rumor-plan.ts', 889 'src/lib/messaging/conversation-thread.ts', 890 'src/lib/persistence/private-storage.ts', 891 'src/routes/messages/[conversationId=local_id]/+page.svelte' 892 ]) 893 await check( 894 'linked inbox presentation requires exact owned source ' + 895 sourceName, 896 async (t) => { 897 const f = await fixture(t), 898 file = path.join(f.web, sourceName); 899 await writeFile( 900 file, 901 (await readFile(file, 'utf8')) + 902 '\n// changed presentation source\n' 903 ); 904 // Match the actual altered source identity before probing the 905 // independent exact producer pin. The stale identity guard stays. 906 await refresh(f); 907 await assert.rejects( 908 f.audit, 909 /inbox presentation source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 910 ); 911 } 912 ); 913 for (const mutation of [ 914 'missing-private-cache-directory', 915 'extra-private-edge', 916 'missing-private-edge', 917 'private-dynamic', 918 'publisher-extra-edge' 919 ]) 920 await check( 921 'actual inbox compiler rejects ' + mutation, 922 async (t) => { 923 const f = await fixture(t), 924 file = path.join( 925 f.web, 926 '.svelte-kit/output/client/.vite/manifest.json' 927 ); 928 const manifest = JSON.parse(await readFile(file, 'utf8')); 929 const find = (/** @type {string} */ name) => { 930 const row = Object.entries(manifest).find( 931 ([, v]) => v.name === name 932 ); 933 assert.ok(row); 934 return row; 935 }; 936 const [key, row] = find('InboxStatus'); 937 if (mutation === 'missing-private-cache-directory') 938 delete manifest[key]; 939 if (mutation === 'extra-private-edge') 940 row.imports = row.imports.concat(find('references')[0]); 941 if (mutation === 'missing-private-edge') 942 row.imports = row.imports.slice(1); 943 if (mutation === 'private-dynamic') 944 row.dynamicImports = [find('InboxSetup')[0]]; 945 if (mutation === 'publisher-extra-edge') 946 find('publishers')[1].imports = find( 947 'publishers' 948 )[1].imports.concat(find('references')[0]); 949 await writeFile(file, JSON.stringify(manifest)); 950 await assert.rejects(f.audit, /compiler|references/); 951 } 952 ); 953 954 for (const mutation of [ 955 'directory-missing-context', 956 'directory-entry-role', 957 'directory-duplicate-role', 958 'thread-missing-edge', 959 'thread-dynamic', 960 'thread-entry-role', 961 'reply-missing-navigation', 962 'reply-missing-owner-key', 963 'context-resolver-dynamic', 964 'context-resolver-entry', 965 'enquiry-view-dynamic', 966 'enquiry-view-entry', 967 'enquiry-setup-dynamic', 968 'enquiry-setup-entry', 969 'enquiry-gate-dynamic', 970 'enquiry-gate-entry', 971 'enquiry-root-missing-gate', 972 'enquiry-root-missing-css', 973 'enquiry-root-extra-css' 974 ]) 975 await check( 976 'actual inbox list compiler rejects ' + mutation, 977 async (t) => { 978 const f = await fixture(t), 979 file = path.join( 980 f.web, 981 '.svelte-kit/output/client/.vite/manifest.json' 982 ), 983 manifest = JSON.parse(await readFile(file, 'utf8')); 984 const entry = Object.entries(manifest).find( 985 ([, row]) => 986 row.name === 987 (mutation.startsWith('enquiry-view-') 988 ? 'inbox-view' 989 : mutation.startsWith('enquiry-setup-') 990 ? 'InboxSetup' 991 : mutation.startsWith('enquiry-gate-') 992 ? 'InboxSetup' 993 : mutation.startsWith('enquiry-root-') 994 ? 'nodes/0' 995 : mutation.startsWith('context-') 996 ? 'publishers' 997 : mutation.startsWith('reply-') 998 ? 'MessageComposer' 999 : mutation.startsWith('thread-') 1000 ? 'nodes/5' 1001 : 'InboxStatus') 1002 ); 1003 assert.ok(entry); 1004 const [, row] = entry; 1005 if (mutation === 'enquiry-root-missing-css') row.css = []; 1006 if (mutation === 'enquiry-root-extra-css') 1007 row.css = [...row.css, row.css[0]]; 1008 if ( 1009 mutation.startsWith('enquiry-') && 1010 mutation.endsWith('-dynamic') 1011 ) 1012 row.dynamicImports = []; 1013 if ( 1014 mutation.startsWith('enquiry-') && 1015 mutation.endsWith('-entry') 1016 ) 1017 row.isEntry = true; 1018 if (mutation === 'enquiry-root-missing-gate') 1019 row.imports = row.imports.filter( 1020 (/** @type {string} */ value) => 1021 !['view-context', 'CapabilityGate'].includes( 1022 manifest[value].name 1023 ) 1024 ); 1025 if (mutation === 'context-resolver-dynamic') 1026 row.dynamicImports = []; 1027 if (mutation === 'context-resolver-entry') row.isEntry = true; 1028 if (mutation === 'directory-missing-context') 1029 row.imports = row.imports.filter( 1030 (/** @type {string} */ value) => 1031 manifest[value].name !== 'InboxSetup' 1032 ); 1033 if (mutation === 'directory-entry-role') row.isEntry = true; 1034 if (mutation === 'directory-duplicate-role') 1035 manifest['_forged_directory.js'] = { ...row }; 1036 if (mutation === 'thread-missing-edge') 1037 row.imports = row.imports.slice(1); 1038 if (mutation === 'thread-dynamic') 1039 row.dynamicImports = [ 1040 Object.keys(manifest).find( 1041 (key) => manifest[key].name === 'InboxSetup' 1042 ) 1043 ]; 1044 if (mutation === 'thread-entry-role') row.isEntry = false; 1045 if (mutation === 'reply-missing-navigation') 1046 row.imports = row.imports.filter( 1047 (/** @type {string} */ value) => 1048 manifest[value].name !== 'navigation' 1049 ); 1050 if (mutation === 'reply-missing-owner-key') { 1051 const key = Object.keys(manifest).find( 1052 (key) => manifest[key].name === 'public-runtime' 1053 ); 1054 assert.ok( 1055 key && row.imports.includes(key), 1056 'Mutate an actual current owner-key compiler edge' 1057 ); 1058 row.imports = row.imports.filter( 1059 (/** @type {string} */ value) => 1060 manifest[value].name !== 'public-runtime' 1061 ); 1062 } 1063 await writeFile(file, JSON.stringify(manifest)); 1064 await assert.rejects(f.audit, /compiler|duplicate|inventory/); 1065 } 1066 ); 1067 1068 for (const name of [ 1069 'components/InboxSetup.svelte', 1070 'messaging/inbox-setup-view.ts', 1071 'runtime/view-context.ts' 1072 ]) 1073 await check( 1074 'linked inbox setup requires exact owned source ' + name, 1075 async (t) => { 1076 const f = await fixture(t); 1077 const file = path.join(f.web, 'src/lib', name); 1078 await writeFile( 1079 file, 1080 (await readFile(file, 'utf8')) + '\n// changed source\n' 1081 ); 1082 await refresh(f); 1083 await assert.rejects( 1084 f.audit, 1085 /inbox compiler source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 1086 ); 1087 } 1088 ); 1089 for (const name of [ 1090 'references', 1091 'public-runtime', 1092 gateRole, 1093 'Disclosure' 1094 ]) 1095 await check( 1096 'linked inbox setup rejects changed exact compiler edge ' + name, 1097 async (t) => { 1098 const f = await fixture(t); 1099 const file = path.join( 1100 f.web, 1101 '.svelte-kit/output/client/.vite/manifest.json' 1102 ); 1103 const manifest = JSON.parse(await readFile(file, 'utf8')); 1104 const entry = Object.entries(manifest).find( 1105 ([, row]) => row.name === name 1106 ); 1107 assert.ok(entry, 'Missing actual linked inbox compiler role'); 1108 entry[1].imports = ['forged-compiler-edge']; 1109 await writeFile(file, JSON.stringify(manifest)); 1110 await assert.rejects(f.audit, /compiler/); 1111 } 1112 ); 1113 await check( 1114 'owned root preserves its lifecycle across a 64 KiB read boundary', 1115 async (t) => { 1116 const f = await fixture(t); 1117 const file = path.join(f.web, 'src/routes/+layout.svelte'); 1118 const layout = await readFile(file, 'utf8'); 1119 // A large harmless comment after the real lifecycle must not overwrite its 1120 // first read chunk when the file reader reuses a scratch buffer. 1121 const expanded = layout.replace( 1122 '</script>', 1123 '/*' + 'owned reader boundary '.repeat(4000) + '*/\n</script>' 1124 ); 1125 assert.ok(Buffer.byteLength(expanded) > 64 * 1024); 1126 await writeFile(file, expanded); 1127 await refresh(f); 1128 assert.equal((await f.audit()).length, 58); 1129 } 1130 ); 1131 1132 for (const comment of [ 1133 '/*#__PURE__*/', 1134 '/*@vite-ignore*/', 1135 '/*webpackChunkName: "hidden"*/', 1136 '// ordinary line comment\n' 1137 ]) 1138 await check( 1139 'root rejects trailing annotation or unsupported trivia ' + comment, 1140 async (t) => { 1141 const f = await fixture(t); 1142 const file = path.join(f.web, 'src/routes/+layout.svelte'); 1143 const root = await readFile(file, 'utf8'); 1144 const changed = root.replace( 1145 '</script>', 1146 comment + '\n</script>' 1147 ); 1148 assert.notEqual(changed, root); 1149 await writeFile(file, changed); 1150 await refresh(f); 1151 await assert.rejects( 1152 f.audit, 1153 /Invalid owned root runtime activation/ 1154 ); 1155 } 1156 ); 1157 1158 for (const mutation of [ 1159 'unknown-name', 1160 'missing-references', 1161 'missing-dist', 1162 'missing-negentropy', 1163 'missing-root-edge', 1164 'random-key', 1165 'wrong-src', 1166 'wrong-version', 1167 'wrong-peer', 1168 'wrong-basename', 1169 'wrong-dynamic-flag', 1170 'entry-flag', 1171 'css', 1172 'wrong-import', 1173 'chunk-src', 1174 'chunk-entry' 1175 ]) 1176 await check( 1177 'owned root SDK compiler admission rejects ' + mutation, 1178 async (t) => { 1179 const f = await fixture(t); 1180 const file = path.join( 1181 f.web, 1182 '.svelte-kit/output/client/.vite/manifest.json' 1183 ); 1184 const m = JSON.parse(await readFile(file, 'utf8')); 1185 const root = Object.values(m).find((v) => v.name === 'nodes/0'); 1186 const dist = Object.entries(m).find( 1187 ([, v]) => 1188 v.name === 1189 (Object.values(m).some((row) => row.name === 'public-runtime') 1190 ? 'public-runtime' 1191 : 'Disclosure') 1192 ); 1193 assert.ok( 1194 m[sdkKey] && root && dist, 1195 'Actual successor SDK identities' 1196 ); 1197 if (mutation === 'unknown-name') 1198 m[sdkKey].name = 'unapproved-sdk'; 1199 if ( 1200 mutation.startsWith('missing-') && 1201 mutation !== 'missing-root-edge' 1202 ) { 1203 const entry = Object.entries(m).find( 1204 ([, v]) => 1205 v.name === 1206 (mutation === 'missing-dist' 1207 ? dist[1].name 1208 : mutation.slice(8)) 1209 ); 1210 assert.ok(entry); 1211 delete m[entry[0]]; 1212 } 1213 if (mutation === 'missing-root-edge') dist[1].dynamicImports = []; 1214 if ( 1215 [ 1216 'random-key', 1217 'wrong-version', 1218 'wrong-peer', 1219 'wrong-basename' 1220 ].includes(mutation) 1221 ) { 1222 const next = 1223 mutation === 'random-key' 1224 ? '_HCrandom.js' 1225 : sdkKey.replace( 1226 mutation === 'wrong-version' 1227 ? '6.2.1' 1228 : mutation === 'wrong-peer' 1229 ? '6.0.3' 1230 : 'negentropy.js', 1231 mutation === 'wrong-basename' ? 'other.js' : '0.0.0' 1232 ); 1233 m[next] = m[sdkKey]; 1234 delete m[sdkKey]; 1235 m[next].src = next; 1236 dist[1].dynamicImports = dist[1].dynamicImports.map( 1237 (/** @type {string} */ k) => (k === sdkKey ? next : k) 1238 ); 1239 } 1240 if (mutation === 'wrong-src') m[sdkKey].src = '_HCwrong.js'; 1241 if (mutation === 'wrong-dynamic-flag') 1242 m[sdkKey].isDynamicEntry = false; 1243 if (mutation === 'entry-flag') m[sdkKey].isEntry = false; 1244 if (mutation === 'css') m[sdkKey].css = []; 1245 if (mutation === 'wrong-import') 1246 m[sdkKey].imports = [ 1247 Object.keys(m).find((k) => m[k].name === 'Button') 1248 ]; 1249 if (mutation === 'chunk-src') dist[1].src = dist[0]; 1250 if (mutation === 'chunk-entry') dist[1].isEntry = false; 1251 await writeFile(file, JSON.stringify(m)); 1252 await assert.rejects(f.audit, /compiler|runtime/i); 1253 } 1254 ); 1255 for (const mutation of [ 1256 'copied-files-only', 1257 'comment-only', 1258 'string-only', 1259 'shadowed', 1260 'rebound', 1261 'aliased', 1262 'missing-cleanup', 1263 'missing-context', 1264 'wrong-context' 1265 ]) 1266 await check( 1267 'root runtime activation rejects ' + mutation, 1268 async (t) => { 1269 const f = await fixture(t); 1270 const file = path.join(f.web, 'src/routes/+layout.svelte'); 1271 let layout = await readFile(file, 'utf8'); 1272 if ( 1273 ['copied-files-only', 'comment-only', 'string-only'].includes( 1274 mutation 1275 ) 1276 ) { 1277 const script = layout.slice( 1278 layout.indexOf('>') + 1, 1279 layout.indexOf('</script>') 1280 ); 1281 layout = 1282 '<script lang="ts">' + 1283 (mutation === 'comment-only' 1284 ? '/*' + script + '*/' 1285 : mutation === 'string-only' 1286 ? 'const text = ' + JSON.stringify(script) + ';' 1287 : '') + 1288 '</script><main>Controlled root</main>'; 1289 } 1290 if (mutation === 'shadowed') 1291 layout = layout.replace( 1292 'onMount(() => {', 1293 'onMount((publicContext) => {' 1294 ); 1295 if (mutation === 'rebound') 1296 layout = layout.replace( 1297 'const publicContext', 1298 'let publicContext' 1299 ); 1300 if (mutation === 'aliased') 1301 layout = layout 1302 .replace( 1303 ' mountPublicRuntime,', 1304 ' mountPublicRuntime as otherMount,' 1305 ) 1306 .replace( 1307 'mountPublicRuntime(publicContext)', 1308 'otherMount(publicContext)' 1309 ); 1310 if (mutation === 'missing-cleanup') 1311 layout = layout.includes('closeLocalPublicHides(publicHides)') 1312 ? layout.replace( 1313 ' closePublicRuntime(publicContext);', 1314 '' 1315 ) 1316 : layout.replace( 1317 'return () => closePublicRuntime(publicContext);', 1318 'return () => {};' 1319 ); 1320 if (mutation === 'missing-context') 1321 layout = layout.replace( 1322 'setContext(PUBLIC_RUNTIME_CONTEXT, publicContext);', 1323 '' 1324 ); 1325 if (mutation === 'wrong-context') 1326 layout = layout.replace( 1327 'closePublicRuntime(publicContext)', 1328 'closePublicRuntime({})' 1329 ); 1330 assert.notEqual( 1331 layout, 1332 await readFile(file, 'utf8'), 1333 'Actual hostile root mutation must change the source' 1334 ); 1335 await writeFile(file, layout); 1336 await refresh(f); 1337 await assert.rejects( 1338 f.audit, 1339 /compiler|runtime|Invalid owned listing editor source/i 1340 ); 1341 } 1342 ); 1343 for (const mutation of [ 1344 'missing-mount', 1345 'missing-subscription', 1346 'missing-unsubscribe', 1347 'missing-close', 1348 'wrong-context', 1349 'duplicate-context', 1350 'extra-mount', 1351 'aliased-mount', 1352 'shadowed', 1353 'missing-context', 1354 'rebound-context' 1355 ]) 1356 await check( 1357 'owned identity lifecycle rejects ' + mutation, 1358 async (t) => { 1359 const f = await fixture(t); 1360 const file = path.join(f.web, 'src/routes/+layout.svelte'); 1361 const original = await readFile(file, 'utf8'); 1362 let layout = original; 1363 assert.ok(layout.includes('mountIdentityView(identityContext);')); 1364 if (mutation === 'missing-mount') 1365 layout = layout.replace( 1366 'mountIdentityView(identityContext);', 1367 '' 1368 ); 1369 if (mutation === 'missing-subscription') 1370 layout = layout.replace( 1371 'subscribeIdentityView(identityContext,', 1372 'subscribeIdentityView({},' 1373 ); 1374 if (mutation === 'missing-unsubscribe') 1375 layout = layout.replace(' off();', ''); 1376 if (mutation === 'missing-close') 1377 layout = layout.replace( 1378 'closeIdentityView(identityContext);', 1379 '' 1380 ); 1381 if (mutation === 'wrong-context') 1382 layout = layout.replace( 1383 'closeIdentityView(identityContext)', 1384 'closeIdentityView({})' 1385 ); 1386 if (mutation === 'duplicate-context') 1387 layout = layout.replace( 1388 'const identityContext = createIdentityViewContext();', 1389 'const identityContext = createIdentityViewContext(); const other = createIdentityViewContext();' 1390 ); 1391 if (mutation === 'extra-mount') 1392 layout = layout.replace( 1393 'mountIdentityView(identityContext);', 1394 'mountIdentityView(identityContext); mountIdentityView(identityContext);' 1395 ); 1396 if (mutation === 'aliased-mount') 1397 layout = layout 1398 .replace( 1399 ' mountIdentityView,', 1400 ' mountIdentityView as otherMount,' 1401 ) 1402 .replace( 1403 'mountIdentityView(identityContext);', 1404 'otherMount(identityContext);' 1405 ); 1406 if (mutation === 'shadowed') 1407 layout = layout.replace( 1408 'const off = subscribeIdentityView', 1409 'const identityContext = {}; const off = subscribeIdentityView' 1410 ); 1411 if (mutation === 'missing-context') 1412 layout = layout.replace( 1413 'setContext(IDENTITY_VIEW_CONTEXT, identityContext);', 1414 '' 1415 ); 1416 if (mutation === 'rebound-context') 1417 layout = layout.replace( 1418 'const identityContext =', 1419 'let identityContext =' 1420 ); 1421 assert.notEqual(layout, original); 1422 await writeFile(file, layout); 1423 await refresh(f); 1424 await assert.rejects( 1425 f.audit, 1426 /Invalid owned root runtime activation/ 1427 ); 1428 } 1429 ); 1430 for (const mutation of [ 1431 'missing-view', 1432 'missing-heads', 1433 'extra-view-field', 1434 'wrong-view-imports', 1435 'wrong-heads-imports', 1436 'missing-root-edge', 1437 'missing-gate-edge' 1438 ]) 1439 await check( 1440 'owned identity compiler topology rejects ' + mutation, 1441 async (t) => { 1442 const f = await fixture(t), 1443 file = path.join( 1444 f.web, 1445 '.svelte-kit/output/client/.vite/manifest.json' 1446 ); 1447 const manifest = JSON.parse(await readFile(file, 'utf8')); 1448 /** @param {string} name */ 1449 const find = (name) => { 1450 const entry = Object.entries(manifest).find( 1451 ([, record]) => record.name === name 1452 ); 1453 assert.ok(entry, 'Missing observed compiler role: ' + name); 1454 return entry; 1455 }; 1456 const identityCompilerRole = Object.values(manifest).some( 1457 (record) => record.name === 'identity-session' 1458 ) 1459 ? 'identity-session' 1460 : Object.values(manifest).some( 1461 (record) => record.name === 'public-runtime' 1462 ) 1463 ? 'public-runtime' 1464 : 'heads'; 1465 const [identityKey, identity] = find( 1466 Object.values(manifest).some( 1467 (record) => record.name === 'view-context' 1468 ) 1469 ? 'view-context' 1470 : 'CapabilityGate' 1471 ), 1472 [headsKey, heads] = find(identityCompilerRole); 1473 if (mutation === 'missing-view') delete manifest[identityKey]; 1474 if (mutation === 'missing-heads') delete manifest[headsKey]; 1475 if (mutation === 'extra-view-field') identity.dynamicImports = []; 1476 if (mutation === 'wrong-view-imports') identity.imports = []; 1477 if (mutation === 'wrong-heads-imports') heads.imports = []; 1478 if ( 1479 mutation === 'missing-root-edge' || 1480 mutation === 'missing-gate-edge' 1481 ) { 1482 const [, consumer] = find( 1483 mutation === 'missing-root-edge' ? 'nodes/0' : gateRole 1484 ); 1485 assert.ok(consumer.imports.includes(identityKey)); 1486 consumer.imports = consumer.imports.filter( 1487 /** @param {string} dependency */ 1488 (dependency) => dependency !== identityKey 1489 ); 1490 } 1491 await writeFile(file, JSON.stringify(manifest)); 1492 await assert.rejects(f.audit, /compiler/i); 1493 } 1494 ); 1495 for (const name of [ 1496 'runtime/public-runtime.ts', 1497 'nostr/request-scope.ts', 1498 'nostr/public-pool.ts', 1499 'nostr/public-store.ts', 1500 'nostr/request-result.ts', 1501 'nostr/ingress.ts', 1502 'nostr/verified-envelope.ts', 1503 'nostr/envelope-bounds.ts', 1504 'nostr/exports.ts', 1505 'catalog/observations.ts', 1506 'config/budgets.ts', 1507 'config/relays.ts', 1508 'config/deployment-relays.ts' 1509 ]) 1510 await check( 1511 'root runtime admission requires owned ' + name, 1512 async (t) => { 1513 const f = await fixture(t); 1514 await rm(path.join(f.web, 'src/lib', name)); 1515 await refresh(f); 1516 await assert.rejects(f.audit); 1517 } 1518 ); 1519 for (const routeSource of [ 1520 'search/+page.svelte', 1521 'messages/+page.svelte' 1522 ]) 1523 await check( 1524 routeSource + 1525 ' admission requires its owned source and exact module/page counterparts', 1526 async (t) => { 1527 const f = await fixture(t); 1528 const source = path.join(f.web, 'src/routes', routeSource); 1529 const original = await readFile(source); 1530 await rm(source); 1531 git(f.root, 'add', '--', 'web/src/routes/' + routeSource); 1532 await generateBuildInfo(f.web); 1533 const metadata = await readFile( 1534 path.join(f.web, 'static/build-info.json') 1535 ); 1536 await writeFile( 1537 path.join(f.web, 'build/build-info.json'), 1538 metadata 1539 ); 1540 await writeFile( 1541 path.join(f.web, '.svelte-kit/output/client/build-info.json'), 1542 metadata 1543 ); 1544 await assert.rejects(f.audit, /Undeclared compiler module/); 1545 await writeFile(source, original); 1546 } 1547 ); 1548 for (const mutation of [ 1549 'unknown-name', 1550 'duplicate', 1551 'missing-module', 1552 'missing-page', 1553 'changed-page' 1554 ]) { 1555 await check( 1556 'exact search compiler admission rejects ' + mutation, 1557 async (t) => { 1558 const f = await fixture(t); 1559 const file = path.join( 1560 f.web, 1561 '.svelte-kit/output/client/.vite/manifest.json' 1562 ); 1563 const manifest = JSON.parse(await readFile(file, 'utf8')); 1564 const entry = Object.entries(manifest).find( 1565 ([, record]) => record.name === 'routes' 1566 ); 1567 assert.ok(entry, 'The actual shared routes module must exist'); 1568 const [key, module] = entry; 1569 if (mutation === 'unknown-name') 1570 module.name = 'unapproved-routes'; 1571 if (mutation === 'duplicate') manifest.duplicate = { ...module }; 1572 if (mutation === 'missing-module') delete manifest[key]; 1573 if (mutation === 'missing-page') 1574 await rm(path.join(f.web, 'build/search.html')); 1575 if (mutation === 'changed-page') 1576 await writeFile( 1577 path.join(f.web, 'build/search.html'), 1578 '<h1>Different source</h1>' 1579 ); 1580 await writeFile(file, JSON.stringify(manifest)); 1581 await assert.rejects(f.audit); 1582 } 1583 ); 1584 } 1585 for (const mutation of ['missing', 'changed']) { 1586 await check( 1587 'full-route static robots rejects ' + mutation, 1588 async (t) => { 1589 const f = await fixture(t); 1590 const target = path.join(f.web, 'build/robots.txt'); 1591 if (mutation === 'missing') await rm(target); 1592 else await writeFile(target, 'User-agent: *\nAllow: /\n'); 1593 await assert.rejects(f.audit); 1594 } 1595 ); 1596 } 1597 await check( 1598 'full-route compiler rejects an unowned thirteenth node', 1599 async (t) => { 1600 const f = await fixture(t); 1601 const file = path.join( 1602 f.web, 1603 '.svelte-kit/output/client/.vite/manifest.json' 1604 ); 1605 const manifest = JSON.parse(await readFile(file, 'utf8')); 1606 const entry = Object.entries(manifest).find( 1607 ([, record]) => record.name === 'nodes/12' 1608 ); 1609 assert.ok(entry); 1610 entry[1].name = 'nodes/13'; 1611 await writeFile(file, JSON.stringify(manifest)); 1612 await assert.rejects(f.audit, /Undeclared compiler module/); 1613 } 1614 ); 1615 await check( 1616 'actual shared budgets/navigation validator chunk has owned consumers and counterpart', 1617 async (t) => { 1618 const f = await fixture(t); 1619 const manifest = JSON.parse( 1620 await readFile( 1621 path.join( 1622 f.web, 1623 '.svelte-kit/output/client/.vite/manifest.json' 1624 ), 1625 'utf8' 1626 ) 1627 ); 1628 const entries = Object.entries(manifest).filter( 1629 ([, record]) => record.name === 'navigation-url' 1630 ); 1631 assert.equal(entries.length, 1); 1632 const [key, budget] = entries[0]; 1633 assert.deepEqual(Object.keys(budget).sort(), ['file', 'name']); 1634 for (const name of [ 1635 'public-runtime', 1636 'nodes/9', 1637 'routes', 1638 'Button', 1639 'ReportPreview' 1640 ]) { 1641 const consumer = Object.values(manifest).find( 1642 (record) => record.name === name 1643 ); 1644 assert.ok(consumer, 'Missing actual budget consumer ' + name); 1645 assert.ok( 1646 consumer.imports.includes(key), 1647 'Missing actual shared budget edge from ' + name 1648 ); 1649 } 1650 assert.deepEqual( 1651 await readFile(path.join(f.web, 'build', budget.file)), 1652 await readFile( 1653 path.join(f.web, '.svelte-kit/output/client', budget.file) 1654 ) 1655 ); 1656 assert.ok((await f.audit()).includes(budget.file)); 1657 } 1658 ); 1659 for (const name of [ 1660 'ListingEditor', 1661 'public-runtime', 1662 'nodes/8', 1663 'nodes/10', 1664 'nodes/12' 1665 ]) { 1666 for (const mutation of [ 1667 'missing', 1668 'missing-edge', 1669 'extra-edge', 1670 'duplicate-edge', 1671 'permuted-edges', 1672 'dynamic', 1673 'entry', 1674 'css' 1675 ]) { 1676 await check( 1677 'exact listing editor compiler rejects ' + name + ' ' + mutation, 1678 async (t) => { 1679 const f = await fixture(t), 1680 file = path.join( 1681 f.web, 1682 '.svelte-kit/output/client/.vite/manifest.json' 1683 ); 1684 const manifest = JSON.parse(await readFile(file, 'utf8')); 1685 const entry = Object.entries(manifest).find( 1686 ([, row]) => row.name === name 1687 ); 1688 assert.ok(entry); 1689 const [key, row] = entry; 1690 if (mutation === 'missing') delete manifest[key]; 1691 if (mutation === 'missing-edge') 1692 row.imports = row.imports.slice(1); 1693 if (mutation === 'extra-edge') { 1694 const extra = Object.entries(manifest).find( 1695 ([, record]) => record.name === unrelatedRole 1696 ); 1697 assert.ok(extra, 'Missing actual unrelated compiler role'); 1698 assert.ok(!row.imports.includes(extra[0])); 1699 row.imports = row.imports.concat(extra[0]); 1700 } 1701 if (mutation === 'duplicate-edge') 1702 row.imports = row.imports.concat(row.imports[0]); 1703 if (mutation === 'permuted-edges') 1704 row.imports = [...row.imports].reverse(); 1705 if (mutation === 'dynamic') 1706 row.dynamicImports = [row.imports[0]]; 1707 if (mutation === 'entry') { 1708 if (row.isEntry === true) delete row.isEntry; 1709 else row.isEntry = true; 1710 } 1711 if (mutation === 'css') row.css = []; 1712 await writeFile(file, JSON.stringify(manifest)); 1713 await assert.rejects(f.audit, /compiler|references|import/); 1714 } 1715 ); 1716 } 1717 } 1718 for (const producer of [ 1719 'src/routes/sell/+page.svelte', 1720 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', 1721 'src/routes/products/[naddr=naddr]/edit/+page.svelte', 1722 'src/lib/components/ListingEditor.svelte', 1723 'src/lib/publishing/listing-editor.ts', 1724 'src/lib/components/ListingReview.svelte', 1725 'src/lib/publishing/editor-workflow.ts', 1726 'src/lib/components/ConflictNotice.svelte', 1727 'src/lib/publishing/edit-source.ts', 1728 'src/lib/publishing/prepare-listing.ts', 1729 'src/lib/publishing/new-listing-readiness.ts', 1730 'src/lib/runtime/public-runtime.ts', 1731 'src/lib/persistence/public-publications.ts', 1732 'src/lib/persistence/quota.ts', 1733 'src/lib/publishing/revise-listing.ts', 1734 'src/lib/publishing/mark-sold.ts', 1735 'src/lib/components/ConfirmPanel.svelte', 1736 'src/lib/nostr/listing-publisher.ts', 1737 'src/lib/publishing/withdraw-listing.ts', 1738 'src/lib/publishing/sign-listing.ts', 1739 'src/lib/persistence/artifact-records.ts', 1740 'src/lib/publishing/listing-operation-view.ts', 1741 'src/lib/components/OperationStatus.svelte', 1742 'src/lib/runtime/effect-ownership.ts', 1743 'src/lib/nostr/public-pool.ts', 1744 'src/lib/persistence/public-receipts.ts' 1745 ]) { 1746 await check( 1747 'listing editor rejects changed owned producer ' + producer, 1748 async (t) => { 1749 const f = await fixture(t); 1750 await writeFile( 1751 path.join(f.web, producer), 1752 (await readFile(path.join(f.web, producer), 'utf8')) + 1753 '\n// owned editor source mutation\n' 1754 ); 1755 await refresh(f); 1756 await assert.rejects( 1757 f.audit, 1758 /Invalid owned listing editor source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 1759 ); 1760 } 1761 ); 1762 } 1763 for (const producer of [ 1764 'src/routes/selling/+page.svelte', 1765 'src/lib/components/SellingRow.svelte', 1766 'src/lib/publishing/selling-view.ts' 1767 ]) { 1768 await check( 1769 'seller workspace rejects changed owned producer ' + producer, 1770 async (t) => { 1771 const f = await fixture(t); 1772 await writeFile( 1773 path.join(f.web, producer), 1774 (await readFile(path.join(f.web, producer), 'utf8')) + 1775 '\n// owned seller source mutation\n' 1776 ); 1777 await refresh(f); 1778 await assert.rejects( 1779 f.audit, 1780 /Invalid owned selling workspace source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 1781 ); 1782 } 1783 ); 1784 } 1785 for (const producer of [ 1786 'src/lib/runtime/identity-session.ts', 1787 'src/lib/persistence/local-public-hides.ts', 1788 'src/lib/runtime/public-runtime.ts', 1789 'src/lib/catalog/product-view.ts', 1790 'src/lib/catalog/search-run.ts', 1791 'src/lib/catalog/search-view.ts', 1792 'src/lib/publishing/selling-view.ts', 1793 'src/routes/+layout.svelte', 1794 'src/routes/products/[naddr=naddr]/+page.svelte', 1795 'src/routes/privacy/+page.svelte', 1796 'src/lib/components/PublisherHide.svelte' 1797 ]) { 1798 await check( 1799 'public hiding rejects changed owned producer ' + producer, 1800 async (t) => { 1801 const f = await fixture(t); 1802 await writeFile( 1803 path.join(f.web, producer), 1804 (await readFile(path.join(f.web, producer), 'utf8')) + 1805 '\n// public hiding source mutation\n' 1806 ); 1807 await refresh(f); 1808 await assert.rejects( 1809 f.audit, 1810 /Invalid owned (public hiding source|private blocking source|support reporting source|privacy data source|operational flags source|root runtime activation)/ 1811 ); 1812 } 1813 ); 1814 } 1815 await check( 1816 'private blocking rejects missing actual private-session producer', 1817 async (t) => { 1818 const f = await fixture(t); 1819 await rm(path.join(f.web, 'src/lib/runtime/private-session.ts')); 1820 await refresh(f); 1821 await assert.rejects(f.audit); 1822 } 1823 ); 1824 for (const producer of [ 1825 'src/lib/persistence/local-private-blocks.ts', 1826 'src/lib/runtime/private-session.ts', 1827 'src/lib/messaging/decryption-queue.ts', 1828 'src/lib/messaging/inbox-view.ts', 1829 'src/lib/messaging/cited-product.ts', 1830 'src/lib/components/ConversationOptions.svelte', 1831 'src/lib/components/ConversationThread.svelte', 1832 'src/lib/components/InboxStatus.svelte', 1833 'src/routes/privacy/+page.svelte' 1834 ]) { 1835 await check( 1836 'private blocking rejects changed owned producer ' + producer, 1837 async (t) => { 1838 const f = await fixture(t); 1839 const file = path.join(f.web, producer); 1840 await writeFile( 1841 file, 1842 (await readFile(file, 'utf8')) + 1843 '\n// private blocking source mutation\n' 1844 ); 1845 await refresh(f); 1846 await assert.rejects( 1847 f.audit, 1848 /Invalid owned (private blocking source|support reporting source|privacy data source|operational flags source|root runtime activation)/ 1849 ); 1850 } 1851 ); 1852 } 1853 for (const producer of [ 1854 'src/lib/config/support.ts', 1855 'src/lib/config/deployment-support.ts', 1856 'src/lib/support/report.ts', 1857 'src/lib/components/ReportPreview.svelte', 1858 'src/lib/components/SupportLink.svelte', 1859 'src/routes/about/+page.svelte', 1860 'src/routes/products/[naddr=naddr]/+page.svelte', 1861 'src/lib/components/ConversationOptions.svelte', 1862 'src/lib/navigation-url.ts' 1863 ]) { 1864 await check( 1865 'support reporting rejects changed owned producer ' + producer, 1866 async (t) => { 1867 const f = await fixture(t); 1868 const file = path.join(f.web, producer); 1869 await writeFile( 1870 file, 1871 (await readFile(file, 'utf8')) + 1872 '\n// changed support reporting producer\n' 1873 ); 1874 await refresh(f); 1875 await assert.rejects( 1876 f.audit, 1877 /Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 1878 ); 1879 } 1880 ); 1881 await check( 1882 'support reporting rejects missing owned producer ' + producer, 1883 async (t) => { 1884 const f = await fixture(t); 1885 await rm(path.join(f.web, producer)); 1886 await refresh(f); 1887 await assert.rejects( 1888 f.audit, 1889 /ENOENT|support reporting|incomplete route source/ 1890 ); 1891 } 1892 ); 1893 } 1894 for (const producer of [ 1895 'src/routes/privacy/+page.svelte', 1896 'src/lib/components/LocalDataReview.svelte', 1897 'src/lib/persistence/local-data-review.ts', 1898 'src/lib/persistence/quota.ts', 1899 'src/lib/persistence/private-records.ts', 1900 'src/lib/persistence/inbox-retention.ts', 1901 'src/lib/persistence/local-inventory.ts' 1902 ]) { 1903 await check( 1904 'privacy data rejects changed owned producer ' + producer, 1905 async (t) => { 1906 const f = await fixture(t); 1907 const file = path.join(f.web, producer); 1908 await writeFile( 1909 file, 1910 (await readFile(file, 'utf8')) + 1911 '\n// changed privacy data producer\n' 1912 ); 1913 await refresh(f); 1914 await assert.rejects( 1915 f.audit, 1916 /Invalid owned privacy data source|Invalid owned operational flags source/ 1917 ); 1918 } 1919 ); 1920 await check( 1921 'privacy data rejects missing owned producer ' + producer, 1922 async (t) => { 1923 const f = await fixture(t); 1924 await rm(path.join(f.web, producer)); 1925 await refresh(f); 1926 await assert.rejects( 1927 f.audit, 1928 producer === 'src/routes/privacy/+page.svelte' 1929 ? /Undeclared compiler module: incomplete route source/ 1930 : /ENOENT|privacy data/ 1931 ); 1932 } 1933 ); 1934 } 1935 for (const mutation of [ 1936 'Order placed. Guaranteed delivery.', 1937 'Messages are delivered to the person.' 1938 ]) { 1939 await check( 1940 'privacy copy rejects changed AccountGate ' + mutation, 1941 async (t) => { 1942 const f = await fixture(t); 1943 const file = path.join( 1944 f.web, 1945 'src/lib/components/AccountGate.svelte' 1946 ); 1947 const source = await readFile(file, 'utf8'); 1948 const current = 1949 'Messages stay hidden until you connect and explicitly unlock your inbox.'; 1950 assert.ok(source.includes(current)); 1951 await writeFile(file, source.replace(current, mutation)); 1952 await refresh(f); 1953 await assert.rejects( 1954 f.audit, 1955 /Invalid owned operational flags source/ 1956 ); 1957 } 1958 ); 1959 } 1960 for (const attribute of [ 1961 'rel="noopener noreferrer"', 1962 'referrerpolicy="no-referrer"' 1963 ]) { 1964 await check( 1965 'bounded contact rejects removed ' + attribute, 1966 async (t) => { 1967 const f = await fixture(t); 1968 const file = path.join( 1969 f.web, 1970 'src/routes/products/[naddr=naddr]/+page.svelte' 1971 ); 1972 const source = await readFile(file, 'utf8'); 1973 assert.ok(source.includes(attribute)); 1974 await writeFile(file, source.replace(attribute, '')); 1975 await refresh(f); 1976 await assert.rejects( 1977 f.audit, 1978 /Invalid owned operational flags source/ 1979 ); 1980 } 1981 ); 1982 } 1983 for (const producer of [ 1984 'src/lib/nostr/private-publisher.ts', 1985 'src/lib/persistence/inbox-probes.ts', 1986 'src/lib/persistence/inbox-probe-cleanup.ts', 1987 'src/lib/messaging/inbox-access-qualification.ts', 1988 'src/lib/messaging/inbox-access-check.ts', 1989 'src/lib/nostr/inbox-access.ts', 1990 'src/lib/nostr/seal-builder.ts', 1991 'src/lib/nostr/giftwrap-builder.ts', 1992 'src/lib/config/inbox-operators.ts', 1993 'src/lib/persistence/private-sends.ts', 1994 // CR008-S4C2B: current admissions also bind genuine recovered 1995 // lineage, shared Retry metering and actual private-pool idle state. 1996 'src/lib/nostr/self-recovery-reader.ts', 1997 'src/lib/config/operation-flags.ts', 1998 'src/lib/nostr/private-pool.ts', 1999 'src/lib/messaging/inbox-access-controller.ts', 2000 'src/lib/messaging/inbox-sync.ts', 2001 'src/lib/nostr/inbox-ingress.ts', 2002 'src/lib/config/relays.ts', 2003 'src/lib/runtime/capabilities.ts', 2004 'src/lib/components/AppShell.svelte', 2005 'src/lib/components/ListingEditor.svelte', 2006 'src/lib/components/MessageComposer.svelte', 2007 'src/lib/publishing/prepare-listing.ts', 2008 'src/lib/nostr/listing-publisher.ts', 2009 'src/lib/publishing/resume-listing.ts', 2010 'src/lib/messaging/inbox-setup.ts', 2011 'src/lib/messaging/inbox-setup-operation.ts', 2012 'src/lib/messaging/inbox-setup-view.ts', 2013 'src/lib/messaging/reply-controller.ts', 2014 'src/lib/messaging/product-request-controller.ts', 2015 'src/lib/nostr/inbox-preference-publication.ts', 2016 'src/lib/nostr/incoming-wire.ts', 2017 'src/lib/messaging/send-identity.ts', 2018 'src/lib/persistence/private-send-reservations.ts', 2019 'src/lib/persistence/local-data-review.ts', 2020 'src/lib/persistence/local-inventory.ts', 2021 'src/lib/persistence/private-storage.ts', 2022 'src/lib/persistence/private-outbox-cleanup.ts', 2023 'src/lib/persistence/private-records.ts', 2024 'src/lib/persistence/inbox-envelope-repository.ts', 2025 'src/lib/persistence/history-metadata-repository.ts', 2026 'src/lib/messaging/history-pagination.ts', 2027 'src/lib/runtime/private-session.ts', 2028 'src/lib/components/LocalDataReview.svelte' 2029 ]) { 2030 await check( 2031 'operational flags rejects changed owned producer ' + producer, 2032 async (t) => { 2033 const f = await fixture(t); 2034 const file = path.join(f.web, producer); 2035 await writeFile( 2036 file, 2037 (await readFile(file, 'utf8')) + 2038 '\n// changed operational flags producer\n' 2039 ); 2040 await refresh(f); 2041 await assert.rejects( 2042 f.audit, 2043 /Invalid owned operational flags source/ 2044 ); 2045 } 2046 ); 2047 await check( 2048 'operational flags rejects missing owned producer ' + producer, 2049 async (t) => { 2050 const f = await fixture(t); 2051 await rm(path.join(f.web, producer)); 2052 await refresh(f); 2053 await assert.rejects(f.audit, /ENOENT|operational flags/); 2054 } 2055 ); 2056 } 2057 for (const mutation of [ 2058 'missing-owner', 2059 'duplicate-owner', 2060 'dynamic-edge' 2061 ]) 2062 await check( 2063 'settled cleanup compiler rejects ' + mutation, 2064 async (t) => { 2065 const f = await fixture(t), 2066 file = path.join( 2067 f.web, 2068 '.svelte-kit/output/client/.vite/manifest.json' 2069 ), 2070 manifest = JSON.parse(await readFile(file, 'utf8')), 2071 row = Object.values(manifest).find( 2072 (record) => record.name === 'nodes/6' 2073 ), 2074 owner = Object.entries(manifest).find( 2075 ([, record]) => record.name === 'public-runtime' 2076 )?.[0]; 2077 assert.ok(row && owner && row.imports.includes(owner)); 2078 if (mutation === 'missing-owner') 2079 row.imports = row.imports.filter( 2080 (/** @type {string} */ key) => key !== owner 2081 ); 2082 if (mutation === 'duplicate-owner') 2083 row.imports = [...row.imports, owner]; 2084 if (mutation === 'dynamic-edge') row.dynamicImports = [owner]; 2085 await writeFile(file, JSON.stringify(manifest)); 2086 await assert.rejects( 2087 f.audit, 2088 mutation === 'duplicate-owner' 2089 ? /Invalid compiler references/ 2090 : /Invalid owned listing editor compiler graph/ 2091 ); 2092 } 2093 ); 2094 for (const route of [ 2095 'src/routes/sell/+page.svelte', 2096 'src/routes/selling/drafts/[draftId=local_id]/+page.svelte', 2097 'src/routes/products/[naddr=naddr]/edit/+page.svelte' 2098 ]) { 2099 await check( 2100 'listing editor rejects partial three-route activation ' + route, 2101 async (t) => { 2102 const f = await fixture(t); 2103 const historical = historicalPublicOnly[route]; 2104 assert.equal( 2105 createHash('sha256').update(historical.source).digest('hex'), 2106 historical.sha256 2107 ); 2108 await writeFile(path.join(f.web, route), historical.source); 2109 await refresh(f); 2110 await assert.rejects( 2111 f.audit, 2112 /Invalid owned listing editor activation|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 2113 ); 2114 } 2115 ); 2116 } 2117 for (const producer of [ 2118 'src/routes/products/[naddr=naddr]/+page.svelte', 2119 'src/lib/catalog/product-view.ts', 2120 'src/lib/components/ProductEnquiry.svelte', 2121 'src/lib/messaging/product-enquiry.ts', 2122 'src/lib/messaging/product-request-controller.ts', 2123 'src/lib/messaging/enquiry-readiness.ts', 2124 'src/lib/messaging/resolve-inbox.ts', 2125 'src/lib/components/CapabilityGate.svelte', 2126 'src/lib/messaging/enquiry-context.ts', 2127 'src/lib/components/ListingFacts.svelte', 2128 'src/lib/components/PublisherIdentity.svelte', 2129 'src/lib/contracts/food-availability-v1/contact-read.ts', 2130 'src/lib/navigation-copy.ts', 2131 'src/lib/runtime/public-runtime.ts', 2132 'src/lib/catalog/publishers.ts', 2133 'src/lib/catalog/resolve-head.ts' 2134 ]) { 2135 await check( 2136 'real product compiler rejects changed owned producer ' + producer, 2137 async (t) => { 2138 const f = await fixture(t); 2139 await writeFile( 2140 path.join(f.web, producer), 2141 (await readFile(path.join(f.web, producer), 'utf8')) + 2142 '\n// source mutation\n' 2143 ); 2144 await refresh(f); 2145 await assert.rejects( 2146 f.audit, 2147 producer === 'src/lib/runtime/public-runtime.ts' 2148 ? /Invalid owned (product presentation|listing editor) source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 2149 : /Invalid owned product presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 2150 ); 2151 } 2152 ); 2153 } 2154 for (const mutation of [ 2155 'permuted-edges', 2156 'extra-edge', 2157 'duplicate-edge' 2158 ]) { 2159 await check( 2160 'product compiler dependency order: ' + mutation, 2161 async (t) => { 2162 const f = await fixture(t); 2163 const file = path.join( 2164 f.web, 2165 '.svelte-kit/output/client/.vite/manifest.json' 2166 ); 2167 const manifest = JSON.parse(await readFile(file, 'utf8')); 2168 const find = (/** @type {string} */ name) => { 2169 const row = Object.entries(manifest).find( 2170 ([, v]) => v.name === name 2171 ); 2172 assert.ok(row); 2173 return row; 2174 }; 2175 for (const name of ['nodes/7', 'nodes/9']) { 2176 const row = find(name)[1]; 2177 row.imports = [...row.imports].reverse(); 2178 if (mutation === 'extra-edge') { 2179 const extra = find(unrelatedRole)[0]; 2180 assert.ok(!row.imports.includes(extra)); 2181 row.imports = row.imports.concat(extra); 2182 } 2183 if (mutation === 'duplicate-edge') 2184 row.imports = row.imports.concat(row.imports[0]); 2185 } 2186 await writeFile(file, JSON.stringify(manifest)); 2187 await assert.rejects(f.audit, /compiler|references/); 2188 } 2189 ); 2190 } 2191 for (const mutation of [ 2192 'missing', 2193 'extra-edge', 2194 'missing-edge', 2195 'duplicate-edge', 2196 'dynamic', 2197 'entry', 2198 'css' 2199 ]) { 2200 await check( 2201 'inline request shared composer compiler rejects ' + mutation, 2202 async (t) => { 2203 const f = await fixture(t), 2204 file = path.join( 2205 f.web, 2206 '.svelte-kit/output/client/.vite/manifest.json' 2207 ); 2208 const manifest = JSON.parse(await readFile(file, 'utf8')); 2209 const entry = Object.entries(manifest).find( 2210 ([, row]) => row.name === 'MessageComposer' 2211 ); 2212 assert.ok(entry); 2213 const [key, row] = entry; 2214 if (mutation === 'missing') delete manifest[key]; 2215 if (mutation === 'extra-edge') { 2216 const extra = Object.entries(manifest).find( 2217 ([, record]) => record.name === unrelatedRole 2218 ); 2219 assert.ok(extra, 'Missing actual unrelated compiler role'); 2220 assert.ok(!row.imports.includes(extra[0])); 2221 row.imports = row.imports.concat(extra[0]); 2222 } 2223 if (mutation === 'missing-edge') 2224 row.imports = row.imports.slice(1); 2225 if (mutation === 'duplicate-edge') 2226 row.imports = row.imports.concat(row.imports[0]); 2227 if (mutation === 'dynamic') row.dynamicImports = []; 2228 if (mutation === 'entry') row.isEntry = true; 2229 if (mutation === 'css') row.css = []; 2230 await writeFile(file, JSON.stringify(manifest)); 2231 await assert.rejects(f.audit, /compiler|references/); 2232 } 2233 ); 2234 } 2235 for (const mutation of [ 2236 'missing-publishers', 2237 'publisher-budget', 2238 'publisher-shared', 2239 'publisher-dynamic', 2240 'product-shared', 2241 'product-publisher', 2242 'product-budget', 2243 'product-dynamic', 2244 'search-publisher' 2245 ]) { 2246 await check( 2247 'real product compiler rejects ' + mutation, 2248 async (t) => { 2249 const f = await fixture(t), 2250 file = path.join( 2251 f.web, 2252 '.svelte-kit/output/client/.vite/manifest.json' 2253 ); 2254 const manifest = JSON.parse(await readFile(file, 'utf8')); 2255 const original = JSON.stringify(manifest); 2256 const records = Object.entries(manifest); 2257 const find = (/** @type {string} */ name) => { 2258 const row = records.find(([, v]) => v.name === name); 2259 assert.ok(row); 2260 return row; 2261 }; 2262 const [publisherKey, publisher] = find('publishers'); 2263 if (mutation === 'missing-publishers') 2264 delete manifest[publisherKey]; 2265 else if (mutation === 'publisher-dynamic') 2266 publisher.dynamicImports = [find('client-entry')[0]]; 2267 else if (mutation === 'product-dynamic') 2268 find('nodes/7')[1].dynamicImports = [find('client-entry')[0]]; 2269 else if ( 2270 mutation === 'publisher-budget' || 2271 mutation === 'publisher-shared' 2272 ) 2273 publisher.imports = publisher.imports.filter( 2274 (/** @type {string} */ key) => 2275 key !== 2276 find( 2277 mutation === 'publisher-budget' 2278 ? 'navigation-url' 2279 : Object.values(manifest).some( 2280 (row) => row.name === 'public-runtime' 2281 ) 2282 ? 'public-runtime' 2283 : 'Disclosure' 2284 )[0] 2285 ); 2286 else { 2287 const target = 2288 mutation === 'search-publisher' 2289 ? 'nodes/9' 2290 : mutation === 'product-publisher' 2291 ? 'ReportPreview' 2292 : 'nodes/7'; 2293 const dependency = 2294 mutation === 'product-shared' 2295 ? 'Disclosure' 2296 : mutation === 'product-budget' 2297 ? 'Button' 2298 : 'publishers'; 2299 find(target)[1].imports = find(target)[1].imports.filter( 2300 (/** @type {string} */ key) => key !== find(dependency)[0] 2301 ); 2302 } 2303 assert.notEqual( 2304 JSON.stringify(manifest), 2305 original, 2306 'Every product graph mutation must change the actual input' 2307 ); 2308 await writeFile(file, JSON.stringify(manifest)); 2309 await assert.rejects(f.audit, /compiler|budgets/); 2310 } 2311 ); 2312 } 2313 for (const producer of [ 2314 'src/routes/search/+page.svelte', 2315 'src/lib/catalog/search-view.ts', 2316 'src/lib/components/ListingRow.svelte', 2317 'src/lib/components/SourceStatus.svelte', 2318 'src/lib/navigation-scroll.ts', 2319 'src/lib/components/primitives/Disclosure.svelte' 2320 ]) { 2321 await check( 2322 'real search compiler rejects changed owned producer ' + producer, 2323 async (t) => { 2324 const f = await fixture(t); 2325 await writeFile( 2326 path.join(f.web, producer), 2327 (await readFile(path.join(f.web, producer), 'utf8')) + 2328 '\n// source mutation\n' 2329 ); 2330 await refresh(f); 2331 await assert.rejects( 2332 f.audit, 2333 /Invalid owned search presentation source|Invalid owned public hiding source|Invalid owned private blocking source|Invalid owned support reporting source|Invalid owned privacy data source|Invalid owned operational flags source/ 2334 ); 2335 } 2336 ); 2337 } 2338 for (const mutation of [ 2339 'missing-shared', 2340 'missing-navigation', 2341 'root-edge', 2342 'search-edge', 2343 'budget-edge', 2344 'negentropy-edge', 2345 'sdk-backedge', 2346 'navigation-edge', 2347 'navigation-import', 2348 'navigation-dynamic', 2349 'shared-import' 2350 ]) { 2351 await check('real search compiler rejects ' + mutation, async (t) => { 2352 const f = await fixture(t); 2353 const file = path.join( 2354 f.web, 2355 '.svelte-kit/output/client/.vite/manifest.json' 2356 ); 2357 const manifest = JSON.parse(await readFile(file, 'utf8')); 2358 const original = JSON.stringify(manifest); 2359 const records = Object.entries(manifest); 2360 const find = (/** @type {string} */ name) => { 2361 const entry = records.find(([, v]) => v.name === name); 2362 assert.ok(entry, 'Missing actual compiler record ' + name); 2363 return entry; 2364 }; 2365 const [sharedKey, shared] = find( 2366 Object.values(manifest).some( 2367 (row) => row.name === 'public-runtime' 2368 ) 2369 ? 'public-runtime' 2370 : 'Disclosure' 2371 ); 2372 const [budgetKey] = find('navigation-url'); 2373 if (mutation === 'missing-shared') delete manifest[sharedKey]; 2374 else if (mutation === 'missing-navigation') 2375 delete manifest[find('navigation')[0]]; 2376 else if (mutation === 'root-edge') 2377 find('nodes/0')[1].imports = find('nodes/0')[1].imports.filter( 2378 (/** @type {string} */ k) => k !== sharedKey 2379 ); 2380 else if (mutation === 'search-edge') 2381 find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( 2382 (/** @type {string} */ k) => k !== sharedKey 2383 ); 2384 else if (mutation === 'budget-edge') 2385 shared.imports = shared.imports.filter( 2386 (/** @type {string} */ k) => k !== budgetKey 2387 ); 2388 else if (mutation === 'sdk-backedge') 2389 find('negentropy')[1].imports = []; 2390 else if (mutation === 'navigation-edge') 2391 find('nodes/9')[1].imports = find('nodes/9')[1].imports.filter( 2392 (/** @type {string} */ k) => k !== find('navigation')[0] 2393 ); 2394 else if (mutation === 'navigation-import') 2395 find('navigation')[1].imports = [find('client')[0]]; 2396 else if (mutation === 'navigation-dynamic') 2397 find('navigation')[1].dynamicImports = [find('client-entry')[0]]; 2398 else if (mutation === 'shared-import') 2399 shared.imports = shared.imports.filter( 2400 (/** @type {string} */ k) => k !== find('references')[0] 2401 ); 2402 else shared.dynamicImports = []; 2403 assert.notEqual( 2404 JSON.stringify(manifest), 2405 original, 2406 'Every search graph mutation must change the actual input' 2407 ); 2408 await writeFile(file, JSON.stringify(manifest)); 2409 await assert.rejects(f.audit, /compiler|SDK|budgets/); 2410 }); 2411 } 2412 for (const mutation of [ 2413 'unknown-name', 2414 'duplicate', 2415 'missing-module', 2416 'extra-field', 2417 'missing-root-edge', 2418 'missing-routes-edge', 2419 'missing-counterpart', 2420 'changed-counterpart' 2421 ]) { 2422 await check('budgets module fails closed: ' + mutation, async (t) => { 2423 const f = await fixture(t); 2424 const file = path.join( 2425 f.web, 2426 '.svelte-kit/output/client/.vite/manifest.json' 2427 ); 2428 const manifest = JSON.parse(await readFile(file, 'utf8')); 2429 const original = JSON.stringify(manifest); 2430 const entry = Object.entries(manifest).find( 2431 ([, record]) => record.name === 'navigation-url' 2432 ); 2433 assert.ok(entry); 2434 const [key, budget] = entry; 2435 if (mutation === 'unknown-name') budget.name = 'unapproved-budgets'; 2436 if (mutation === 'duplicate') 2437 manifest['_HCduplicate.js'] = { ...budget }; 2438 if (mutation === 'missing-module') delete manifest[key]; 2439 if (mutation === 'extra-field') budget.dynamicImports = []; 2440 if ( 2441 mutation === 'missing-root-edge' || 2442 mutation === 'missing-routes-edge' 2443 ) { 2444 const name = 2445 mutation === 'missing-root-edge' ? 'nodes/9' : 'routes'; 2446 const consumer = Object.values(manifest).find( 2447 (record) => record.name === name 2448 ); 2449 consumer.imports = consumer.imports.filter( 2450 /** @param {string} dependency */ 2451 (dependency) => dependency !== key 2452 ); 2453 } 2454 if (mutation === 'missing-counterpart') 2455 await rm(path.join(f.web, 'build', budget.file)); 2456 if (mutation === 'changed-counterpart') 2457 await writeFile( 2458 path.join(f.web, 'build', budget.file), 2459 'changed counterpart' 2460 ); 2461 if ( 2462 !['missing-counterpart', 'changed-counterpart'].includes(mutation) 2463 ) 2464 assert.notEqual( 2465 JSON.stringify(manifest), 2466 original, 2467 'Every budgets graph mutation must change the actual input' 2468 ); 2469 await writeFile(file, JSON.stringify(manifest)); 2470 await assert.rejects( 2471 f.audit, 2472 /Undeclared compiler module|Unresolved compiler import|Invalid owned budgets compiler|Invalid owned listing editor compiler graph|Static output inventory mismatch|Static output differs from owned compiler input/ 2473 ); 2474 }); 2475 } 2476 await check( 2477 'actual route-state compiler module has an owned client counterpart', 2478 async (t) => { 2479 const f = await fixture(t); 2480 const manifest = JSON.parse( 2481 await readFile( 2482 path.join( 2483 f.web, 2484 '.svelte-kit/output/client/.vite/manifest.json' 2485 ), 2486 'utf8' 2487 ) 2488 ); 2489 const entries = Object.entries(manifest).filter( 2490 ([, record]) => record.name === 'state' 2491 ); 2492 assert.equal(entries.length, 1); 2493 const [key, state] = entries[0]; 2494 assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); 2495 assert.ok( 2496 state.imports.some( 2497 /** @param {string} dependency */ 2498 (dependency) => manifest[dependency].name === 'client.svelte' 2499 ) 2500 ); 2501 assert.deepEqual( 2502 await readFile(path.join(f.web, 'build', state.file)), 2503 await readFile( 2504 path.join(f.web, '.svelte-kit/output/client', state.file) 2505 ) 2506 ); 2507 assert.ok((await f.audit()).includes(state.file)); 2508 } 2509 ); 2510 for (const mutation of [ 2511 'unknown-name', 2512 'duplicate-state', 2513 'missing-counterpart', 2514 'changed-counterpart' 2515 ]) { 2516 await check('state module fails closed: ' + mutation, async (t) => { 2517 const f = await fixture(t); 2518 const file = path.join( 2519 f.web, 2520 '.svelte-kit/output/client/.vite/manifest.json' 2521 ); 2522 const manifest = JSON.parse(await readFile(file, 'utf8')); 2523 const state = Object.values(manifest).find( 2524 (record) => record.name === 'state' 2525 ); 2526 assert.ok( 2527 state, 2528 'The actual route-state module must exist before mutation' 2529 ); 2530 if (mutation === 'unknown-name') state.name = 'state-unapproved'; 2531 if (mutation === 'duplicate-state') 2532 manifest['_HCduplicate.js'] = { ...state }; 2533 if (mutation === 'missing-counterpart') 2534 await rm(path.join(f.web, 'build', state.file)); 2535 if (mutation === 'changed-counterpart') 2536 await writeFile( 2537 path.join(f.web, 'build', state.file), 2538 Buffer.concat([ 2539 await readFile(path.join(f.web, 'build', state.file)), 2540 Buffer.from('changed counterpart') 2541 ]) 2542 ); 2543 await writeFile(file, JSON.stringify(manifest)); 2544 await assert.rejects( 2545 f.audit, 2546 mutation.endsWith('name') || mutation === 'duplicate-state' 2547 ? /Undeclared compiler module/ 2548 : /Static output inventory mismatch|Static output differs from owned compiler input/ 2549 ); 2550 }); 2551 } 2552 await check( 2553 'actual shared Button compiler module has an owned client counterpart', 2554 async (t) => { 2555 const f = await fixture(t); 2556 const manifest = JSON.parse( 2557 await readFile( 2558 path.join( 2559 f.web, 2560 '.svelte-kit/output/client/.vite/manifest.json' 2561 ), 2562 'utf8' 2563 ) 2564 ); 2565 const entries = Object.entries(manifest).filter( 2566 ([, record]) => record.name === 'Button' 2567 ); 2568 assert.equal(entries.length, 1); 2569 const [key, button] = entries[0]; 2570 assert.match(key, /^_[A-Za-z0-9_-]+\.js$/); 2571 assert.ok( 2572 button.imports.some( 2573 /** @param {string} dependency */ 2574 (dependency) => manifest[dependency].name === 'client' 2575 ) 2576 ); 2577 for (const consumer of ['nodes/0', 'nodes/9']) { 2578 assert.ok( 2579 Object.values(manifest).some( 2580 (record) => 2581 record.name === consumer && record.imports.includes(key) 2582 ) 2583 ); 2584 } 2585 assert.deepEqual( 2586 await readFile(path.join(f.web, 'build', button.file)), 2587 await readFile( 2588 path.join(f.web, '.svelte-kit/output/client', button.file) 2589 ) 2590 ); 2591 assert.ok((await f.audit()).includes(button.file)); 2592 } 2593 ); 2594 for (const mutation of [ 2595 'unknown-name', 2596 'duplicate-Button', 2597 'missing-counterpart', 2598 'changed-counterpart' 2599 ]) { 2600 await check('Button module fails closed: ' + mutation, async (t) => { 2601 const f = await fixture(t); 2602 const file = path.join( 2603 f.web, 2604 '.svelte-kit/output/client/.vite/manifest.json' 2605 ); 2606 const manifest = JSON.parse(await readFile(file, 'utf8')); 2607 const state = Object.values(manifest).find( 2608 (record) => record.name === 'Button' 2609 ); 2610 assert.ok( 2611 state, 2612 'The actual shared Button module must exist before mutation' 2613 ); 2614 if (mutation === 'unknown-name') state.name = 'Button-unapproved'; 2615 if (mutation === 'duplicate-Button') 2616 manifest['_HCduplicate.js'] = { ...state }; 2617 if (mutation === 'missing-counterpart') 2618 await rm(path.join(f.web, 'build', state.file)); 2619 if (mutation === 'changed-counterpart') 2620 await writeFile( 2621 path.join(f.web, 'build', state.file), 2622 Buffer.concat([ 2623 await readFile(path.join(f.web, 'build', state.file)), 2624 Buffer.from('changed counterpart') 2625 ]) 2626 ); 2627 await writeFile(file, JSON.stringify(manifest)); 2628 await assert.rejects( 2629 f.audit, 2630 mutation.endsWith('name') || mutation === 'duplicate-Button' 2631 ? /Undeclared compiler module/ 2632 : /Static output inventory mismatch|Static output differs from owned compiler input/ 2633 ); 2634 }); 2635 } 2636 for (const name of [ 2637 'notes.txt', 2638 '_app/immutable/chunks/innocent.ABC12345.js', 2639 'docs/parent.html', 2640 'state.css', 2641 'source.map', 2642 'contracts/vector.json' 2643 ]) { 2644 await check( 2645 `undeclared copied output is rejected: ${name}`, 2646 async (t) => { 2647 const f = await fixture(t); 2648 const file = path.join(f.web, 'build', name); 2649 await mkdir(path.dirname(file), { recursive: true }); 2650 await writeFile(file, 'ordinary public text'); 2651 await assert.rejects(f.audit); 2652 } 2653 ); 2654 } 2655 for (const payload of [ 2656 Buffer.from('SQLite format 3\0'), 2657 Buffer.from([0x7f, 0x45, 0x4c, 0x46]), 2658 Buffer.from([0xcf, 0xfa, 0xed, 0xfe]), 2659 Buffer.from('PK\x03\x04'), 2660 Buffer.from('MZnative'), 2661 Buffer.from('generated UniFFI bindings'), 2662 Buffer.from('HC_TEST_ONLY_SECRET'), 2663 Buffer.from('nsec1' + 'a'.repeat(60)), 2664 Buffer.from('-----BEGIN PRIVATE KEY-----'), 2665 Buffer.from('private_transcript: controlled disclosure'), 2666 Buffer.from('class TestSigner {}') 2667 ]) { 2668 await check( 2669 `manifest-admitted contamination ${payload.subarray(0, 18).toString('hex')}`, 2670 async (t) => { 2671 const f = await fixture(t); 2672 const manifest = JSON.parse( 2673 await readFile( 2674 path.join( 2675 f.web, 2676 '.svelte-kit/output/client/.vite/manifest.json' 2677 ), 2678 'utf8' 2679 ) 2680 ); 2681 const name = Object.values(manifest).find( 2682 (entry) => entry.name === 'client' 2683 ).file; 2684 // Poison both sides: byte mapping alone does not qualify contents. 2685 for (const directory of ['build', '.svelte-kit/output/client']) 2686 await writeFile(path.join(f.web, directory, name), payload); 2687 await assert.rejects(f.audit, /contamination|binary|text/); 2688 } 2689 ); 2690 } 2691 for (const name of [ 2692 'index.html', 2693 '200.html', 2694 '_app/version.json', 2695 'build-info.json' 2696 ]) { 2697 await check(`missing/tampered owned output: ${name}`, async (t) => { 2698 const f = await fixture(t); 2699 const file = path.join(f.web, 'build', name); 2700 const original = await readFile(file); 2701 await rm(file); 2702 await assert.rejects(f.audit); 2703 await writeFile( 2704 file, 2705 Buffer.concat([original, Buffer.from('tampered')]) 2706 ); 2707 await assert.rejects(f.audit); 2708 }); 2709 } 2710 for (const mutation of [ 2711 'unknown', 2712 'private', 2713 'revision', 2714 'dirty', 2715 'lock', 2716 'config', 2717 'source', 2718 'generated' 2719 ]) { 2720 await check(`provenance fails closed: ${mutation}`, async (t) => { 2721 const f = await fixture(t); 2722 const metadata = JSON.parse( 2723 await readFile(path.join(f.web, 'build/build-info.json'), 'utf8') 2724 ); 2725 if (mutation === 'unknown') metadata.web_source.unknown = 'extra'; 2726 if (mutation === 'private') 2727 metadata.private_transcript = 'controlled disclosure'; 2728 if (mutation === 'revision') 2729 metadata.web_source.revision = 'a'.repeat(40); 2730 if (mutation === 'dirty') 2731 metadata.web_source.dirty = !metadata.web_source.dirty; 2732 if (mutation === 'lock') 2733 await writeFile( 2734 path.join(f.web, 'pnpm-lock.yaml'), 2735 'changed lock' 2736 ); 2737 if (mutation === 'config') 2738 await writeFile( 2739 path.join(f.web, 'vite.config.ts'), 2740 'changed config' 2741 ); 2742 if (mutation === 'source') 2743 await writeFile( 2744 path.join(f.web, 'src/app.html'), 2745 'changed source' 2746 ); 2747 if (mutation === 'generated') 2748 git(f.root, 'add', '-f', 'web/static/build-info.json'); 2749 if ( 2750 ['unknown', 'private', 'revision', 'dirty'].includes(mutation) 2751 ) { 2752 for (const directory of [ 2753 'build', 2754 'static', 2755 '.svelte-kit/output/client' 2756 ]) 2757 await writeFile( 2758 path.join(f.web, directory, 'build-info.json'), 2759 JSON.stringify(metadata) 2760 ); 2761 } 2762 await assert.rejects(f.audit); 2763 }); 2764 } 2765 for (const kind of [ 2766 'symlink', 2767 'hardlink', 2768 'fifo', 2769 'directory', 2770 'oversize', 2771 'parent' 2772 ]) { 2773 await check(`unsafe output refuses ${kind} promptly`, async (t) => { 2774 const f = await fixture(t); 2775 const file = path.join(f.web, 'build/index.html'); 2776 await rm(file); 2777 if (kind === 'symlink') await symlink('../src/app.html', file); 2778 if (kind === 'hardlink') 2779 await link(path.join(f.web, 'src/app.html'), file); 2780 if (kind === 'fifo') execFileSync('mkfifo', [file]); 2781 if (kind === 'directory') await mkdir(file); 2782 if (kind === 'oversize') 2783 await writeFile(file, Buffer.alloc(8 * 1024 * 1024 + 1)); 2784 if (kind === 'parent') { 2785 await rm(path.join(f.web, 'build'), { recursive: true }); 2786 await symlink( 2787 path.join(base, 'web/build'), 2788 path.join(f.web, 'build') 2789 ); 2790 } 2791 await assert.rejects(f.audit); 2792 }); 2793 } 2794 await check( 2795 'compiler manifest cannot authorize arbitrary resources, escapes or unresolved imports', 2796 async (t) => { 2797 const f = await fixture(t); 2798 const file = path.join( 2799 f.web, 2800 '.svelte-kit/output/client/.vite/manifest.json' 2801 ); 2802 const original = await readFile(file, 'utf8'); 2803 for (const mutation of [ 2804 'extra', 2805 'escape', 2806 'reference', 2807 'unknown' 2808 ]) { 2809 const manifest = JSON.parse(original); 2810 const record = Object.values(manifest)[0]; 2811 if (mutation === 'extra') 2812 manifest.extra = { 2813 name: 'provider', 2814 file: '_app/immutable/chunks/provider.ABC12345.js' 2815 }; 2816 if (mutation === 'escape') record.file = '../outside.js'; 2817 if (mutation === 'reference') record.imports = ['absent']; 2818 if (mutation === 'unknown') record.secret = 'private'; 2819 await writeFile(file, JSON.stringify(manifest)); 2820 await assert.rejects(f.audit); 2821 } 2822 } 2823 ); 2824 2825 await check( 2826 'generated provenance must remain ignored even when freshly regenerated', 2827 async (t) => { 2828 const f = await fixture(t); 2829 await writeFile(path.join(f.web, '.gitignore'), ''); 2830 await generateBuildInfo(f.web); 2831 await assert.rejects(f.audit, /must be ignored/); 2832 } 2833 ); 2834 for (const name of [ 2835 'static/build-info.json', 2836 '.svelte-kit/output/client/.vite/manifest.json', 2837 '.svelte-kit/output/prerendered/pages/index.html', 2838 '.svelte-kit/output/prerendered/pages/search.html', 2839 'src/routes/search/+page.svelte', 2840 'static/robots.txt', 2841 '.svelte-kit/output/prerendered/pages/messages.html' 2842 ]) { 2843 for (const kind of ['fifo', 'symlink', 'hardlink']) { 2844 await check( 2845 `unsafe compiler/static counterpart ${name}: ${kind}`, 2846 async (t) => { 2847 const f = await fixture(t); 2848 const file = path.join(f.web, name); 2849 await rm(file); 2850 if (kind === 'fifo') execFileSync('mkfifo', [file]); 2851 if (kind === 'symlink') 2852 await symlink(path.join(base, 'web/src/app.html'), file); 2853 if (kind === 'hardlink') 2854 await link(path.join(f.web, 'src/app.html'), file); 2855 await assert.rejects(f.audit); 2856 } 2857 ); 2858 } 2859 } 2860 await check( 2861 'empty output directory and excessive depth are rejected', 2862 async (t) => { 2863 const f = await fixture(t); 2864 await mkdir(path.join(f.web, 'build/extra')); 2865 await assert.rejects(f.audit); 2866 await rm(path.join(f.web, 'build/extra'), { recursive: true }); 2867 await mkdir(path.join(f.web, 'build/a/b/c/d/e/f/g/h/i'), { 2868 recursive: true 2869 }); 2870 await assert.rejects(f.audit); 2871 } 2872 ); 2873 await check( 2874 'forged public output failures do not echo private poisoned bytes', 2875 async (t) => { 2876 const f = await fixture(t); 2877 const marker = 'CONTROLLED_SENSITIVE_DO_NOT_ECHO'; 2878 const file = path.join(f.web, 'static/build-info.json'); 2879 await writeFile(file, marker); 2880 await assert.rejects( 2881 f.audit, 2882 (error) => !String(error).includes(marker) 2883 ); 2884 } 2885 ); 2886 await check( 2887 'output entry and aggregate-byte bounds reject oversized inventories', 2888 async (t) => { 2889 const f = await fixture(t); 2890 for (let i = 0; i < 513; i++) 2891 await writeFile(path.join(f.web, 'build', `tiny-${i}.js`), 'x'); 2892 // Confine the actual audit's allocation measurement to a fresh child; 2893 // prior source/output fixture copies must not enter this baseline/peak. 2894 const measurement = JSON.parse( 2895 execFileSync( 2896 process.execPath, 2897 [ 2898 '--input-type=module', 2899 '-e', 2900 ` 2901 const { auditOutput } = await import(process.argv[2]); 2902 const baseline = process.memoryUsage().arrayBuffers; 2903 let peak = baseline, rejection; 2904 const sample = () => { peak = Math.max(peak, process.memoryUsage().arrayBuffers); }; 2905 const timer = setInterval(sample, 1); 2906 try { await auditOutput(process.argv[1]); } 2907 catch (error) { rejection = error instanceof Error ? error.message : 'unexpected'; } 2908 finally { sample(); clearInterval(timer); } 2909 if (rejection !== 'Unbounded output inventory') throw new Error('Unexpected inventory measurement rejection'); 2910 process.stdout.write(JSON.stringify({ baseline, peak, growth: peak - baseline, rejection })); 2911 `, 2912 f.web, 2913 new URL('../../tools/check-output.mjs', import.meta.url).href 2914 ], 2915 { 2916 cwd: f.web, 2917 encoding: 'utf8', 2918 timeout: 86400000, 2919 maxBuffer: 4096 2920 } 2921 ) 2922 ); 2923 assert.deepEqual(Object.keys(measurement).sort(), [ 2924 'baseline', 2925 'growth', 2926 'peak', 2927 'rejection' 2928 ]); 2929 assert.equal(measurement.rejection, 'Unbounded output inventory'); 2930 for (const name of ['baseline', 'peak', 'growth']) 2931 assert.ok( 2932 Number.isSafeInteger(measurement[name]) && 2933 measurement[name] >= 0 2934 ); 2935 assert.equal( 2936 measurement.growth, 2937 measurement.peak - measurement.baseline 2938 ); 2939 t.diagnostic( 2940 'isolated actual inventory buffers: ' + 2941 JSON.stringify(measurement) 2942 ); 2943 assert.ok( 2944 measurement.growth < 64 * 1024 * 1024, 2945 'Tiny files must not retain a maximum-sized buffer per entry: ' + 2946 JSON.stringify(measurement) 2947 ); 2948 for (let i = 0; i < 513; i++) 2949 await rm(path.join(f.web, 'build', `tiny-${i}.js`)); 2950 for (let i = 0; i < 33; i++) 2951 await writeFile( 2952 path.join(f.web, 'build', `large-${i}.js`), 2953 Buffer.alloc(1024 * 1024, 97) 2954 ); 2955 await assert.rejects(f.audit, /Unbounded output bytes/); 2956 } 2957 ); 2958 } 2959 ); 2960 await test( 2961 'actual compiler admits nonempty approved theme/app CSS', 2962 { timeout: 86400000 }, 2963 async (t) => { 2964 ready(t); 2965 const layout = path.join(base, 'web/src/routes/+layout.svelte'); 2966 const root = await readFile(layout, 'utf8'); 2967 assert.equal(root.split("import '../theme.css';").length - 1, 1); 2968 assert.equal(root.split("import '../app.css';").length - 1, 1); 2969 await writeFile( 2970 path.join(base, 'web/src/theme.css'), 2971 ':root { --hc-accent: #336633; }\n' 2972 ); 2973 await writeFile( 2974 path.join(base, 'web/src/app.css'), 2975 'main { color: var(--hc-accent); }\n' 2976 ); 2977 await generateBuildInfo(path.join(base, 'web')); 2978 compile(t, path.join(base, 'web')); 2979 const files = await auditOutput(await realpath(path.join(base, 'web'))); 2980 assert.ok(files.some((name) => name.endsWith('.css'))); 2981 } 2982 ); 2983 } finally { 2984 // Await the complete serial sequence before reclaiming its shared build. 2985 await rm(base, { recursive: true, force: true }); 2986 } 2987 }