@powerhousedao/reactor-browser 6.2.3-dev.22 → 6.2.3-dev.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attachment-service-C14mVTk_.d.ts → attachment-service-cIdRZcTa.d.ts} +36 -9
- package/dist/attachment-service-cIdRZcTa.d.ts.map +1 -0
- package/dist/{document-by-id-iXB59Ge-.js → document-by-id-DgdUGMVm.js} +163 -35
- package/dist/document-by-id-DgdUGMVm.js.map +1 -0
- package/dist/{document-model-modules-BSwKnUR_.js → document-model-modules-D1ZEoGjN.js} +21 -9
- package/dist/document-model-modules-D1ZEoGjN.js.map +1 -0
- package/dist/{document-operations-BjZmu1JC.js → document-operations-DhrcpXMf.js} +42 -26
- package/dist/document-operations-DhrcpXMf.js.map +1 -0
- package/dist/{global-D4e836Hk.d.ts → global-BGoyNc1s.d.ts} +10 -3
- package/dist/global-BGoyNc1s.d.ts.map +1 -0
- package/dist/{index-BvJaeywJ.d.ts → index-DrgDweMA.d.ts} +2 -2
- package/dist/{index-BvJaeywJ.d.ts.map → index-DrgDweMA.d.ts.map} +1 -1
- package/dist/index.d.ts +20 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +73 -20
- package/dist/index.js.map +1 -1
- package/dist/src/ai/index.d.ts +1 -1
- package/dist/src/ai/index.js +2 -2
- package/dist/src/analytics/index.js +1 -1
- package/dist/src/graphql-client/entry.d.ts +2 -2
- package/dist/src/graphql-client/entry.js +3 -3
- package/dist/src/renown/index.d.ts +1 -1
- package/dist/src/rpc/index.d.ts +1 -1
- package/dist/src/rpc/index.js +1 -1
- package/dist/{switchboard-Yt6ASJRx.js → switchboard-BEiFkv9K.js} +3 -3
- package/dist/{switchboard-Yt6ASJRx.js.map → switchboard-BEiFkv9K.js.map} +1 -1
- package/package.json +11 -11
- package/dist/attachment-service-C14mVTk_.d.ts.map +0 -1
- package/dist/document-by-id-iXB59Ge-.js.map +0 -1
- package/dist/document-model-modules-BSwKnUR_.js.map +0 -1
- package/dist/document-operations-BjZmu1JC.js.map +0 -1
- package/dist/global-D4e836Hk.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-by-id-DgdUGMVm.js","names":[],"sources":["../src/actions/queue.ts","../src/actions/sign.ts","../src/actions/dispatch.ts","../src/document-refetcher.ts","../src/reactor-interop.ts","../src/document-cache.ts","../src/hooks/document-cache.ts","../src/hooks/dispatch.ts","../src/hooks/document-by-id.ts"],"sourcesContent":["import type { FileUploadProgressCallback } from \"@powerhousedao/reactor-browser\";\nimport type {\n Action,\n DocumentOperations,\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\n\nexport async function queueActions(\n document: PHDocument | undefined,\n actionOrActions: Action[] | Action | undefined,\n) {\n if (!document) {\n throw new Error(\"No document provided\");\n }\n if (!actionOrActions) {\n throw new Error(\"No actions provided\");\n }\n const actions = Array.isArray(actionOrActions)\n ? actionOrActions\n : [actionOrActions];\n\n if (actions.length === 0) {\n throw new Error(\"No actions provided\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n return await reactorClient.execute(document.header.id, \"main\", actions);\n}\n\nexport async function queueOperations(\n documentId: string,\n operationOrOperations: Operation[] | Operation | undefined,\n) {\n if (!documentId) {\n throw new Error(\"No documentId provided\");\n }\n if (!operationOrOperations) {\n throw new Error(\"No operations provided\");\n }\n const operations = Array.isArray(operationOrOperations)\n ? operationOrOperations\n : [operationOrOperations];\n\n if (operations.length === 0) {\n throw new Error(\"No operations provided\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const actions = operations.map((op) => op.action);\n return await reactorClient.execute(documentId, \"main\", actions);\n}\n\nexport function deduplicateOperations(\n existingOperations: Record<string, Operation[]>,\n operationsToDeduplicate: Operation[],\n) {\n // make a set of all the operation indices for each scope to avoid duplicates\n const operationIndicesByScope = {} as Record<string, Set<number>>;\n for (const scope of Object.keys(existingOperations)) {\n operationIndicesByScope[scope] = new Set(\n existingOperations[scope].map((op) => op.index),\n );\n }\n\n const newOperations: Operation[] = [];\n\n for (const operation of operationsToDeduplicate) {\n const scope = operation.action.scope;\n const index = operation.index;\n if (operationIndicesByScope[scope].has(index)) {\n const duplicatedExistingOperation = existingOperations[scope].find(\n (op) => op.index === index,\n );\n const duplicatedNewOperation = newOperations.find(\n (op) => op.index === index,\n );\n console.warn(\"skipping duplicate operation\");\n if (duplicatedExistingOperation) {\n console.warn(\n \"duplicate existing operation\",\n duplicatedExistingOperation,\n );\n }\n if (duplicatedNewOperation) {\n console.warn(\"duplicate new operation\", duplicatedNewOperation);\n }\n continue;\n }\n newOperations.push(operation);\n operationIndicesByScope[scope].add(index);\n }\n\n const uniqueOperationIds = new Set<string>();\n const operationsDedupedById: Operation[] = [];\n\n for (const [scope, operations] of Object.entries(existingOperations)) {\n for (const operation of operations) {\n const id = operation.id;\n if (!id) {\n console.warn(\"skipping operation with no id\", operation);\n continue;\n }\n if (uniqueOperationIds.has(id)) {\n console.warn(\n \"skipping existing operation with duplicate id in scope\",\n scope,\n operation,\n );\n continue;\n }\n uniqueOperationIds.add(id);\n }\n }\n\n for (const operation of newOperations) {\n const id = operation.id;\n if (!id) {\n console.warn(\"skipping operation with no id\", operation);\n continue;\n }\n if (uniqueOperationIds.has(id)) {\n console.warn(\n \"skipping new operation with duplicate id in scope\",\n operation.action.scope,\n operation,\n );\n continue;\n }\n uniqueOperationIds.add(id);\n operationsDedupedById.push(operation);\n }\n return operationsDedupedById;\n}\n\nexport async function uploadOperations(\n documentId: string,\n allOperations: DocumentOperations,\n pushOperations: (\n documentId: string,\n operations: Operation[],\n ) => Promise<PHDocument | undefined>,\n options?: {\n operationsLimit?: number;\n onProgress?: FileUploadProgressCallback;\n },\n) {\n const operationsLimit = options?.operationsLimit || 50;\n const onProgress = options?.onProgress;\n\n logger.verbose(\n `uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(\",\")}, limit:${operationsLimit})`,\n );\n\n // Calculate total operations for progress tracking\n const allOperationsArray = Object.values(allOperations).filter(\n (ops): ops is Operation[] => ops !== undefined,\n );\n const totalOperations = allOperationsArray.reduce(\n (total, operations) => total + operations.length,\n 0,\n );\n let uploadedOperations = 0;\n\n for (const operations of allOperationsArray) {\n for (let i = 0; i < operations.length; i += operationsLimit) {\n logger.verbose(\n `uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`,\n );\n const chunk = operations.slice(i, i + operationsLimit);\n const operation = chunk.at(-1);\n if (!operation) {\n break;\n }\n const scope = operation.action.scope;\n\n await pushOperations(documentId, chunk);\n\n uploadedOperations += chunk.length;\n\n // Report progress\n if (onProgress) {\n const progress = Math.round(\n (uploadedOperations / totalOperations) * 100,\n );\n onProgress({\n stage: \"uploading\",\n progress,\n totalOperations,\n uploadedOperations,\n });\n }\n\n logger.verbose(\n `uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`,\n );\n }\n }\n\n logger.verbose(\n `uploadDocumentOperations:for:waitForUpdate(${documentId}): END`,\n );\n}\n","import type {\n Action,\n ActionSigner,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\n\nexport function addActionContext(action: Action) {\n const renown = window.ph?.renown;\n if (!renown?.user) return action;\n\n const signer: ActionSigner = {\n app: {\n name: \"Connect\",\n key: renown.did,\n },\n user: {\n address: renown.user.address,\n networkId: renown.user.networkId,\n chainId: renown.user.chainId,\n },\n signatures: [],\n };\n\n return {\n context: { signer },\n ...action,\n };\n}\n\nfunction makeSignedActionWithContext(\n action: Action | undefined,\n document: PHDocument | undefined,\n) {\n if (!action) {\n logger.error(\"No action found\");\n return;\n }\n if (!document) {\n logger.error(\"No document found\");\n return;\n }\n // The reactor client signs it: an empty signer is filled in for the log the\n // write lands in, which only the client knows.\n return addActionContext(action);\n}\n\nexport function makeSignedActionsWithContext(\n actionOrActions: Action[] | Action | undefined,\n document: PHDocument | undefined,\n) {\n if (!actionOrActions) {\n logger.error(\"No actions found\");\n return;\n }\n const actions = Array.isArray(actionOrActions)\n ? actionOrActions\n : [actionOrActions];\n\n const signedActionsWithContext = actions.map((action) =>\n makeSignedActionWithContext(action, document),\n );\n return signedActionsWithContext.filter((a) => a !== undefined);\n}\n","import type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { queueActions } from \"./queue.js\";\nimport { makeSignedActionsWithContext } from \"./sign.js\";\n\nasync function getDocument(\n documentId: string,\n): Promise<PHDocument | undefined> {\n try {\n return await window.ph?.reactorClient?.get(documentId);\n } catch (error) {\n logger.debug(`Failed to get document with id ${documentId}:`, error);\n return undefined;\n }\n}\n\nfunction getActionErrors(result: PHDocument, actions: Action[]) {\n return actions.reduce((errors, a) => {\n const scopeOperations = result.operations[a.scope];\n if (!scopeOperations) {\n return errors;\n }\n const op = scopeOperations.findLast((op) => op.action.id === a.id);\n\n if (op?.error) {\n errors.push(new Error(op.error));\n }\n return errors;\n }, new Array<Error>());\n}\n\n/**\n * Dispatches actions to a document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param document - The document to dispatch actions to.\n * @param onErrors - Callback invoked with any errors that occurred during action execution.\n * @returns The updated document, or undefined if the dispatch failed.\n */\nexport async function dispatchActions<TDocument = PHDocument, TAction = Action>(\n actionOrActions: TAction[] | TAction | undefined,\n document: TDocument | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n): Promise<PHDocument | undefined>;\n/**\n * Dispatches actions to a document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param documentId - The ID of the document to dispatch actions to.\n * @param onErrors - Callback invoked with any errors that occurred during action execution.\n * @returns The updated document, or undefined if the dispatch failed.\n */\nexport async function dispatchActions(\n actionOrActions: Action[] | Action | undefined,\n documentId: string,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n): Promise<PHDocument | undefined>;\nexport async function dispatchActions(\n actionOrActions: Action[] | Action | undefined,\n documentOrDocumentId: PHDocument | string | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n): Promise<PHDocument | undefined> {\n const document =\n typeof documentOrDocumentId === \"string\"\n ? await getDocument(documentOrDocumentId)\n : documentOrDocumentId;\n\n if (!document) {\n logger.error(\n `Document with id ${JSON.stringify(documentOrDocumentId)} not found`,\n );\n return;\n }\n\n const signedActionsWithContext = makeSignedActionsWithContext(\n actionOrActions,\n document,\n );\n if (!signedActionsWithContext) {\n logger.error(\"No signed actions with context found\");\n return;\n }\n const result = await queueActions(document, signedActionsWithContext);\n\n if (onErrors && result) {\n const errors = getActionErrors(result, signedActionsWithContext);\n if (errors.length) {\n onErrors(errors);\n }\n }\n\n if (onSuccess && result) {\n onSuccess(result);\n }\n\n return result;\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport type {\n DocumentRefetchState,\n FulfilledPromise,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.js\";\n\n/** The refetch snapshot of a document with nothing in flight and no kept failure. */\nexport const IDLE_REFETCH_STATE: DocumentRefetchState = Object.freeze({\n isRefetching: false,\n error: undefined,\n});\n\nfunction fulfilledPromise<T>(value: T): FulfilledPromise<T> {\n const promise = Promise.resolve(value) as FulfilledPromise<T>;\n promise.status = \"fulfilled\";\n promise.value = value;\n return promise;\n}\n\nfunction rejectedPromise<T>(reason: unknown): RejectedPromise<T> {\n const promise = Promise.reject(reason as Error) as RejectedPromise<T>;\n promise.status = \"rejected\";\n promise.reason = reason;\n // Readers get the reason from `status`; the refetch caller gets the rejection.\n promise.catch(() => undefined);\n return promise;\n}\n\nconst MISSING_DOCUMENT_ERRORS = [\n \"DocumentNotFoundError\",\n \"DocumentDeletedError\",\n];\n\n// The document is gone, so its last loaded state must not stay on screen.\n// The document view and GraphQL client throw a plain \"Document not found\" Error.\nexport function isMissingDocumentError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n return (\n MISSING_DOCUMENT_ERRORS.includes(error.name) ||\n error.message.startsWith(\"Document not found\")\n );\n}\n\nconst noop = () => undefined;\n\n/** One refetch running per cache key, and at most one queued behind it. */\ntype Refetch = {\n running: Promise<PHDocument> | undefined;\n queued: Promise<PHDocument> | undefined;\n};\n\nexport type DocumentRefetcherHost = {\n /** The cache's stored promises; an entry is replaced only once its refetch settles. */\n documents: Map<string, PromiseWithState<PHDocument>>;\n fetch(id: string): Promise<PHDocument>;\n notify(id: string): void;\n onFetched?(id: string, document: PHDocument): void;\n};\n\n/** Background refetch of loaded documents: readers keep the loaded promise until it settles. */\nexport class DocumentRefetcher {\n private refetches = new Map<string, Refetch>();\n private states = new Map<string, DocumentRefetchState>();\n\n constructor(private readonly host: DocumentRefetcherHost) {}\n\n getState(id: string): DocumentRefetchState {\n return this.states.get(id) ?? IDLE_REFETCH_STATE;\n }\n\n /** Serializes refetches per key: one runs, later requests share one queued run. */\n refetch(id: string): Promise<PHDocument> {\n let entry = this.refetches.get(id);\n if (!entry) {\n entry = { running: undefined, queued: undefined };\n this.refetches.set(id, entry);\n const current = this.host.documents.get(id);\n if (current?.status !== \"pending\") {\n return this.start(id, entry);\n }\n // A pending first load may predate the change, so refetch after it.\n entry.running = current;\n }\n const inFlight = entry;\n inFlight.queued ??= (inFlight.running ?? Promise.resolve())\n .then(noop, noop)\n .then(() => this.start(id, inFlight));\n return inFlight.queued;\n }\n\n /** Stops any refetch of `id` from writing back, e.g. on deletion. */\n forget(id: string): void {\n this.refetches.delete(id);\n this.states.delete(id);\n }\n\n clear(): void {\n this.refetches.clear();\n this.states.clear();\n }\n\n private start(id: string, entry: Refetch): Promise<PHDocument> {\n entry.queued = undefined;\n entry.running = this.run(id, entry);\n return entry.running;\n }\n\n private async run(id: string, entry: Refetch): Promise<PHDocument> {\n const isCurrent = () => this.refetches.get(id) === entry;\n // Superseded: answer the caller without touching the cache.\n if (!isCurrent()) {\n return this.host.fetch(id);\n }\n const started = this.setState(id, {\n isRefetching: true,\n error: this.getState(id).error,\n });\n if (started) {\n this.host.notify(id);\n }\n try {\n const document = await this.host.fetch(id);\n if (isCurrent()) {\n this.host.onFetched?.(id, document);\n this.host.documents.set(id, fulfilledPromise(document));\n this.finish(id, entry, undefined);\n }\n return document;\n } catch (error) {\n if (isCurrent()) {\n if (isMissingDocumentError(error)) {\n this.host.documents.set(id, rejectedPromise(error));\n this.finish(id, entry, undefined);\n } else {\n console.warn(\n \"[DocumentCache] Refetch failed; keeping the loaded document:\",\n error,\n );\n this.finish(id, entry, error);\n }\n }\n throw error;\n }\n }\n\n private finish(id: string, entry: Refetch, error: unknown): void {\n if (!entry.queued) {\n this.refetches.delete(id);\n }\n this.setState(id, { isRefetching: entry.queued !== undefined, error });\n this.host.notify(id);\n }\n\n /** Returns whether the snapshot changed; the caller notifies. */\n private setState(id: string, state: DocumentRefetchState): boolean {\n const current = this.getState(id);\n if (\n current.isRefetching === state.isRefetching &&\n current.error === state.error\n ) {\n return false;\n }\n if (!state.isRefetching && state.error === undefined) {\n this.states.delete(id);\n } else {\n this.states.set(id, Object.freeze({ ...state }));\n }\n return true;\n }\n}\n","import type {\n DocumentChangeType,\n DuplicateManifestError,\n DuplicateModuleError,\n} from \"@powerhousedao/reactor\";\n\n/**\n * The handful of runtime values the browser-safe surface needs from\n * `@powerhousedao/reactor`, mirrored so that nothing on that surface has to\n * import the package as a value.\n *\n * `@powerhousedao/reactor` has a single entry point, and it reaches `pg`\n * (`dns`/`fs`/`net`/`tls`), `@electric-sql/pglite` and `node:worker_threads`. A\n * browser bundler must resolve all of those the moment any module imports a\n * VALUE from the package, which is what previously forced every consuming app\n * to alias the reactor away in its own build config. Type imports are erased\n * before the bundler ever sees them, so types keep coming from the reactor and\n * only these values are mirrored.\n *\n * Drift is a compile error rather than a runtime surprise - see the assertions\n * below.\n */\n\nconst DOCUMENT_CHANGE_TYPE_VALUES = {\n Created: \"created\",\n Deleted: \"deleted\",\n Updated: \"updated\",\n ParentAdded: \"parent_added\",\n ParentRemoved: \"parent_removed\",\n ChildAdded: \"child_added\",\n ChildRemoved: \"child_removed\",\n} as const satisfies Record<string, `${DocumentChangeType}`>;\n\n/**\n * `satisfies` above rejects a mirrored value the enum does not declare. This\n * rejects the other direction: a member the reactor added and this mirror does\n * not cover.\n */\ntype MissingDocumentChangeTypeMembers = Exclude<\n `${DocumentChangeType}`,\n (typeof DOCUMENT_CHANGE_TYPE_VALUES)[keyof typeof DOCUMENT_CHANGE_TYPE_VALUES]\n>;\ntype AssertNoMissingDocumentChangeTypeMembers = [\n MissingDocumentChangeTypeMembers,\n] extends [never]\n ? true\n : [\n \"DOCUMENT_CHANGE_TYPE is missing DocumentChangeType members\",\n MissingDocumentChangeTypeMembers,\n ];\nconst documentChangeTypeMirrorIsComplete: AssertNoMissingDocumentChangeTypeMembers = true;\nvoid documentChangeTypeMirrorIsComplete;\n\n/**\n * The reactor's `DocumentChangeType` members, typed as the enum so they can be\n * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a\n * TypeScript string enum is nominal, so no string literal is assignable to it\n * without one - and the two checks above are what make it safe.\n */\nexport const DOCUMENT_CHANGE_TYPE = DOCUMENT_CHANGE_TYPE_VALUES as unknown as {\n readonly [K in keyof typeof DOCUMENT_CHANGE_TYPE_VALUES]: DocumentChangeType;\n};\n\n/**\n * Structural equivalents of the reactor error classes' own static `isError`\n * guards. Those guards match on `error.name` rather than the prototype chain\n * (`packages/reactor/src/registry/errors.ts`), so re-implementing them here is\n * behaviour-preserving and does not need the class at runtime.\n */\nexport function isDuplicateModuleError(\n error: unknown,\n): error is DuplicateModuleError {\n return Error.isError(error) && error.name === \"DuplicateModuleError\";\n}\n\nexport function isDuplicateManifestError(\n error: unknown,\n): error is DuplicateManifestError {\n return Error.isError(error) && error.name === \"DuplicateManifestError\";\n}\n","import type { DocumentChangeEvent, PagedResults } from \"@powerhousedao/reactor\";\nimport { DocumentRefetcher } from \"./document-refetcher.js\";\nimport { DOCUMENT_CHANGE_TYPE } from \"./reactor-interop.js\";\nimport type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n DocumentRefetchState,\n FulfilledPromise,\n IDocumentCache,\n IOperationCache,\n OperationsCacheEntry,\n PromiseState,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.js\";\nimport type { IReactorBrowserClient } from \"./types/reactor-browser-client.js\";\n\nexport function addPromiseState<T>(promise: Promise<T>): PromiseWithState<T> {\n if (\"status\" in promise) {\n return promise as PromiseWithState<T>;\n }\n\n const promiseWithState = promise as PromiseWithState<T>;\n promiseWithState.status = \"pending\";\n promiseWithState.then(\n (value) => {\n promiseWithState.status = \"fulfilled\";\n (promiseWithState as FulfilledPromise<T>).value = value;\n },\n (reason) => {\n promiseWithState.status = \"rejected\";\n (promiseWithState as RejectedPromise<T>).reason = reason;\n // Re-throw to preserve unhandled rejection behavior\n // This allows React's error boundaries to catch the error\n throw reason;\n },\n );\n\n return promiseWithState;\n}\n\nexport function readPromiseState<T>(\n promise: Promise<T> | PromiseWithState<T>,\n): PromiseState<T> {\n return \"status\" in promise ? promise : { status: \"pending\" };\n}\n\n/**\n * Resolves an array of document promises using `Promise.allSettled`,\n * returning only the fulfilled values. A single missing/rejected\n * document does not poison the whole batch. Rejected entries are\n * logged at warn level so developers can see dangling references.\n */\nfunction fulfilledOnly(promises: Promise<PHDocument>[]): Promise<PHDocument[]> {\n return Promise.allSettled(promises).then((results) => {\n const documents: PHDocument[] = [];\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n documents.push(result.value);\n } else {\n console.warn(\n \"[DocumentCache] Skipped unavailable document:\",\n result.reason,\n );\n }\n }\n return documents;\n });\n}\n\n/** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */\nexport const IDLE_OPERATIONS_ENTRY: OperationsCacheEntry = Object.freeze({\n status: \"idle\",\n operations: Object.freeze([]) as readonly Operation[],\n error: undefined,\n hasNextPage: false,\n totalCount: undefined,\n});\n\n/** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */\nexport function isOperationCache(cache: unknown): cache is IOperationCache {\n if (typeof cache !== \"object\" || cache === null) return false;\n const candidate = cache as Partial<IOperationCache>;\n return (\n typeof candidate.getOperationsState === \"function\" &&\n typeof candidate.loadOperations === \"function\" &&\n typeof candidate.loadMoreOperations === \"function\" &&\n typeof candidate.invalidateOperations === \"function\" &&\n typeof candidate.subscribeOperations === \"function\"\n );\n}\n\n/**\n * Page size used to refresh a scope whose request record has gone missing.\n * A loaded scope always has one, so this is a floor rather than a default.\n */\nconst FALLBACK_REFRESH_LIMIT = 100;\n\n/**\n * The highest revision among the operations loaded so far, or -1 for none.\n * Pages arrive oldest first, so this is normally the last entry; it is\n * computed rather than assumed because nothing in the cache enforces that.\n */\nfunction highestOperationIndex(operations: readonly Operation[]): number {\n let highest = -1;\n for (const operation of operations) {\n if (operation.index > highest) highest = operation.index;\n }\n return highest;\n}\n\n/** Bookkeeping for one document scope that is not part of its snapshot. */\ntype OperationsRequest = {\n /** Aborts the request in flight, or marks a settled one as superseded. */\n controller: AbortController;\n /** The cursor for the page after the last loaded one; `undefined` when there is none. */\n nextCursor: string | undefined;\n /** The page size the scope was loaded with, reused for every subsequent page. */\n limit: number;\n};\n\n/**\n * Document cache implementation that uses the new ReactorClient API.\n *\n * This cache subscribes to document change events via IReactorBrowserClient.subscribe()\n * and automatically updates the cache when documents are created, updated, or deleted.\n * It also holds paginated operation history per document scope (see `IOperationCache`),\n * which is dropped for a document whenever a change event for it arrives.\n */\nexport class DocumentCache implements IDocumentCache, IOperationCache {\n private documents = new Map<string, PromiseWithState<PHDocument>>();\n private batchPromises = new Map<\n string,\n { promises: Promise<PHDocument>[]; promise: Promise<PHDocument[]> }\n >();\n private listeners = new Map<string, (() => void)[]>();\n\n private refetcher = new DocumentRefetcher({\n documents: this.documents,\n fetch: (id) => this.client.get(id),\n notify: (id) => this.notifyListeners(id),\n onFetched: (id, document) => {\n if (document.header.id !== id) {\n this.recordAlias(document.header.id, id);\n }\n },\n });\n\n /**\n * Cache keys that fetched a document under a name other than its id --\n * slugs, which `client.get` resolves. Change events dispatch by `header.id`,\n * so without this mapping a slug-keyed entry (and its listeners) would never\n * see an update: keyed by the id the events carry, valued by the other keys\n * the same document is cached under.\n */\n private aliasKeys = new Map<string, Set<string>>();\n\n /** Operations by document id, then scope. Entries are replaced, never mutated. */\n private operationEntries = new Map<\n string,\n Map<string, OperationsCacheEntry>\n >();\n /** In-flight controllers and the next page's cursor/limit, by document id then scope. */\n private operationRequests = new Map<string, Map<string, OperationsRequest>>();\n private operationListeners = new Map<string, (() => void)[]>();\n\n private unsubscribe: (() => void) | null = null;\n\n constructor(private client: IReactorBrowserClient) {\n this.unsubscribe = client.subscribe({}, (event: DocumentChangeEvent) => {\n this.handleDocumentChange(event);\n });\n }\n\n private handleDocumentChange(event: DocumentChangeEvent): void {\n if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {\n const documentId = event.context?.childId;\n if (documentId) {\n // Read the alias keys before `handleDocumentDeleted` clears them, so a\n // slug-keyed operations entry is invalidated too.\n const keys = this.cacheKeysFor(documentId);\n this.handleDocumentDeleted(documentId);\n for (const key of keys) {\n this.invalidateOperations(key);\n }\n }\n } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) {\n for (const doc of event.documents) {\n const keys = this.cacheKeysFor(doc.header.id);\n this.handleDocumentUpdated(doc.header.id).catch(console.warn);\n for (const key of keys) {\n this.refreshOperations(key);\n }\n }\n }\n }\n\n private handleDocumentDeleted(documentId: string): void {\n for (const key of this.cacheKeysFor(documentId)) {\n const listeners = this.listeners.get(key);\n this.documents.delete(key);\n this.refetcher.forget(key);\n this.invalidateBatchesContaining(key);\n if (listeners) {\n listeners.forEach((listener) => listener());\n }\n this.listeners.delete(key);\n }\n this.aliasKeys.delete(documentId);\n }\n\n // The refetch notifies listeners itself once it settles.\n private async handleDocumentUpdated(documentId: string): Promise<void> {\n const refetches = this.cacheKeysFor(documentId)\n .filter((key) => this.documents.has(key))\n .map((key) => this.get(key, true));\n await Promise.all(refetches);\n }\n\n private notifyListeners(key: string): void {\n for (const listener of this.listeners.get(key) ?? []) {\n listener();\n }\n }\n\n /** The id an event dispatches by, plus every alias the document is cached under. */\n private cacheKeysFor(documentId: string): string[] {\n return [documentId, ...(this.aliasKeys.get(documentId) ?? [])];\n }\n\n /** Records that `key` cached the document change events know as `header.id`. */\n private recordAlias(documentId: string, key: string): void {\n const keys = this.aliasKeys.get(documentId) ?? new Set<string>();\n keys.add(key);\n this.aliasKeys.set(documentId, keys);\n }\n\n private invalidateBatchesContaining(documentId: string): void {\n for (const key of this.batchPromises.keys()) {\n if (key.split(\",\").includes(documentId)) {\n this.batchPromises.delete(key);\n }\n }\n }\n\n get(id: string, refetch?: boolean): Promise<PHDocument> {\n const currentData = this.documents.get(id);\n if (currentData && !refetch) {\n return currentData;\n }\n // A loaded document stays served while it refetches; a pending first load\n // may predate the change, so it gets a refetch queued behind it.\n if (currentData && currentData.status !== \"rejected\") {\n return this.refetcher.refetch(id);\n }\n\n this.refetcher.forget(id);\n const documentPromise = this.client.get(id);\n documentPromise.then(\n (doc) => {\n if (doc.header.id !== id) {\n this.recordAlias(doc.header.id, id);\n }\n },\n // Rejections are surfaced by the stored promise; this chain only learns aliases.\n () => undefined,\n );\n this.documents.set(id, addPromiseState(documentPromise));\n return documentPromise;\n }\n\n getRefetchState(id: string): DocumentRefetchState {\n return this.refetcher.getState(id);\n }\n\n getBatch(ids: string[]): Promise<PHDocument[]> {\n const key = ids.join(\",\");\n const cached = this.batchPromises.get(key);\n\n const hasDeletedDocuments = ids.some((id) => !this.documents.has(id));\n const currentPromises = ids.map((id) => this.get(id));\n\n if (hasDeletedDocuments) {\n const batchPromise = fulfilledOnly(currentPromises);\n this.batchPromises.set(key, {\n promises: currentPromises,\n promise: batchPromise,\n });\n return batchPromise;\n }\n\n if (cached) {\n const samePromises = currentPromises.every(\n (p, i) => p === cached.promises[i],\n );\n if (samePromises) {\n return cached.promise;\n }\n }\n\n const states = currentPromises.map((p) =>\n readPromiseState(p as PromiseWithState<PHDocument>),\n );\n const allSettled = states.every((s) => s.status !== \"pending\");\n\n if (allSettled) {\n const values = states\n .filter(\n (s): s is { status: \"fulfilled\"; value: PHDocument } =>\n s.status === \"fulfilled\",\n )\n .map((s) => s.value);\n const batchPromise = Promise.resolve(values) as PromiseWithState<\n PHDocument[]\n >;\n batchPromise.status = \"fulfilled\";\n (batchPromise as FulfilledPromise<PHDocument[]>).value = values;\n\n this.batchPromises.set(key, {\n promises: currentPromises,\n promise: batchPromise,\n });\n return batchPromise;\n }\n\n if (cached) {\n return cached.promise;\n }\n\n const batchPromise = fulfilledOnly(currentPromises);\n this.batchPromises.set(key, {\n promises: currentPromises,\n promise: batchPromise,\n });\n return batchPromise;\n }\n\n subscribe(id: string | string[], callback: () => void): () => void {\n const ids = Array.isArray(id) ? id : [id];\n for (const docId of ids) {\n const listeners = this.listeners.get(docId) ?? [];\n this.listeners.set(docId, [...listeners, callback]);\n }\n return () => {\n for (const docId of ids) {\n const listeners = this.listeners.get(docId) ?? [];\n this.listeners.set(\n docId,\n listeners.filter((listener) => listener !== callback),\n );\n }\n };\n }\n\n getOperationsState(documentId: string, scope: string): OperationsCacheEntry {\n return (\n this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY\n );\n }\n\n loadOperations(documentId: string, scope: string, limit: number): void {\n const current = this.getOperationsState(documentId, scope);\n if (current.status !== \"idle\") {\n return;\n }\n const controller = new AbortController();\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor: undefined,\n limit,\n });\n this.setOperationsEntry(documentId, scope, {\n ...current,\n status: \"pending\",\n });\n this.settleOperationsPage(\n documentId,\n scope,\n this.client.getOperations(\n documentId,\n { scopes: [scope] },\n undefined,\n { cursor: \"\", limit },\n controller.signal,\n ),\n controller,\n limit,\n );\n }\n\n loadMoreOperations(documentId: string, scope: string): void {\n const current = this.getOperationsState(documentId, scope);\n const request = this.operationRequests.get(documentId)?.get(scope);\n if (\n current.status !== \"success\" ||\n !current.hasNextPage ||\n !request?.nextCursor\n ) {\n return;\n }\n // Each page gets its own controller, so invalidation can abort whichever\n // page is currently in flight.\n const controller = new AbortController();\n const { nextCursor, limit } = request;\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor,\n limit,\n });\n this.setOperationsEntry(documentId, scope, {\n ...current,\n status: \"pending\",\n });\n this.settleOperationsPage(\n documentId,\n scope,\n this.client.getOperations(\n documentId,\n { scopes: [scope] },\n undefined,\n { cursor: nextCursor, limit },\n controller.signal,\n ),\n controller,\n limit,\n );\n }\n\n /**\n * Bring a document's cached scopes up to date after it changed, without\n * throwing away what is already loaded.\n *\n * The operation stream is append-only: an update adds operations at higher\n * revisions and never rewrites the ones below, so history already paged in\n * is still correct. Dropping it meant a panel showing a fully loaded\n * document re-walked every page on each edit -- the cost of which grows\n * with the document, exactly where it hurts most. Each scope instead asks\n * only for what comes after the newest revision it holds, using the\n * `sinceRevision` filter, and appends the answer.\n *\n * A scope that has not finished paging is dropped as before: it has no\n * meaningful \"newest revision\" to resume from, since asking for everything\n * past the newest row it happens to hold would skip the pages between that\n * row and the end of the stream.\n */\n private refreshOperations(documentId: string): void {\n const scopes = this.operationEntries.get(documentId);\n if (!scopes) return;\n\n for (const [scope, entry] of [...scopes.entries()]) {\n if (entry.status !== \"success\" || entry.hasNextPage) {\n this.invalidateOperationsScope(documentId, scope);\n continue;\n }\n\n const previous = this.operationRequests.get(documentId)?.get(scope);\n const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;\n // Marks the settled page superseded, so a late arrival cannot append\n // on top of the refresh.\n previous?.controller.abort();\n\n const controller = new AbortController();\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor: undefined,\n limit,\n });\n // Pending, but the operations stay in the entry: consumers keep\n // rendering the history they have instead of flashing empty while the\n // tail is fetched.\n this.setOperationsEntry(documentId, scope, {\n ...entry,\n status: \"pending\",\n });\n this.settleOperationsPage(\n documentId,\n scope,\n this.client.getOperations(\n documentId,\n { scopes: [scope] },\n { sinceRevision: highestOperationIndex(entry.operations) + 1 },\n { cursor: \"\", limit },\n controller.signal,\n ),\n controller,\n limit,\n );\n }\n }\n\n /** Drops one scope of a document, aborting its request if one is in flight. */\n private invalidateOperationsScope(documentId: string, scope: string): void {\n const requests = this.operationRequests.get(documentId);\n const request = requests?.get(scope);\n if (request && requests) {\n request.controller.abort();\n requests.delete(scope);\n if (requests.size === 0) {\n this.operationRequests.delete(documentId);\n }\n }\n const scopes = this.operationEntries.get(documentId);\n if (scopes?.delete(scope)) {\n if (scopes.size === 0) {\n this.operationEntries.delete(documentId);\n }\n this.notifyOperationListeners(documentId);\n }\n }\n\n invalidateOperations(documentId: string): void {\n const requests = this.operationRequests.get(documentId);\n if (requests) {\n for (const request of requests.values()) {\n request.controller.abort();\n }\n this.operationRequests.delete(documentId);\n }\n if (this.operationEntries.delete(documentId)) {\n this.notifyOperationListeners(documentId);\n }\n }\n\n subscribeOperations(documentId: string, callback: () => void): () => void {\n const listeners = this.operationListeners.get(documentId) ?? [];\n this.operationListeners.set(documentId, [...listeners, callback]);\n return () => {\n const current = this.operationListeners.get(documentId) ?? [];\n this.operationListeners.set(\n documentId,\n current.filter((listener) => listener !== callback),\n );\n };\n }\n\n private settleOperationsPage(\n documentId: string,\n scope: string,\n page: Promise<PagedResults<Operation>>,\n controller: AbortController,\n limit: number,\n ): void {\n page.then(\n (result) => {\n if (controller.signal.aborted) return;\n const current = this.getOperationsState(documentId, scope);\n this.setOperationsRequest(documentId, scope, {\n controller,\n nextCursor: result.nextCursor,\n limit,\n });\n this.setOperationsEntry(documentId, scope, {\n status: \"success\",\n operations: [...current.operations, ...result.results],\n error: undefined,\n hasNextPage: !!result.nextCursor,\n totalCount: result.totalCount,\n });\n },\n (reason: unknown) => {\n if (controller.signal.aborted) return;\n const current = this.getOperationsState(documentId, scope);\n this.setOperationsEntry(documentId, scope, {\n ...current,\n status: \"error\",\n error: reason,\n });\n },\n );\n }\n\n private setOperationsEntry(\n documentId: string,\n scope: string,\n entry: OperationsCacheEntry,\n ): void {\n const scopes =\n this.operationEntries.get(documentId) ??\n new Map<string, OperationsCacheEntry>();\n scopes.set(scope, entry);\n this.operationEntries.set(documentId, scopes);\n this.notifyOperationListeners(documentId);\n }\n\n private setOperationsRequest(\n documentId: string,\n scope: string,\n request: OperationsRequest,\n ): void {\n const scopes =\n this.operationRequests.get(documentId) ??\n new Map<string, OperationsRequest>();\n scopes.set(scope, request);\n this.operationRequests.set(documentId, scopes);\n }\n\n private notifyOperationListeners(documentId: string): void {\n for (const listener of this.operationListeners.get(documentId) ?? []) {\n listener();\n }\n }\n\n /**\n * Disposes of the cache and unsubscribes from document change events.\n */\n dispose(): void {\n if (this.unsubscribe) {\n this.unsubscribe();\n this.unsubscribe = null;\n }\n for (const requests of this.operationRequests.values()) {\n for (const request of requests.values()) {\n request.controller.abort();\n }\n }\n this.operationRequests.clear();\n this.operationEntries.clear();\n this.refetcher.clear();\n this.operationListeners.clear();\n }\n}\n\nexport { IDLE_REFETCH_STATE } from \"./document-refetcher.js\";\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n use,\n useCallback,\n useEffect,\n useReducer,\n useSyncExternalStore,\n} from \"react\";\nimport { IDLE_REFETCH_STATE, readPromiseState } from \"../document-cache.js\";\nimport type {\n DocumentRefetchState,\n IDocumentCache,\n} from \"../types/documents.js\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst documentEventFunctions = makePHEventFunctions(\"documentCache\");\n\n/** Returns all documents in the reactor. */\nexport const useDocumentCache: UsePHGlobalValue<IDocumentCache> =\n documentEventFunctions.useValue;\n\n/** Sets all of the documents in the reactor. */\nexport const setDocumentCache: SetPHGlobalValue<IDocumentCache> =\n documentEventFunctions.setValue;\n\n/** Adds an event handler for all of the documents in the reactor. */\nexport const addDocumentCacheEventHandler =\n documentEventFunctions.addEventHandler;\n\n/**\n * Reads the state of a document promise and converts it to a query state object.\n * @param promise - The document promise to read\n * @returns An object containing the status, data, error, and isPending flag\n */\nfunction getDocumentQueryState(promise: Promise<PHDocument>) {\n const state = readPromiseState(promise);\n switch (state.status) {\n case \"pending\":\n return {\n status: \"pending\",\n isPending: true,\n error: undefined,\n data: undefined,\n } as const;\n case \"fulfilled\":\n return {\n status: \"success\",\n isPending: false,\n error: undefined,\n data: state.value,\n } as const;\n case \"rejected\":\n return {\n status: \"error\",\n isPending: false,\n error: state.reason,\n data: undefined,\n } as const;\n }\n}\n\n/**\n * Retrieves a document from the reactor and subscribes to changes using React Suspense.\n * This hook will suspend rendering while the document is loading.\n * @param id - The document ID to retrieve, or null/undefined to skip retrieval\n * @returns The document if found, or undefined if id is null/undefined\n */\nexport function useDocument(id: string | null | undefined) {\n const documentCache = useDocumentCache();\n const document = useSyncExternalStore(\n (cb) => (id && documentCache ? documentCache.subscribe(id, cb) : () => {}),\n () => (id ? documentCache?.get(id) : undefined),\n );\n return document ? use(document) : undefined;\n}\n\n/**\n * Retrieves a document from the reactor and subscribes to changes without\n * suspending or throwing. Use this when the ID might be stale (e.g., a\n * previously selected node that has since been deleted) and the consumer\n * wants to render a placeholder instead of crashing.\n *\n * Unlike {@link useGetDocumentAsync}, this hook subscribes to cache\n * updates, so the returned state stays in sync with reactor changes.\n *\n * @param id - The document ID to retrieve, or null/undefined to skip retrieval\n * @returns An object containing:\n * - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n * - data: The document if successfully loaded\n * - isPending: Whether the document is currently loading\n * - error: Any error that occurred during loading (e.g., document not found)\n * - reload: Function to force a refetch, or undefined when no id is supplied\n * - isRefetching: A loaded document is being refetched; `data` is the loaded one\n * - refetchError: The last refetch failure that kept the loaded document\n */\nexport function useDocumentSafe(id: string | null | undefined) {\n const documentCache = useDocumentCache();\n const subscribe = (cb: () => void) =>\n id && documentCache ? documentCache.subscribe(id, cb) : () => {};\n const promise = useSyncExternalStore(subscribe, () =>\n id ? documentCache?.get(id) : undefined,\n );\n const refetch = useSyncExternalStore(subscribe, () =>\n readRefetchState(documentCache, id),\n );\n\n // The cache notifies subscribers only when a document CHANGES (its stored\n // promise is replaced); the INITIAL fetch settles without a notification,\n // and since the snapshot above is the promise itself - same identity before\n // and after settling - nothing re-renders this hook past \"pending\" on a\n // page that is otherwise quiet. Watch the pending promise and bump local\n // state when it settles, so the state below is re-read. The promise is\n // captured at render time: if it settles before the effect runs, `.then`\n // still fires the bump on the next microtask, so the race loses nothing.\n // `useDocument` needs none of this - React itself resumes a component\n // suspended on `use(promise)`.\n const [, bumpOnSettle] = useReducer((count: number) => count + 1, 0);\n const pendingPromise =\n promise && readPromiseState(promise).status === \"pending\" ? promise : null;\n useEffect(() => {\n if (!pendingPromise) return;\n let active = true;\n const settled = () => {\n if (active) bumpOnSettle();\n };\n pendingPromise.then(settled, settled);\n return () => {\n active = false;\n };\n }, [pendingPromise]);\n\n if (!promise || !documentCache || !id) {\n return {\n status: \"initial\",\n isPending: false,\n error: undefined,\n data: undefined,\n reload: undefined,\n isRefetching: false,\n refetchError: undefined,\n } as const;\n }\n\n const state = getDocumentQueryState(promise);\n return {\n ...state,\n reload: () => documentCache.get(id, true),\n isRefetching: refetch.isRefetching,\n refetchError: refetch.error,\n } as const;\n}\n\nfunction readRefetchState(\n documentCache: IDocumentCache | undefined,\n id: string | null | undefined,\n): DocumentRefetchState {\n return (id && documentCache?.getRefetchState?.(id)) || IDLE_REFETCH_STATE;\n}\n\n/**\n * Retrieves multiple documents from the reactor using React Suspense.\n * This hook will suspend rendering while any of the documents are loading.\n *\n * Uses getBatch from the document cache which handles promise caching internally,\n * ensuring stable references for useSyncExternalStore.\n *\n * @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval\n * @returns An array of documents if found, or empty array if ids is null/undefined\n */\nexport function useDocuments(ids: string[] | null | undefined) {\n const documentCache = useDocumentCache();\n\n const documents = useSyncExternalStore(\n (cb) =>\n ids?.length && documentCache\n ? documentCache.subscribe(ids, cb)\n : () => {},\n () =>\n ids?.length && documentCache ? documentCache.getBatch(ids) : undefined,\n );\n\n return documents ? use(documents) : [];\n}\n\n/**\n * Returns a function to retrieve a document from the cache.\n * The returned function fetches and returns a document by ID.\n * @returns A function that takes a document ID and returns a Promise of the document\n */\nexport function useGetDocument() {\n const documentCache = useDocumentCache();\n\n return useCallback(\n (id: string) => {\n if (!documentCache) {\n return Promise.reject(new Error(\"Document cache not initialized\"));\n }\n return documentCache.get(id);\n },\n [documentCache],\n );\n}\n\n/**\n * Returns a function to retrieve multiple documents from the cache.\n * The returned function fetches and returns documents by their IDs.\n * @returns A function that takes an array of document IDs and returns a Promise of the documents\n */\nexport function useGetDocuments() {\n const documentCache = useDocumentCache();\n\n return useCallback(\n (ids: string[]) => {\n if (!documentCache) {\n return Promise.reject(new Error(\"Document cache not initialized\"));\n }\n return documentCache.getBatch(ids);\n },\n [documentCache],\n );\n}\n\n/**\n * Retrieves a document from the reactor without suspending rendering.\n * Returns the current state of the document loading operation.\n * @param id - The document ID to retrieve, or null/undefined to skip retrieval\n * @returns An object containing:\n * - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n * - data: The document if successfully loaded\n * - isPending: Boolean indicating if the document is currently loading\n * - error: Any error that occurred during loading\n * - reload: Function to force reload the document from cache\n * - isRefetching: A loaded document is being refetched; `data` is the loaded one\n * - refetchError: The last refetch failure that kept the loaded document\n */\nexport function useGetDocumentAsync(id: string | null | undefined) {\n const documentCache = useDocumentCache();\n if (!id || !documentCache) {\n return {\n status: \"initial\",\n data: undefined,\n isPending: false,\n error: undefined,\n reload: undefined,\n isRefetching: false,\n refetchError: undefined,\n } as const;\n }\n\n const promise = documentCache.get(id);\n const state = getDocumentQueryState(promise);\n const refetch = readRefetchState(documentCache, id);\n\n return {\n ...state,\n reload: () => documentCache.get(id, true),\n isRefetching: refetch.isRefetching,\n refetchError: refetch.error,\n } as const;\n}\n","import type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport { dispatchActions } from \"../actions/dispatch.js\";\n\n/**\n * Returns a dispatch function for dispatching actions to a document.\n * Used internally by other hooks to provide action dispatching capabilities.\n * @param document - The document to dispatch actions to.\n * @returns A tuple containing the document and a dispatch function.\n */\nexport type DispatchFn<TAction> = (\n actionOrActions: TAction[] | TAction | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n) => void;\n\nexport type UseDispatchResult<TDocument, TAction> = readonly [\n TDocument | undefined,\n DispatchFn<TAction>,\n];\n\nexport function useDispatch<TDocument = PHDocument, TAction = Action>(\n document: TDocument | undefined,\n): UseDispatchResult<TDocument, TAction> {\n /**\n * Dispatches actions to the document.\n * @param actionOrActions - The action or actions to dispatch.\n * @param onErrors - Callback invoked with any errors that occurred during action execution.\n */\n function dispatch(\n actionOrActions: TAction[] | TAction | undefined,\n onErrors?: (errors: Error[]) => void,\n onSuccess?: (result: PHDocument) => void,\n ) {\n dispatchActions(actionOrActions, document, onErrors, onSuccess).catch(\n (error: unknown) => {\n logger.error(\"Failed to dispatch actions: @error\", error);\n },\n );\n }\n return [document, dispatch] as const;\n}\n","import type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { useDispatch, type UseDispatchResult } from \"./dispatch.js\";\nimport { useDocument, useDocuments } from \"./document-cache.js\";\n\n/** Returns a document by id. */\nexport function useDocumentById(\n id: string | null | undefined,\n): UseDispatchResult<PHDocument, Action> {\n const document = useDocument(id);\n const [, dispatch] = useDispatch<PHDocument, Action>(document);\n return [document, dispatch] as const;\n}\n\n/** Returns documents by ids. */\nexport function useDocumentsByIds(ids: string[] | null | undefined) {\n return useDocuments(ids);\n}\n"],"mappings":";;;;AASA,eAAsB,aACpB,UACA,iBACA;AACA,KAAI,CAAC,SACH,OAAM,IAAI,MAAM,uBAAuB;AAEzC,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BACd,IACuC;CACvC,MAAM,WAAW,YAAY,GAAG;CAChC,MAAM,GAAG,YAAY,YAAgC,SAAS;AAC9D,QAAO,CAAC,UAAU,SAAS;;;AAI7B,SAAgB,kBAAkB,KAAkC;AAClE,QAAO,aAAa,IAAI"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { b as isDuplicateModuleError, n as useDocumentsByIds, r as useDispatch, y as isDuplicateManifestError } from "./document-by-id-
|
|
1
|
+
import { b as isDuplicateModuleError, n as useDocumentsByIds, r as useDispatch, y as isDuplicateManifestError } from "./document-by-id-DgdUGMVm.js";
|
|
2
2
|
import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
|
|
3
|
+
import { isDerivedDocumentId } from "@powerhousedao/shared/document-model";
|
|
3
4
|
import { useSyncExternalStore } from "react";
|
|
4
5
|
import slug from "slug";
|
|
5
6
|
//#region src/graphql-client/auth.ts
|
|
@@ -69,6 +70,7 @@ var NoSelectedDocumentError = class extends Error {
|
|
|
69
70
|
};
|
|
70
71
|
//#endregion
|
|
71
72
|
//#region src/utils/url.ts
|
|
73
|
+
const DERIVED_ID_LENGTH = 43;
|
|
72
74
|
function resolveUrlPathname(path) {
|
|
73
75
|
return new URL(path.replace(/^\/+/, ""), window.location.origin + (window.ph?.basePath ?? "/")).pathname;
|
|
74
76
|
}
|
|
@@ -82,12 +84,14 @@ function makeDriveUrlComponent(drive) {
|
|
|
82
84
|
if (!drive) return "";
|
|
83
85
|
return `/d/${slug(drive.header.slug)}`;
|
|
84
86
|
}
|
|
85
|
-
/**
|
|
87
|
+
/**
|
|
88
|
+
* Makes a URL component for a node: `<slugged name>-<id>`. The id is kept
|
|
89
|
+
* verbatim, since a v2-required id is case-sensitive base64url.
|
|
90
|
+
*/
|
|
86
91
|
function makeNodeSlug(node) {
|
|
87
92
|
if (!node) return "";
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
return slug(`${nodeName}-${node.id}`);
|
|
93
|
+
const nameSlug = node.name ? slug(node.name) : "";
|
|
94
|
+
return nameSlug ? `${nameSlug}-${node.id}` : node.id;
|
|
91
95
|
}
|
|
92
96
|
/** Extracts the node slug from a path.
|
|
93
97
|
*
|
|
@@ -102,8 +106,16 @@ function findUuid(input) {
|
|
|
102
106
|
if (!input) return void 0;
|
|
103
107
|
return /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/.exec(input)?.[0];
|
|
104
108
|
}
|
|
109
|
+
/** The v2-required document id a slug ends with, if any. */
|
|
110
|
+
function findDerivedId(input) {
|
|
111
|
+
if (!input || input.length < DERIVED_ID_LENGTH) return void 0;
|
|
112
|
+
const start = input.length - DERIVED_ID_LENGTH;
|
|
113
|
+
if (start > 0 && input[start - 1] !== "-") return void 0;
|
|
114
|
+
const candidate = input.slice(start);
|
|
115
|
+
return isDerivedDocumentId(candidate) ? candidate : void 0;
|
|
116
|
+
}
|
|
105
117
|
function extractNodeIdFromSlug(nodeSlug) {
|
|
106
|
-
return findUuid(nodeSlug);
|
|
118
|
+
return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);
|
|
107
119
|
}
|
|
108
120
|
function extractNodeIdFromPath(path) {
|
|
109
121
|
return extractNodeIdFromSlug(extractNodeSlugFromPath(path));
|
|
@@ -117,7 +129,7 @@ function extractDriveSlugFromPath(path) {
|
|
|
117
129
|
return /^\/d\/([^/]+)/.exec(currentPath)?.[1] ?? "";
|
|
118
130
|
}
|
|
119
131
|
function extractDriveIdFromSlug(driveSlug) {
|
|
120
|
-
return findUuid(driveSlug);
|
|
132
|
+
return findUuid(driveSlug) ?? findDerivedId(driveSlug);
|
|
121
133
|
}
|
|
122
134
|
function extractDriveIdFromPath(path) {
|
|
123
135
|
return extractDriveIdFromSlug(extractDriveSlugFromPath(path));
|
|
@@ -414,6 +426,6 @@ function useDocumentModelModuleById(id, version) {
|
|
|
414
426
|
return latestModule;
|
|
415
427
|
}
|
|
416
428
|
//#endregion
|
|
417
|
-
export { createUrlWithPreservedParams as A,
|
|
429
|
+
export { createUrlWithPreservedParams as A, makeDriveUrlComponent as B, addResetSelectedNodeEventHandler as C, addDrivesEventHandler as D, setSelectedNode as E, extractNodeIdFromSlug as F, NoSelectedDocumentError as G, resolveUrlPathname as H, extractNodeSlugFromPath as I, makeAuthMiddleware as J, UnsupportedDocumentTypeError as K, findDerivedId as L, extractDriveIdFromSlug as M, extractDriveSlugFromPath as N, setDrives as O, extractNodeIdFromPath as P, findUuid as R, useSelectedDriveSafe as S, addSetSelectedNodeOnPopStateEventHandler as T, DocumentModelNotFoundError as U, makeNodeSlug as V, DocumentTypeMismatchError as W, addSetSelectedDriveOnPopStateEventHandler as _, useVetraPackageManager as a, useSelectedDrive as b, useDocumentTypesInSelectedDrive as c, useFolderNodesInSelectedDrive as d, useNodesInSelectedDrive as f, addSelectedDriveIdEventHandler as g, sortNodesByName as h, setVetraPackageManager as i, extractDriveIdFromPath as j, useDrives as k, useDocumentsInSelectedDrive as l, isFolderNodeKind as m, useDocumentModelModules as n, useVetraPackages as o, isFileNodeKind as p, ambientRenownTokenProvider as q, addVetraPackageManagerEventHandler as r, useSelectedNode as s, useDocumentModelModuleById as t, useFileNodesInSelectedDrive as u, setSelectedDrive as v, addSelectedNodeIdEventHandler as w, useSelectedDriveId as x, setSelectedDriveId as y, getPathWithoutBase as z };
|
|
418
430
|
|
|
419
|
-
//# sourceMappingURL=document-model-modules-
|
|
431
|
+
//# sourceMappingURL=document-model-modules-D1ZEoGjN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-model-modules-D1ZEoGjN.js","names":[],"sources":["../src/graphql-client/auth.ts","../src/errors.ts","../src/utils/url.ts","../src/hooks/drives.ts","../src/hooks/set-selected-node.ts","../src/hooks/selected-drive.ts","../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/vetra-packages.ts","../src/hooks/document-model-modules.ts"],"sourcesContent":["import type { SdkFunctionWrapper } from \"../graphql/gen/schema.js\";\n\n/**\n * Resolves the bearer token to send with a request.\n *\n * Returning `undefined` (or an empty string) means \"send this request\n * anonymously\": open Switchboards must keep serving reads to logged-out users.\n */\nexport type BearerTokenProvider = () => Promise<string | undefined>;\n\n/** Lifetime requested for an ambient Renown token, in seconds. */\nconst ambientTokenExpiresInSeconds = 600;\n\n/**\n * The default token provider: the token of the currently logged-in Renown user.\n *\n * It is deliberately resolved from `window.ph` on every call rather than\n * captured at construction time, so a client built before login starts sending\n * the token as soon as there is one.\n *\n * The token is requested WITHOUT an `aud` claim - the Switchboard verifier\n * rejects tokens that carry an audience.\n */\nexport async function ambientRenownTokenProvider(): Promise<\n string | undefined\n> {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n\n const renown = window.ph?.renown;\n if (!renown?.user) {\n return undefined;\n }\n\n return renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });\n}\n\n/**\n * Builds the SDK middleware that authenticates every request.\n *\n * The token is resolved per request and never cached, so a login, a logout or\n * an expiry between two calls is picked up by the next one. When no token is\n * available the request goes out unauthenticated.\n */\nexport function makeAuthMiddleware(\n tokenProvider: BearerTokenProvider,\n): SdkFunctionWrapper {\n return async (action) => {\n const token = await tokenProvider();\n if (!token) {\n return action();\n }\n\n return action({ authorization: `Bearer ${token}` });\n };\n}\n","export class UnsupportedDocumentTypeError extends Error {\n constructor(documentType: string) {\n super(`Document type ${documentType} is not supported`);\n this.name = \"UnsupportedDocumentTypeError\";\n }\n\n static isError(error: unknown): error is UnsupportedDocumentTypeError {\n return (\n Error.isError(error) && error.name === \"UnsupportedDocumentTypeError\"\n );\n }\n}\n\nexport class DocumentModelNotFoundError extends Error {\n readonly documentType: string;\n readonly name = \"DocumentModelNotFoundError\";\n\n constructor(documentType: string) {\n super(`Document model module for type ${documentType} not found`);\n this.documentType = documentType;\n }\n\n static isError(error: unknown): error is DocumentModelNotFoundError {\n return Error.isError(error) && error.name === \"DocumentModelNotFoundError\";\n }\n}\n\nexport class DocumentTypeMismatchError extends Error {\n constructor(documentId: string, expectedType: string, actualType: string) {\n super(\n `Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`,\n );\n }\n}\n\nexport class NoSelectedDocumentError extends Error {\n constructor() {\n super(\n \"There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?\",\n );\n }\n}\n","import type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport { isDerivedDocumentId } from \"@powerhousedao/shared/document-model\";\nimport slug from \"slug\";\n\n// Length of the base64url id a v2-required document gets.\nconst DERIVED_ID_LENGTH = 43;\n\n// Returns url with base path plus provided path\nexport function resolveUrlPathname(path: string) {\n return new URL(\n path.replace(/^\\/+/, \"\"),\n window.location.origin + (window.ph?.basePath ?? \"/\"),\n ).pathname;\n}\n\n/** Returns the current path without the base path */\nexport function getPathWithoutBase(path: string) {\n const basePath = window.ph?.basePath ?? \"/\";\n return path.replace(basePath, basePath.endsWith(\"/\") ? \"/\" : \"\");\n}\n\n/** Makes a URL component for a drive. */\nexport function makeDriveUrlComponent(\n drive: DocumentDriveDocument | undefined,\n) {\n if (!drive) return \"\";\n return `/d/${slug(drive.header.slug)}`;\n}\n\n/**\n * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept\n * verbatim, since a v2-required id is case-sensitive base64url.\n */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n const nameSlug = node.name ? slug(node.name) : \"\";\n return nameSlug ? `${nameSlug}-${node.id}` : node.id;\n}\n\n/** Extracts the node slug from a path.\n *\n * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n */\nexport function extractNodeSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath);\n return match?.[1];\n}\n\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nexport function findUuid(input: string | undefined) {\n if (!input) return undefined;\n const uuidRegex =\n /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/;\n const match = uuidRegex.exec(input);\n return match?.[0];\n}\n\n/** The v2-required document id a slug ends with, if any. */\nexport function findDerivedId(input: string | undefined) {\n if (!input || input.length < DERIVED_ID_LENGTH) return undefined;\n const start = input.length - DERIVED_ID_LENGTH;\n if (start > 0 && input[start - 1] !== \"-\") return undefined;\n const candidate = input.slice(start);\n return isDerivedDocumentId(candidate) ? candidate : undefined;\n}\n\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);\n}\n\nexport function extractNodeIdFromPath(path: string) {\n const nodeSlug = extractNodeSlugFromPath(path);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n return nodeId;\n}\n\n/** Extracts the drive slug from a path.\n * Used for extracting drive ids from drive slugs in the URL.\n * Expects the path to be in the format `/d/<drive-slug>`.\n */\nexport function extractDriveSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/([^/]+)/.exec(currentPath);\n return match?.[1] ?? \"\";\n}\n\nexport function extractDriveIdFromSlug(driveSlug: string | undefined) {\n return findUuid(driveSlug) ?? findDerivedId(driveSlug);\n}\n\nexport function extractDriveIdFromPath(path: string) {\n const driveSlug = extractDriveSlugFromPath(path);\n const driveId = extractDriveIdFromSlug(driveSlug);\n return driveId;\n}\n\n/**\n * Creates a URL string with the given pathname while preserving existing query parameters.\n */\nexport function createUrlWithPreservedParams(pathname: string): string {\n const search = window.location.search;\n return search ? `${pathname}${search}` : pathname;\n}\n","import type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type { SetPHGlobalValue, UsePHGlobalValue } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n\n/** Returns all of the drives in the reactor */\nexport const useDrives: UsePHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.useValue;\n\n/** Sets the drives in the reactor */\nexport const setDrives: SetPHGlobalValue<DocumentDriveDocument[]> =\n drivesEventFunctions.setValue;\n\n/** Adds an event handler for the drives */\nexport const addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport {\n createUrlWithPreservedParams,\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n extractNodeSlugFromPath,\n makeNodeSlug,\n resolveUrlPathname,\n} from \"../utils/url.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nexport const useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\nconst setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\n\n/** Sets the selected node (file or folder). */\nexport function setSelectedNode(nodeOrNodeSlug: Node | string | undefined) {\n const nodeSlug =\n typeof nodeOrNodeSlug === \"string\"\n ? nodeOrNodeSlug\n : makeNodeSlug(nodeOrNodeSlug);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n setSelectedNodeId(nodeId);\n const driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);\n if (!driveSlugFromPath) {\n return;\n }\n if (!nodeSlug) {\n const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n return;\n }\n const pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\n\nexport function addResetSelectedNodeEventHandler() {\n window.addEventListener(\"ph:selectedDriveIdUpdated\", () => {\n setSelectedNodeId(undefined);\n });\n}\n\nexport function addSetSelectedNodeOnPopStateEventHandler() {\n window.addEventListener(\"popstate\", () => {\n const pathname = window.location.pathname;\n const nodeSlug = extractNodeSlugFromPath(pathname);\n // The slug embeds the id (`<name>-<uuid>`); compare ids, not slug vs id.\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n const selectedNodeId = window.ph?.selectedNodeId;\n if (nodeId !== selectedNodeId) {\n setSelectedNode(nodeSlug);\n }\n });\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n createUrlWithPreservedParams,\n extractDriveIdFromPath,\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n resolveUrlPathname,\n} from \"../utils/url.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDrives } from \"./drives.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\nimport { setSelectedNode } from \"./set-selected-node.js\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n\n/** Returns the selected drive id */\nexport const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Sets the selected drive id */\nexport const setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n\n/** Adds an event handler for the selected drive id */\nexport const addSelectedDriveIdEventHandler =\n selectedDriveIdEventFunctions.addEventHandler;\n\n/** Returns the selected drive */\nexport function useSelectedDrive() {\n const drive = useSelectedDriveSafe();\n if (!drive[0]) {\n throw new Error(\n \"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\",\n );\n }\n\n return drive;\n}\n\n/** Returns the selected drive, or undefined if no drive is selected */\nexport function useSelectedDriveSafe() {\n const selectedDriveId = useSelectedDriveId();\n const drives = useDrives();\n const selectedDrive = drives?.find(\n (drive) => drive.header.id === selectedDriveId,\n );\n\n const [drive, dispatch] = useDispatch(selectedDrive);\n if (!selectedDrive) {\n return [undefined, undefined] as const;\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n\nexport function setSelectedDrive(\n driveOrDriveSlug: string | DocumentDriveDocument | undefined,\n) {\n const driveSlug =\n typeof driveOrDriveSlug === \"string\"\n ? driveOrDriveSlug\n : driveOrDriveSlug?.header.slug;\n\n // A full drive document is selected directly — a just-created drive\n // navigates before the collection refresh. Slugs go through the lookup.\n const drives = window.ph?.drives;\n const drive =\n typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null\n ? driveOrDriveSlug\n : drives?.find((d) => d.header.slug === driveSlug);\n const driveId = drive?.header.id;\n\n // A URL-pinned slug with no matching drive: the deep link may predate\n // remote drive registration, so defer instead of rewriting the URL.\n if (\n !driveId &&\n driveSlug &&\n extractDriveSlugFromPath(window.location.pathname) === driveSlug\n ) {\n // Clear the previous selection so a stale drive doesn't render against\n // the new URL; the selected node resets with it, the URL is untouched.\n if (window.ph?.selectedDriveId) {\n setSelectedDriveId(undefined);\n }\n deferDriveSelection(driveSlug);\n return;\n }\n\n // Any resolved selection supersedes a pending deferred lookup.\n cancelPendingDriveSelection();\n\n setSelectedDriveId(driveId);\n\n if (!driveId) {\n const pathname = resolveUrlPathname(\"/\");\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n return;\n }\n const pathname = resolveUrlPathname(`/d/${driveSlug}`);\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\n\n// Tick between unresolved-slug checks; re-armed while a sync is in flight.\nconst DEFERRED_DRIVE_TICK_MS = 2_000;\n// Hard cap so a wedged remote can't pin the deep link forever.\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15_000;\n\n// True while any sync remote has not completed its first successful pull —\n// a drive may still be on its way in, so the deferred lookup keeps waiting.\nfunction isInitialSyncInFlight(): boolean {\n const remotes =\n window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();\n if (!remotes?.length) {\n return false;\n }\n return remotes.some((remote) => {\n try {\n const snapshot = remote.channel.getConnectionState();\n return (\n snapshot.receivingPages ||\n (!snapshot.lastSuccessUtcMs && snapshot.state !== \"error\")\n );\n } catch {\n return false;\n }\n });\n}\n\nlet pendingHandler: (() => void) | undefined;\nlet pendingTimeout: ReturnType<typeof setTimeout> | undefined;\n\nfunction cancelPendingDriveSelection() {\n if (pendingHandler) {\n window.removeEventListener(\"ph:drivesUpdated\", pendingHandler);\n pendingHandler = undefined;\n }\n if (pendingTimeout) {\n clearTimeout(pendingTimeout);\n pendingTimeout = undefined;\n }\n}\n\n// Re-runs the slug lookup on each drives update until it resolves, then\n// restores the URL-pinned node. Unresolved slugs redirect once syncs settle.\nfunction deferDriveSelection(driveSlug: string) {\n cancelPendingDriveSelection();\n\n // Capture the node pinned in the deep link before setSelectedDrive\n // rewrites the URL to /d/<driveSlug>, dropping the node segment.\n const nodeSlug = extractNodeSlugFromPath(window.location.pathname);\n const handler = () => {\n const drive = window.ph?.drives?.find((d) => d.header.slug === driveSlug);\n if (!drive) {\n return;\n }\n cancelPendingDriveSelection();\n setSelectedDrive(driveSlug);\n setSelectedNode(nodeSlug);\n };\n pendingHandler = handler;\n window.addEventListener(\"ph:drivesUpdated\", handler);\n\n const deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n const scheduleTick = () => {\n pendingTimeout = setTimeout(() => {\n if (Date.now() < deadline && isInitialSyncInFlight()) {\n scheduleTick();\n return;\n }\n cancelPendingDriveSelection();\n const pathname = resolveUrlPathname(\"/\");\n if (pathname === window.location.pathname) {\n return;\n }\n window.history.pushState(\n null,\n \"\",\n createUrlWithPreservedParams(pathname),\n );\n }, DEFERRED_DRIVE_TICK_MS);\n };\n scheduleTick();\n}\n\nexport function addSetSelectedDriveOnPopStateEventHandler() {\n window.addEventListener(\"popstate\", () => {\n const pathname = window.location.pathname;\n const driveId = extractDriveIdFromPath(pathname);\n const selectedDriveId = window.ph?.selectedDriveId;\n if (driveId !== selectedDriveId) {\n setSelectedDrive(driveId);\n }\n });\n}\n","import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n","import type {\n FileNode,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelDocument,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useDocumentsByIds } from \"./document-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\n\n/** Returns the nodes in the selected drive. */\nexport function useNodesInSelectedDrive() {\n const [selectedDrive] = useSelectedDriveSafe();\n return selectedDrive?.state.global.nodes;\n}\n\n/** Returns the file nodes in the selected drive. */\nexport function useFileNodesInSelectedDrive(): FileNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected drive. */\nexport function useFolderNodesInSelectedDrive(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected drive. */\nexport function useDocumentsInSelectedDrive(): PHDocument[] | undefined {\n const fileNodes = useFileNodesInSelectedDrive();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return useDocumentsByIds(fileNodeIds);\n}\n\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nexport function useDocumentTypesInSelectedDrive() {\n const documentsInSelectedDrive = useDocumentsInSelectedDrive();\n const documentModelDocumentsInSelectedDrive =\n documentsInSelectedDrive?.filter(isDocumentModelDocument);\n const documentTypesFromDocumentModelDocuments =\n documentModelDocumentsInSelectedDrive?.map((doc) => doc.state.global.id);\n return documentTypesFromDocumentModelDocuments;\n}\n\nfunction isDocumentModelDocument(\n document: PHDocument,\n): document is DocumentModelDocument {\n return document.header.documentType === \"powerhouse/document-model\";\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n addSetSelectedNodeOnPopStateEventHandler,\n setSelectedNode,\n} from \"./set-selected-node.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n const selectedNodeId = useSelectedNodeId();\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === selectedNodeId);\n}\n","import type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\nimport {\n isDuplicateManifestError,\n isDuplicateModuleError,\n} from \"../reactor-interop.js\";\nimport type { IPackageManager } from \"../types/vetra.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst vetraPackageManagerFunctions = makePHEventFunctions(\n \"vetraPackageManager\",\n);\n\nexport const useVetraPackageManager = vetraPackageManagerFunctions.useValue;\n\nconst EMPTY_VETRA_PACKAGES: DocumentModelLib[] = [];\nconst noPackageManagerUnsubscribe = () => {};\n\n/**\n * Returns all of the Vetra packages loaded by the Connect instance.\n *\n * The snapshot and subscription must keep stable identity while no package\n * manager is registered: `useSyncExternalStore` loops when the snapshot\n * changes on every read, which a fresh `[]` does.\n */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n\n return useSyncExternalStore(\n (cb) =>\n packageManager\n ? packageManager.subscribe(cb)\n : noPackageManagerUnsubscribe,\n () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES,\n );\n};\n\n/** Adds the Vetra package manager event handler */\nexport const addVetraPackageManagerEventHandler =\n vetraPackageManagerFunctions.addEventHandler;\n\n/** Sets the Vetra package manager and registers its packages */\nexport function setVetraPackageManager(packageManager: IPackageManager) {\n vetraPackageManagerFunctions.setValue(packageManager);\n updateReactorClientDocumentModels(packageManager.packages);\n updateReactorClientUpgradeManifests(packageManager.packages);\n packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n updateReactorClientUpgradeManifests(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // dedupe by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n (m.version ?? 1) === (module.version ?? 1),\n ) === index,\n );\n\n const registry =\n window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n const results = registry.registerModules(...documentModelModules);\n const duplicateTypes = new Set<string>();\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateModuleError(result.error)) {\n duplicateTypes.add(result.item.documentModel.global.id);\n } else {\n console.error(\n \"Failed to register document model module:\",\n result.error,\n );\n }\n }\n }\n if (duplicateTypes.size > 0) {\n // unregisterModules is type-scoped, so replace the whole version family\n // with the incoming package's modules: re-registering only the duplicated\n // items would purge any new version that registered successfully above.\n registry.unregisterModules(...duplicateTypes);\n registry.registerModules(\n ...documentModelModules.filter((module) =>\n duplicateTypes.has(module.documentModel.global.id),\n ),\n );\n }\n}\n\nfunction updateReactorClientUpgradeManifests(packages: DocumentModelLib[]) {\n const upgradeManifests = packages\n .flatMap((pkg) => pkg.upgradeManifests)\n .filter((u) => u !== undefined);\n\n const registry =\n window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || upgradeManifests.length === 0) return;\n\n const results = registry.registerUpgradeManifests(...upgradeManifests);\n const duplicates = [];\n for (const result of results) {\n if (result.status === \"error\") {\n if (isDuplicateManifestError(result.error)) {\n duplicates.push(result);\n } else {\n console.error(\"Failed to register upgrade manifest:\", result.error);\n }\n }\n }\n if (duplicates.length > 0) {\n const duplicateTypes = duplicates\n .map((r) => r.item.documentType)\n .filter((t): t is string => !!t);\n registry.unregisterUpgradeManifests(...duplicateTypes);\n registry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n }\n}\n","import type { DocumentModelModule } from \"document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useDocumentModelModules(): DocumentModelModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // deduplicate by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n m.version === module.version,\n ) === index,\n );\n}\n\n/**\n * Resolves a document model module by document type, mirroring the registry's\n * semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the\n * LATEST version of the type wins (`version ?? 1` as each module's default),\n * with `version` given only an exact match is returned. The reactor resolves\n * modules the same way when a document is created, so metadata read through\n * this hook and the version a creation actually uses cannot disagree.\n */\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n version?: number,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n if (!id || !documentModelModules) return undefined;\n\n let latestModule: DocumentModelModule | undefined;\n let latestVersion = -1;\n for (const module of documentModelModules) {\n if (module.documentModel.global.id !== id) continue;\n const moduleVersion = module.version ?? 1;\n if (version !== undefined) {\n if (moduleVersion === version) return module;\n continue;\n }\n if (moduleVersion > latestVersion) {\n latestVersion = moduleVersion;\n latestModule = module;\n }\n }\n return latestModule;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,+BAA+B;;;;;;;;;;;AAYrC,eAAsB,6BAEpB;AACA,KAAI,OAAO,WAAW,YACpB;CAGF,MAAM,SAAS,OAAO,IAAI;AAC1B,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,MAAmB,CAAC,CAAC,EAAE;AAClC,WAAS,2BAA2B,GAAG,eAAe;AACtD,WAAS,yBAAyB,GAAG,WAAW,KAAK,MAAM,EAAE,KAAK,CAAC;;;;;ACtHvE,SAAgB,0BAA6D;AAE3E,QADsB,kBAAkB,CAErC,SAAS,QAAQ,IAAI,eAAe,CACpC,QACE,QAAQ,OAAO,YAEd,QAAQ,WACL,MACC,EAAE,cAAc,OAAO,OAAO,OAAO,cAAc,OAAO,MAC1D,EAAE,YAAY,OAAO,QACxB,KAAK,MACT;;;;;;;;;;AAWL,SAAgB,2BACd,IACA,SACiC;CACjC,MAAM,uBAAuB,yBAAyB;AACtD,KAAI,CAAC,MAAM,CAAC,qBAAsB,QAAO,KAAA;CAEzC,IAAI;CACJ,IAAI,gBAAgB;AACpB,MAAK,MAAM,UAAU,sBAAsB;AACzC,MAAI,OAAO,cAAc,OAAO,OAAO,GAAI;EAC3C,MAAM,gBAAgB,OAAO,WAAW;AACxC,MAAI,YAAY,KAAA,GAAW;AACzB,OAAI,kBAAkB,QAAS,QAAO;AACtC;;AAEF,MAAI,gBAAgB,eAAe;AACjC,mBAAgB;AAChB,kBAAe;;;AAGnB,QAAO"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { C as addResetSelectedNodeEventHandler, D as addDrivesEventHandler,
|
|
1
|
+
import { E as uploadOperations, T as queueOperations, a as setDocumentCache, g as isOperationCache, i as addDocumentCacheEventHandler, m as IDLE_OPERATIONS_ENTRY, p as DocumentCache, s as useDocumentCache, v as DOCUMENT_CHANGE_TYPE, w as queueActions } from "./document-by-id-DgdUGMVm.js";
|
|
2
|
+
import { C as addResetSelectedNodeEventHandler, D as addDrivesEventHandler, J as makeAuthMiddleware, K as UnsupportedDocumentTypeError, T as addSetSelectedNodeOnPopStateEventHandler, U as DocumentModelNotFoundError, _ as addSetSelectedDriveOnPopStateEventHandler, g as addSelectedDriveIdEventHandler, i as setVetraPackageManager, q as ambientRenownTokenProvider, r as addVetraPackageManagerEventHandler, w as addSelectedNodeIdEventHandler, x as useSelectedDriveId } from "./document-model-modules-D1ZEoGjN.js";
|
|
3
3
|
import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
|
|
4
4
|
import { a as PhDocumentFieldsFragmentDoc, n as DocumentChangeType, o as PropagationMode, r as DocumentChangesDocument, t as createClient$1 } from "./client-D4bkR4pH.js";
|
|
5
5
|
import { f as addLoadingEventHandler, t as addRenownEventHandler } from "./renown-BHxwP7xU.js";
|
|
6
6
|
import { logger } from "document-model";
|
|
7
|
-
import { UnsupportedDocumentModelVersionError, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, createPresignedHeader, createZip, deserializeSignature, documentModelDocumentType, generateId, hashDocumentStateForScope, normalizeDocumentModelVersion, replayDocumentVersioned, setName, setPreferredEditor, toTransportAction } from "@powerhousedao/shared/document-model";
|
|
8
7
|
import { addFolder, copyNode, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
|
|
8
|
+
import { UnsupportedDocumentModelVersionError, actionSignerIdentity, actionSigningTarget, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, createCopyHeader, createPresignedHeader, createZip, deserializeSignature, documentModelDocumentType, generateId, hasDerivedDocumentId, hashDocumentStateForScope, normalizeDocumentModelVersion, replayDocumentVersioned, setName, setPreferredEditor, signaturePolicyOf, toTransportAction, withSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
9
9
|
import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
|
|
10
10
|
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
11
11
|
import { GraphQLClient } from "graphql-request";
|
|
@@ -293,7 +293,7 @@ async function addDocument(driveId, name, documentType, parentFolder, document,
|
|
|
293
293
|
if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
|
|
294
294
|
documentModelModule = module;
|
|
295
295
|
} else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
|
|
296
|
-
const newDocument = document ?? documentModelModule.utils.createDocument();
|
|
296
|
+
const newDocument = document ?? withSignaturePolicy(documentModelModule.utils.createDocument(), await reactorClient.getCreateSignaturePolicy());
|
|
297
297
|
if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
|
|
298
298
|
newDocument.header.name = name;
|
|
299
299
|
if (preferredEditor) newDocument.header.meta = {
|
|
@@ -341,9 +341,24 @@ function isDocumentAlreadyExists(error) {
|
|
|
341
341
|
* fails leaves the drive untouched, so a retry has nothing to clean up.
|
|
342
342
|
*/
|
|
343
343
|
async function createImportedDocument(reactor, document, driveId, name, parentFolder) {
|
|
344
|
-
|
|
344
|
+
const v2Required = signaturePolicyOf(document.header) === "v2-required";
|
|
345
|
+
const keepsId = (!v2Required || hasDerivedDocumentId(document.header)) && !await reactor.isDocumentIdTaken(document.header.id);
|
|
346
|
+
let documentId = keepsId ? document.header.id : generateId();
|
|
345
347
|
for (let attempt = 1;; attempt++) {
|
|
346
|
-
|
|
348
|
+
let header;
|
|
349
|
+
if (!v2Required) header = createPresignedHeader(documentId, document.header.documentType);
|
|
350
|
+
else if (keepsId && attempt === 1) {
|
|
351
|
+
header = createPresignedHeader(documentId, document.header.documentType);
|
|
352
|
+
header.createdAtUtcIso = document.header.createdAtUtcIso;
|
|
353
|
+
header.sig = {
|
|
354
|
+
...header.sig,
|
|
355
|
+
nonce: document.header.sig.nonce
|
|
356
|
+
};
|
|
357
|
+
header.protocolVersions = { ...document.header.protocolVersions };
|
|
358
|
+
} else {
|
|
359
|
+
header = createCopyHeader(document.header);
|
|
360
|
+
documentId = header.id;
|
|
361
|
+
}
|
|
347
362
|
header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
|
|
348
363
|
header.meta = document.header.meta;
|
|
349
364
|
header.name = name || document.header.name;
|
|
@@ -609,7 +624,7 @@ async function _duplicateDocument(reactor, document, newId = generateId()) {
|
|
|
609
624
|
reducers,
|
|
610
625
|
upgradeManifest
|
|
611
626
|
};
|
|
612
|
-
const header =
|
|
627
|
+
const header = createCopyHeader(document.header, newId, await reactor.getCreateSignaturePolicy());
|
|
613
628
|
const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
|
|
614
629
|
assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
|
|
615
630
|
return duplicated;
|
|
@@ -646,6 +661,7 @@ async function copyNode$1(driveId, src, target) {
|
|
|
646
661
|
const duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);
|
|
647
662
|
const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
|
|
648
663
|
if (resolvedName) duplicatedDocument.header.name = resolvedName;
|
|
664
|
+
fileNodeToCopy.targetId = duplicatedDocument.header.id;
|
|
649
665
|
await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
|
|
650
666
|
} catch (e) {
|
|
651
667
|
logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
|
|
@@ -941,34 +957,34 @@ function stampAction(action, document, revision = document.header.revision[actio
|
|
|
941
957
|
};
|
|
942
958
|
}
|
|
943
959
|
/**
|
|
944
|
-
* Signs a stamped action
|
|
945
|
-
*
|
|
946
|
-
*
|
|
947
|
-
*
|
|
960
|
+
* Signs a stamped action for `target`, keeping any signatures it already
|
|
961
|
+
* carries. The signer reads `context.prevOpHash`, so this runs after
|
|
962
|
+
* {@link stampAction}. A v2 tuple covers the signer's identity, so the context
|
|
963
|
+
* takes the signer's user and app even when the action named others.
|
|
948
964
|
*/
|
|
949
|
-
async function signStampedAction(action, signer, signal) {
|
|
950
|
-
|
|
951
|
-
const
|
|
952
|
-
const app = actionSigner?.app ?? signer.app;
|
|
953
|
-
if (!user || !app) throw new Error("cannot sign an action: the signer has no user or app identity");
|
|
954
|
-
const signature = await signer.signAction(action, signal);
|
|
965
|
+
async function signStampedAction(action, signer, target, signal) {
|
|
966
|
+
if (!signer.user || !signer.app) throw new Error("cannot sign an action: the signer has no user or app identity");
|
|
967
|
+
const signature = await signer.signAction(action, target, signal);
|
|
955
968
|
return {
|
|
956
969
|
...action,
|
|
957
970
|
context: {
|
|
958
971
|
...action.context,
|
|
959
972
|
signer: {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
signatures: [...actionSigner?.signatures ?? [], signature]
|
|
973
|
+
...actionSignerIdentity(signer),
|
|
974
|
+
signatures: [...action.context?.signer?.signatures ?? [], signature]
|
|
963
975
|
}
|
|
964
976
|
}
|
|
965
977
|
};
|
|
966
978
|
}
|
|
979
|
+
/** The log a snapshot's action is written to; the snapshot names the branch read. */
|
|
980
|
+
function snapshotTarget(action, snapshot) {
|
|
981
|
+
return actionSigningTarget(action, snapshot.header.id, snapshot.header.branch || "main");
|
|
982
|
+
}
|
|
967
983
|
/**
|
|
968
984
|
* Actions a snapshot batch cannot predict the next state for.
|
|
969
985
|
*
|
|
970
|
-
* `UNDO
|
|
971
|
-
*
|
|
986
|
+
* `UNDO` and `REDO` rewrite history the light read path never fetched (and
|
|
987
|
+
* the reducer appends no operation for them); `NOOP` is only ever produced
|
|
972
988
|
* by an undo chain; the document-scope actions run through the reactor's
|
|
973
989
|
* document-action handler rather than a document-model reducer
|
|
974
990
|
* (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and
|
|
@@ -977,7 +993,6 @@ async function signStampedAction(action, signer, signal) {
|
|
|
977
993
|
const unsupportedBatchActions = new Set([
|
|
978
994
|
"UNDO",
|
|
979
995
|
"REDO",
|
|
980
|
-
"PRUNE",
|
|
981
996
|
"NOOP",
|
|
982
997
|
"CREATE_DOCUMENT",
|
|
983
998
|
"DELETE_DOCUMENT",
|
|
@@ -1020,7 +1035,7 @@ const predictionProtocolVersion = 2;
|
|
|
1020
1035
|
*/
|
|
1021
1036
|
async function prepareSignedActions(actions, snapshot, signer, module, signal) {
|
|
1022
1037
|
if (actions.length === 0) return [];
|
|
1023
|
-
if (actions.length === 1) return [await signStampedAction(stampAction(actions[0], snapshot), signer, signal)];
|
|
1038
|
+
if (actions.length === 1) return [await signStampedAction(stampAction(actions[0], snapshot), signer, snapshotTarget(actions[0], snapshot), signal)];
|
|
1024
1039
|
const scope = sharedScope(actions);
|
|
1025
1040
|
assertSupportedBatch(actions);
|
|
1026
1041
|
if (!module) throw new Error(`cannot sign ${actions.length} actions: no document model module for ${snapshot.header.documentType} was supplied, so the batch state cannot be predicted`);
|
|
@@ -1035,7 +1050,8 @@ async function prepareSignedActions(actions, snapshot, signer, module, signal) {
|
|
|
1035
1050
|
const signed = [];
|
|
1036
1051
|
for (const [index, action] of actions.entries()) {
|
|
1037
1052
|
throwIfAborted(signal, index);
|
|
1038
|
-
const
|
|
1053
|
+
const stamped = stampAction(action, working, revision);
|
|
1054
|
+
const signedAction = await signStampedAction(stamped, signer, snapshotTarget(stamped, snapshot), signal);
|
|
1039
1055
|
signed.push(signedAction);
|
|
1040
1056
|
const before = scopeOperationCount(working, scope);
|
|
1041
1057
|
let next;
|
|
@@ -2603,4 +2619,4 @@ function useDocumentOperations(documentId, scope, options = {}) {
|
|
|
2603
2619
|
//#endregion
|
|
2604
2620
|
export { addDefaultDrivesUrlEventHandler as $, useIsAddLocalDrivesEnabled as $n, isAuthRefusalClose as $r, setEnabledEditors as $t, useReactorClientModule as A, fetchDocumentOperations as Ai, setRenownUrl as An, useSentryRelease as Ar, addRenownAdaptersEventHandler as At, useDragNode as B, addModalEventHandler as Bi, setWarnOutdatedApp as Bn, phAppConfigHooks as Br, addSwitchboardUrlEventHandler as Bt, addReactorClientModuleEventHandler as C, addDocument as Ci, setIsRelationalProcessorsEnabled as Cn, useRenownChainId as Cr, addIsExternalRelationalProcessorsEnabledEventHandler as Ct, useModelRegistry as D, deleteNode as Di, setRenownAdapters as Dn, useRouterBasename as Dr, addIsSentryTracingEnabledEventHandler as Dt, useDatabase as E, copyNode$1 as Ei, setLogLevel as En, useRequiresHardRefresh as Er, addIsRelationalProcessorsEnabledEventHandler as Et, usePackageDiscoveryService as F, renameNode as Fi, setSentryRelease as Fn, useWarnOutdatedApp as Fr, addRouterBasenameEventHandler as Ft, useFeatures as G, showPHModal as Gi, useDefaultDrivesUrl as Gn, setIsDragAndDropEnabled as Gr, phGlobalConfigSetters as Gt, useDropTarget as H, setPHModal as Hi, useAnalyticsDatabaseName as Hn, phDocumentEditorConfigHooks as Hr, addVersionEventHandler as Ht, addGraphQLReactorClientEventHandler as I, setPreferredEditorOnNode as Ii, setStudioMode as In, addAllowedDocumentTypesEventHandler as Ir, addSentryDsnEventHandler as It, useAttachmentService as J, useEnabledEditors as Jn, useIsDragAndDropEnabled as Jr, setBasePath as Jt, addAttachmentServiceEventHandler as K, usePHModal as Ki, useDisabledEditors as Kn, setIsExternalControlsEnabled as Kr, setAllowList as Kt, setGraphQLReactorClient as L, upgradeDocument as Li, setSwitchboardUrl as Ln, addIsDragAndDropEnabledEventHandler as Lr, addSentryEnvEventHandler as Lt, useSyncList as M, loadFile as Mi, setRouterBasename as Mn, useSwitchboardUrl as Mr, addRenownNetworkIdEventHandler as Mt, addPackageDiscoveryServiceEventHandler as N, moveNode$1 as Ni, setSentryDsn as Nn, useVersion as Nr, addRenownUrlEventHandler as Nt, usePGlite as O, exportFile as Oi, setRenownChainId as On, useSentryDsn as Or, addLocalDrivesEnabledEventHandler as Ot, setPackageDiscoveryService as P, renameDriveNode as Pi, setSentryEnv as Pn, useVersionCheckInterval as Pr, addRequiresHardRefreshEventHandler as Pt, addCliVersionEventHandler as Q, useIsAddDriveEnabled as Qn, viewFilterInputFromViewFilter as Qr, setDrivesPreserveStrategy as Qt, useGraphQLReactorClient as R, getUserPermissions as Ri, setVersion as Rn, addIsExternalControlsEnabledEventHandler as Rr, addSentryReleaseEventHandler as Rt, addReactorClientEventHandler as S, screamingSnakeToCamel as Si, setIsPublicDrivesEnabled as Sn, useRenownAdapters as Sr, addIsExternalProcessorsEnabledEventHandler as St, setReactorClientModule as T, addFolder$1 as Ti, setLocalDrivesEnabled as Tn, useRenownUrl as Tr, addIsPublicDrivesEnabledEventHandler as Tt, addFeaturesEventHandler as U, showCreateDocumentModal as Ui, useBasePath as Un, phDocumentEditorConfigSetters as Ur, addWarnOutdatedAppEventHandler as Ut, useDropNode as V, closePHModal as Vi, useAllowList as Vn, phAppConfigSetters as Vr, addVersionCheckIntervalEventHandler as Vt, setFeatures as W, showDeleteNodeModal as Wi, useCliVersion as Wn, setAllowedDocumentTypes as Wr, phGlobalConfigHooks as Wt, addAnalyticsDatabaseNameEventHandler as X, useGaTrackingId as Xn, GraphQLReactorClient as Xr, setDefaultDrivesUrl as Xt, addAllowListEventHandler as Y, useFileUploadOperationsChunkSize as Yn, useIsExternalControlsEnabled as Yr, setCliVersion as Yt, addBasePathEventHandler as Z, useIsAddCloudDrivesEnabled as Zn, isGraphQLReactorClient as Zr, setDisabledEditors as Zt, addRevisionHistoryVisibleEventHandler as _, ConflictError as _i, setIsEditorReadModeEnabled as _n, useIsPublicDrivesEnabled as _r, addIsDocumentModelSelectionSettingsEnabledEventHandler as _t, addPHEventHandlers as a, subgraphUrlFromGraphqlUrl as ai, setIsAddPublicDrivesEnabled as an, useIsDeleteCloudDrivesEnabled as ar, addIsAddCloudDrivesEnabledEventHandler as at, showRevisionHistory as b, extractRevisionMap as bi, setIsExternalRelationalProcessorsEnabled as bn, useLocalDrivesEnabled as br, addIsEditorReadModeEnabledEventHandler as bt, addToastEventHandler as c, resolveDocumentModelModule as ci, setIsAnalyticsExternalProcessorsEnabled as cn, useIsDiffAnalyticsEnabled as cr, addIsAddPublicDrivesEnabledEventHandler as ct, addSelectedTimelineRevisionEventHandler as d, stampAction as di, setIsDeleteLocalDrivesEnabled as dn, useIsEditorDebugModeEnabled as dr, addIsAnalyticsExternalProcessorsEnabledEventHandler as dt, makeAuthConnectionParams as ei, setFileUploadOperationsChunkSize as en, useIsAddPublicDrivesEnabled as er, addDisabledEditorsEventHandler as et, setSelectedTimelineRevision as f, MutateDocumentWithOperationsDocument as fi, setIsDeletePublicDrivesEnabled as fn, useIsEditorReadModeEnabled as fr, addIsCloudDrivesEnabledEventHandler as ft, useSelectedTimelineItem as g, revisionMapFromRevisionsList as gi, setIsEditorDebugModeEnabled as gn, useIsLocalDrivesEnabled as gr, addIsDiffAnalyticsEnabledEventHandler as gt, setSelectedTimelineItem as h, phDocumentFromMutation as hi, setIsDriveAnalyticsEnabled as hn, useIsExternalRelationalProcessorsEnabled as hr, addIsDeletePublicDrivesEnabledEventHandler as ht, useSwitchboardClient as i, describeGraphQLDocument as ii, setIsAddLocalDrivesEnabled as in, useIsCloudDrivesEnabled as ir, addGaTrackingIdEventHandler as it, useSync as j, getDocumentExtension as ji, setRequiresHardRefresh as jn, useStudioMode as jr, addRenownChainIdEventHandler as jt, useReactorClient as k, extractInitialState as ki, setRenownNetworkId as kn, useSentryEnv as kr, addLogLevelEventHandler as kt, setPHToast as l, prepareSignedActions as li, setIsCloudDrivesEnabled as ln, useIsDocumentModelSelectionSettingsEnabled as lr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as lt, addSelectedTimelineItemEventHandler as m, phDocumentFromGetDocument as mi, setIsDocumentModelSelectionSettingsEnabled as mn, useIsExternalProcessorsEnabled as mr, addIsDeleteLocalDrivesEnabledEventHandler as mt, GraphQLReactorProvider as n, subscriptionsUrlFromGraphqlUrl as ni, setIsAddCloudDrivesEnabled as nn, useIsAnalyticsEnabled as nr, addEnabledEditorsEventHandler as nt, callEventHandlerRegisterFunctions as o, StaticPackageManager as oi, setIsAnalyticsDatabaseWorkerEnabled as on, useIsDeleteLocalDrivesEnabled as or, addIsAddDriveEnabledEventHandler as ot, useSelectedTimelineRevision as p, ReactorOperationFieldsFragmentDoc as pi, setIsDiffAnalyticsEnabled as pn, useIsExternalPackagesEnabled as pr, addIsDeleteCloudDrivesEnabledEventHandler as pt, setAttachmentService as q, useDrivesPreserveStrategy as qn, useAllowedDocumentTypes as qr, setAnalyticsDatabaseName as qt, ensurePHEventHandlers as r, SubgraphSdkRegistry as ri, setIsAddDriveEnabled as rn, useIsAnalyticsExternalProcessorsEnabled as rr, addFileUploadOperationsChunkSizeEventHandler as rt, commonGlobalEventHandlerFunctions as s, packageFromDocumentModels as si, setIsAnalyticsEnabled as sn, useIsDeletePublicDrivesEnabled as sr, addIsAddLocalDrivesEnabledEventHandler as st, useDocumentOperations as t, startDocumentChangesSubscription as ti, setGaTrackingId as tn, useIsAnalyticsDatabaseWorkerEnabled as tr, addDrivesPreserveStrategyEventHandler as tt, usePHToast as u, signStampedAction as ui, setIsDeleteCloudDrivesEnabled as un, useIsDriveAnalyticsEnabled as ur, addIsAnalyticsEnabledEventHandler as ut, hideRevisionHistory as v, buildPulledDocument as vi, setIsExternalPackagesEnabled as vn, useIsRelationalProcessorsEnabled as vr, addIsDriveAnalyticsEnabledEventHandler as vt, setReactorClient as w, addFileWithProgress as wi, setIsSentryTracingEnabled as wn, useRenownNetworkId as wr, addIsLocalDrivesEnabledEventHandler as wt, useRevisionHistoryVisible as x, hasRevisionConflict as xi, setIsLocalDrivesEnabled as xn, useLogLevel as xr, addIsExternalPackagesEnabledEventHandler as xt, setRevisionHistoryVisible as y, convertRemoteOperations as yi, setIsExternalProcessorsEnabled as yn, useIsSentryTracingEnabled as yr, addIsEditorDebugModeEnabledEventHandler as yt, addDraggingNodeEventHandler as z, isDocumentTypeSupported as zi, setVersionCheckInterval as zn, isExternalControlsEnabledEventFunctions as zr, addStudioModeEventHandler as zt };
|
|
2605
2621
|
|
|
2606
|
-
//# sourceMappingURL=document-operations-
|
|
2622
|
+
//# sourceMappingURL=document-operations-DhrcpXMf.js.map
|