@powerhousedao/reactor-browser 6.0.0-dev.163 → 6.0.0-dev.165
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/index.d.ts.map +1 -1
- package/dist/index.js +8 -1
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["baseAddFolder","baseDeleteNode","copyNode","baseCopyNode","driveCollectionId","DocumentChangeType","truncateAddress","logoutUtil","copyNode","driveCollectionId","GqlRequestChannel","REACTOR_SCHEMA","styles","defaultLogout","#namespace","#storage","#readMap","#writeMap"],"sources":["../src/actions/queue.ts","../src/actions/sign.ts","../src/actions/dispatch.ts","../src/errors.ts","../src/utils/documents.ts","../src/utils/user.ts","../src/actions/document.ts","../src/actions/drive.ts","../src/global/core.ts","../src/analytics/context.tsx","../src/analytics/hooks/analytics-query.ts","../src/hooks/dispatch.ts","../src/document-cache.ts","../src/hooks/make-ph-event-functions.ts","../src/hooks/document-cache.ts","../src/hooks/document-by-id.ts","../src/analytics/hooks/timeline-items.ts","../src/analytics/hooks/document-timeline.ts","../src/constants.ts","../src/document-model.ts","../src/graphql/gen/schema.ts","../src/graphql/batch-queries.ts","../src/graphql/client.ts","../src/hooks/loading.ts","../src/hooks/renown.ts","../src/renown/constants.ts","../src/renown/utils.ts","../src/renown/use-renown-auth.ts","../src/hooks/config/editor.ts","../src/hooks/config/connect.ts","../src/hooks/features.ts","../src/hooks/package-discovery.ts","../src/hooks/drives.ts","../src/hooks/modals.ts","../src/hooks/reactor.ts","../src/hooks/revision-history.ts","../src/utils/url.ts","../src/hooks/selected-drive.ts","../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/selected-timeline-item.ts","../src/hooks/timeline-revision.ts","../src/hooks/toast.ts","../src/hooks/vetra-packages.ts","../src/hooks/add-ph-event-handlers.ts","../src/hooks/document-model-modules.ts","../src/hooks/allowed-document-model-modules.ts","../src/hooks/selected-folder.ts","../src/hooks/child-nodes.ts","../src/hooks/config/set-config-by-key.ts","../src/hooks/config/utils.ts","../src/hooks/config/set-config-by-object.ts","../src/hooks/config/use-value-by-key.ts","../src/hooks/connection-state.ts","../src/hooks/document-of-type.ts","../src/hooks/document-operations.ts","../src/hooks/supported-document-types.ts","../src/hooks/document-types.ts","../src/hooks/drive-by-id.ts","../src/hooks/editor-modules.ts","../src/hooks/folder-by-id.ts","../src/hooks/items-in-selected-folder.ts","../src/hooks/node-actions.ts","../src/hooks/node-by-id.ts","../src/hooks/node-path.ts","../src/hooks/parent-folder.ts","../src/hooks/selected-document.ts","../src/hooks/subgraph-modules.ts","../src/hooks/use-feature-flags.ts","../src/utils/drives.ts","../src/utils/validate-document.ts","../src/utils/export-document.ts","../src/utils/get-revision-from-date.ts","../src/utils/switchboard.ts","../src/hooks/use-get-switchboard-link.ts","../src/hooks/use-on-drop-file.ts","../src/hooks/user-permissions.ts","../src/pglite/drop.ts","../src/reactor.ts","../src/registry/fetchers.ts","../src/registry/client.ts","../src/pglite/usePGlite.ts","../src/relational/hooks/useRelationalDb.ts","../src/relational/hooks/useRelationalQuery.ts","../src/relational/utils/createProcessorQuery.ts","../src/remote-controller/action-tracker.ts","../src/remote-controller/remote-client.ts","../src/remote-controller/utils.ts","../src/remote-controller/remote-controller.ts","../src/renown/components/icons.tsx","../src/renown/components/slot.tsx","../src/renown/components/RenownLoginButton.tsx","../src/renown/components/RenownUserButton.tsx","../src/renown/components/RenownAuthButton.tsx","../src/renown/use-renown-init.ts","../src/renown/renown-init.tsx","../src/storage/base-storage.ts","../src/storage/local-storage.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 { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n buildSignedAction,\n type ActionSigner,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\n\nexport async function signAction(action: Action, document: PHDocument) {\n const reactor = window.ph?.reactorClient;\n if (!reactor) return action;\n\n const documentModelModule = await reactor.getDocumentModelModule(\n document.header.documentType,\n );\n const reducer = documentModelModule.reducer;\n const renown = window.ph?.renown;\n if (!renown?.user) return action;\n if (!action.context?.signer) return action;\n\n const actionSigner = action.context.signer;\n const unsafeSignedAction = await buildSignedAction(\n action,\n reducer,\n document,\n actionSigner,\n renown.crypto.sign,\n );\n\n // TODO: this is super dangerous and is caused by the `buildSignedAction` function returning an `Operation` instead of an `Action`\n return unsafeSignedAction as unknown as Action;\n}\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\nasync function 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 const signedAction = await signAction(action, document);\n const signedActionWithContext = addActionContext(signedAction);\n return signedActionWithContext;\n}\n\nexport async 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 = await Promise.all(\n actions.map((action) => 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 = await 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","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 DocumentNotFoundError extends Error {\n constructor(documentId: string) {\n super(`Document with id ${documentId} not found`);\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","export function isDocumentTypeSupported(\n documentType: string,\n supportedDocuments: string[] | null | undefined,\n): boolean {\n if (!supportedDocuments?.length) {\n return true;\n }\n\n return supportedDocuments.some((pattern) => {\n // Path wildcard: \"powerhouse/*\"\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -2);\n return documentType.startsWith(prefix + \"/\");\n }\n\n // Prefix wildcard: \"power*\"\n if (pattern.endsWith(\"*\") && !pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return documentType.startsWith(prefix);\n }\n\n // Exact match\n return pattern === documentType;\n });\n}\n","export function getUserPermissions() {\n const user = window.ph?.renown?.user;\n const allowList = window.ph?.allowList;\n if (!allowList) {\n return {\n isAllowedToCreateDocuments: true,\n isAllowedToEditDocuments: true,\n };\n }\n return {\n isAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n isAllowedToEditDocuments: allowList.includes(user?.address ?? \"\"),\n };\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport type {\n ConflictResolution,\n DocumentTypeIcon,\n FileUploadProgressCallback,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n addFolder as baseAddFolder,\n copyNode as baseCopyNode,\n deleteNode as baseDeleteNode,\n updateFile as baseUpdateFile,\n generateNodesCopy,\n handleTargetNameCollisions,\n isFileNode,\n isFolderNode,\n updateNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelModule,\n DocumentOperations,\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n baseLoadFromInput,\n baseSaveToFileHandle,\n createPresignedHeader,\n createZip,\n documentModelDocumentType,\n generateId,\n replayDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport {\n DocumentModelNotFoundError,\n UnsupportedDocumentTypeError,\n} from \"../errors.js\";\nimport { isDocumentTypeSupported } from \"../utils/documents.js\";\nimport { getUserPermissions } from \"../utils/user.js\";\nimport { queueActions, queueOperations, uploadOperations } from \"./queue.js\";\n\nasync function isDocumentInLocation(\n document: PHDocument,\n driveId: string,\n parentFolder?: string,\n): Promise<{\n isDuplicate: boolean;\n duplicateType?: \"id\" | \"name\";\n nodeId?: string;\n}> {\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n return { isDuplicate: false };\n }\n\n // Get the drive and check its nodes\n let drive;\n try {\n drive = await reactorClient.get<DocumentDriveDocument>(driveId);\n } catch {\n return { isDuplicate: false };\n }\n\n // Case 1: Check for duplicate by ID\n const nodeById = drive.state.global.nodes.find(\n (node: { id: string }) => node.id === document.header.id,\n );\n\n if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) {\n return {\n isDuplicate: true,\n duplicateType: \"id\",\n nodeId: nodeById.id,\n };\n }\n\n // Case 2: Check for duplicate by name + type in same parent folder\n const nodeByNameAndType = drive.state.global.nodes.find(\n (node: Node) =>\n isFileNode(node) &&\n node.name === document.header.name &&\n node.documentType === document.header.documentType &&\n node.parentFolder === (parentFolder ?? null),\n );\n\n if (nodeByNameAndType) {\n return {\n isDuplicate: true,\n duplicateType: \"name\",\n nodeId: nodeByNameAndType.id,\n };\n }\n\n return { isDuplicate: false };\n}\n\nfunction getDocumentTypeIcon(\n document: PHDocument,\n): DocumentTypeIcon | undefined {\n const documentType = document.header.documentType;\n\n switch (documentType) {\n case \"powerhouse/document-model\":\n return \"document-model\";\n case \"powerhouse/app\":\n return \"app\";\n case \"powerhouse/document-editor\":\n return \"editor\";\n case \"powerhouse/subgraph\":\n return \"subgraph\";\n case \"powerhouse/package\":\n return \"package\";\n case \"powerhouse/processor\": {\n // Check the processor type from global state (safely)\n const globalState = (document.state as { global?: { type?: string } })\n .global;\n const processorType = globalState?.type;\n\n if (processorType === \"analytics\") return \"analytics-processor\";\n if (processorType === \"relational\") return \"relational-processor\";\n if (processorType === \"codegen\") return \"codegen-processor\";\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\nexport function downloadFile(document: PHDocument, fileName: string) {\n const zip = createZip(document);\n zip\n .generateAsync({ type: \"blob\" })\n .then((blob) => {\n const link = window.document.createElement(\"a\");\n link.style.display = \"none\";\n link.href = URL.createObjectURL(blob);\n link.download = fileName;\n\n window.document.body.appendChild(link);\n link.click();\n\n window.document.body.removeChild(link);\n })\n .catch(logger.error);\n}\n\nasync function getDocumentExtension(document: PHDocument): Promise<string> {\n const documentType = document.header.documentType;\n\n // DocumentModel definitions always use \"phdm\"\n if (documentType === documentModelDocumentType) {\n return \"phdm\";\n }\n\n let rawExtension: string | undefined;\n\n const reactorClient = window.ph?.reactorClient;\n if (reactorClient) {\n const { results: documentModelModules } =\n await reactorClient.getDocumentModelModules();\n const module = documentModelModules.find(\n (m: DocumentModelModule) => m.documentModel.global.id === documentType,\n );\n rawExtension = module?.utils.fileExtension;\n }\n\n // Clean the extension (remove leading/trailing dots) and fallback to \"phdm\"\n const cleanExtension = (rawExtension ?? \"phdm\").replace(/^\\.+|\\.+$/g, \"\");\n return cleanExtension || \"phdm\";\n}\n\nconst BASE_STATE_KEYS = new Set([\"auth\", \"document\"]);\n\n/**\n * Fetches all operations for a document using cursor-based pagination.\n * The reactor client handles multi-scope cursors transparently via\n * composite cursors, so all scopes are fetched in a single paginated stream.\n */\nexport async function fetchDocumentOperations(\n reactorClient: IReactorClient,\n document: PHDocument,\n pageSize = 100,\n): Promise<DocumentOperations> {\n const scopes = Object.keys(document.state).filter(\n (k) => !BASE_STATE_KEYS.has(k),\n );\n const operations: DocumentOperations = {};\n for (const scope of scopes) {\n operations[scope] = [];\n }\n\n let cursor = \"\";\n\n do {\n const page = await reactorClient.getOperations(\n document.header.id,\n { scopes },\n undefined,\n { cursor, limit: pageSize },\n );\n\n for (const op of page.results) {\n const scope = op.action.scope ?? \"global\";\n if (operations[scope]) {\n operations[scope].push(op);\n }\n }\n\n cursor = page.nextCursor ?? \"\";\n } while (cursor);\n\n return operations;\n}\n\nexport async function exportFile(document: PHDocument, suggestedName?: string) {\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Fetch operations page-by-page (document from reactor has operations: {})\n const operations = await fetchDocumentOperations(reactorClient, document);\n const documentWithOps = { ...document, operations };\n\n // Get the extension from the document model module\n const extension = await getDocumentExtension(documentWithOps);\n\n const name = `${suggestedName || documentWithOps.header.name || \"Untitled\"}.${extension}.phd`;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!window.showSaveFilePicker) {\n return downloadFile(documentWithOps, name);\n }\n try {\n const fileHandle = await window.showSaveFilePicker({\n suggestedName: name,\n });\n\n await baseSaveToFileHandle(documentWithOps, fileHandle);\n return fileHandle;\n } catch (e) {\n // ignores error if user cancelled the file picker\n if (!(e instanceof DOMException && e.name === \"AbortError\")) {\n throw e;\n }\n }\n}\n\nexport async function loadFile(path: string | File) {\n const baseDocument = await baseLoadFromInput(\n path,\n (state: PHDocument) => state,\n { checkHashes: true },\n );\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n const { results: documentModelModules } =\n await reactorClient.getDocumentModelModules();\n const documentModelModule = documentModelModules.find(\n (module) =>\n module.documentModel.global.id === baseDocument.header.documentType,\n );\n if (!documentModelModule) {\n throw new DocumentModelNotFoundError(baseDocument.header.documentType);\n }\n return documentModelModule.utils.loadFromInput(path);\n}\n\nexport async function addDocument(\n driveId: string,\n name: string,\n documentType: string,\n parentFolder?: string,\n document?: PHDocument,\n id?: string,\n preferredEditor?: string,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // get the module\n const documentModelModule =\n await reactorClient.getDocumentModelModule(documentType);\n\n // create - use passed document's state if available\n const newDocument = documentModelModule.utils.createDocument({\n ...document?.state,\n });\n newDocument.header.name = name;\n\n // Create document using ReactorClient\n let newDoc: PHDocument;\n try {\n newDoc = await reactorClient.createDocumentInDrive(\n driveId,\n newDocument,\n parentFolder,\n );\n } catch (e) {\n logger.error(\"Error adding document\", e);\n throw new Error(\"There was an error adding document\");\n }\n\n // Return a file node structure for compatibility\n return {\n id: newDoc.header.id,\n name: newDoc.header.name,\n documentType,\n parentFolder: parentFolder ?? null,\n kind: \"file\" as const,\n };\n}\n\nexport async function addFile(\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n) {\n logger.verbose(\n `addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`,\n );\n\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create files\");\n }\n\n const document = await loadFile(file);\n\n let duplicateId = false;\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n try {\n await reactorClient.get(document.header.id);\n duplicateId = true;\n } catch {\n // document id not found\n }\n\n const documentId = duplicateId ? generateId() : document.header.id;\n const header = createPresignedHeader(\n documentId,\n document.header.documentType,\n );\n header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n header.meta = document.header.meta;\n header.name = name || document.header.name;\n\n // copy the document at it's initial state\n const initialDocument = {\n ...document,\n header,\n state: document.initialState,\n operations: Object.keys(document.operations).reduce((acc, key) => {\n acc[key] = [];\n return acc;\n }, {} as DocumentOperations),\n };\n\n await addDocument(\n driveId,\n name || document.header.name,\n document.header.documentType,\n parentFolder,\n initialDocument,\n documentId,\n document.header.meta?.preferredEditor,\n );\n\n // then add all the operations in chunks\n await uploadOperations(documentId, document.operations, queueOperations);\n}\n\nexport async function addFileWithProgress(\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n onProgress?: FileUploadProgressCallback,\n documentTypes?: string[],\n resolveConflict?: ConflictResolution,\n) {\n logger.verbose(\n `addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`,\n );\n const reactor = window.ph?.reactorClient;\n if (!reactor) {\n return;\n }\n\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create files\");\n }\n\n // Loading stage (0-10%)\n try {\n onProgress?.({ stage: \"loading\", progress: 0 });\n let document: PHDocument;\n try {\n document = await loadFile(file);\n } catch (loadError) {\n // Only attempt discovery if the failure is specifically a missing\n // document model module, not for other errors like corrupt files.\n const discoveryService = window.ph?.packageDiscoveryService;\n if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {\n // Trigger discovery and retry without blocking the drop handler\n void retryAfterDiscovery(\n discoveryService,\n loadError.documentType,\n file,\n driveId,\n name,\n parentFolder,\n onProgress,\n documentTypes,\n resolveConflict,\n );\n return;\n }\n throw loadError;\n }\n\n // Check for duplicate in same location\n const duplicateCheck = await isDocumentInLocation(\n document,\n driveId,\n parentFolder,\n );\n\n if (duplicateCheck.isDuplicate && !resolveConflict) {\n // Report conflict and return early\n onProgress?.({\n stage: \"conflict\",\n progress: 0,\n duplicateType: duplicateCheck.duplicateType,\n });\n return undefined;\n }\n\n // Handle replace resolution by deleting the existing document\n if (\n duplicateCheck.isDuplicate &&\n resolveConflict === \"replace\" &&\n duplicateCheck.nodeId\n ) {\n await deleteNode(driveId, duplicateCheck.nodeId);\n }\n // For \"duplicate\" resolution, we continue normally which creates a new document\n // with a different ID (the default behavior)\n\n // Send documentType info immediately after loading\n const documentType = getDocumentTypeIcon(document);\n if (documentType) {\n onProgress?.({ stage: \"loading\", progress: 10, documentType });\n } else {\n onProgress?.({ stage: \"loading\", progress: 10 });\n }\n\n if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {\n onProgress?.({\n stage: \"unsupported-document-type\",\n progress: 100,\n error: `Document type ${document.header.documentType} is not supported`,\n });\n throw new UnsupportedDocumentTypeError(document.header.documentType);\n }\n\n // ensure we have the module + can load it (throws if not found)\n await reactor.getDocumentModelModule(document.header.documentType);\n\n // Initializing stage (10-20%)\n onProgress?.({ stage: \"initializing\", progress: 10 });\n\n let duplicateId = false;\n try {\n await reactor.get(document.header.id);\n duplicateId = true;\n } catch {\n // document id not found\n }\n\n const documentId = duplicateId ? generateId() : document.header.id;\n const header = createPresignedHeader(\n documentId,\n document.header.documentType,\n );\n header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n header.meta = document.header.meta;\n header.name = name || document.header.name;\n\n // copy the document at it's initial state\n const initialDocument = {\n ...document,\n header,\n state: document.initialState,\n operations: Object.keys(document.operations).reduce((acc, key) => {\n acc[key] = [];\n return acc;\n }, {} as DocumentOperations),\n };\n\n const fileNode = await addDocument(\n driveId,\n name || document.header.name,\n document.header.documentType,\n parentFolder,\n initialDocument,\n documentId,\n document.header.meta?.preferredEditor,\n );\n\n if (!fileNode) {\n throw new Error(\"There was an error adding file\");\n }\n\n onProgress?.({ stage: \"initializing\", progress: 20 });\n\n // Uploading stage (20-100%)\n await uploadOperations(documentId, document.operations, queueOperations, {\n onProgress: (uploadProgress) => {\n if (\n uploadProgress.totalOperations &&\n uploadProgress.uploadedOperations !== undefined\n ) {\n const uploadPercent =\n uploadProgress.totalOperations > 0\n ? uploadProgress.uploadedOperations /\n uploadProgress.totalOperations\n : 0;\n const overallProgress = 20 + Math.round(uploadPercent * 80);\n onProgress?.({\n stage: \"uploading\",\n progress: overallProgress,\n totalOperations: uploadProgress.totalOperations,\n uploadedOperations: uploadProgress.uploadedOperations,\n });\n }\n },\n });\n\n onProgress?.({ stage: \"complete\", progress: 100, fileNode });\n\n return fileNode;\n } catch (error) {\n // Don't override unsupported-document-type status\n if (!UnsupportedDocumentTypeError.isError(error)) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n onProgress?.({\n stage: \"failed\",\n progress: 100,\n error: errorMessage,\n });\n }\n throw error;\n }\n}\n\nasync function retryAfterDiscovery(\n discoveryService: NonNullable<typeof window.ph>[\"packageDiscoveryService\"],\n documentType: string,\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n onProgress?: FileUploadProgressCallback,\n documentTypes?: string[],\n resolveConflict?: ConflictResolution,\n): Promise<void> {\n if (!discoveryService) return;\n try {\n await discoveryService.load(documentType);\n } catch {\n onProgress?.({\n stage: \"unsupported-document-type\",\n progress: 100,\n error: `Document type ${documentType} is not supported`,\n });\n return;\n }\n await addFileWithProgress(\n file,\n driveId,\n name,\n parentFolder,\n onProgress,\n documentTypes,\n resolveConflict,\n );\n}\n\nexport async function updateFile(\n driveId: string,\n nodeId: string,\n documentType?: string,\n name?: string,\n parentFolder?: string,\n) {\n const reactor = window.ph?.reactorClient;\n if (!reactor) {\n return;\n }\n const { isAllowedToCreateDocuments } = getUserPermissions();\n\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to update files\");\n }\n const drive = await reactor.get<DocumentDriveDocument>(driveId);\n const unsafeCastAsDrive = (await queueActions(\n drive,\n baseUpdateFile({\n id: nodeId,\n name: name ?? undefined,\n parentFolder,\n documentType,\n }),\n )) as DocumentDriveDocument;\n\n const node = unsafeCastAsDrive.state.global.nodes.find(\n (node) => node.id === nodeId,\n );\n if (!node || !isFileNode(node)) {\n throw new Error(\"There was an error updating document\");\n }\n return node;\n}\n\nexport async function addFolder(\n driveId: string,\n name: string,\n parentFolder?: string,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create folders\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Get the drive document and add folder action\n const drive = await reactorClient.get<DocumentDriveDocument>(driveId);\n const folderId = generateId();\n const updatedDrive = await reactorClient.execute<DocumentDriveDocument>(\n driveId,\n \"main\",\n [\n baseAddFolder({\n id: folderId,\n name,\n parentFolder,\n }),\n ],\n );\n\n const node = updatedDrive.state.global.nodes.find(\n (node) => node.id === folderId,\n );\n if (!node || !isFolderNode(node)) {\n throw new Error(\"There was an error adding folder\");\n }\n return node;\n}\n\nexport async function deleteNode(driveId: string, nodeId: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to delete documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // delete the node in the drive document\n await reactorClient.execute(driveId, \"main\", [\n baseDeleteNode({ id: nodeId }),\n ]);\n\n // now delete the document\n await reactorClient.deleteDocument(nodeId);\n}\n\nexport async function renameNode(\n driveId: string,\n nodeId: string,\n name: string,\n): Promise<Node | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Rename the node in the drive document using updateNode action\n const drive = await reactorClient.execute<DocumentDriveDocument>(\n driveId,\n \"main\",\n [updateNode({ id: nodeId, name })],\n );\n\n const node = drive.state.global.nodes.find((n) => n.id === nodeId);\n if (!node) {\n throw new Error(\"There was an error renaming node\");\n }\n return node;\n}\n\nexport async function renameDriveNode(\n driveId: string,\n nodeId: string,\n name: string,\n): Promise<Node | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n await reactorClient.execute(driveId, \"main\", [\n updateNode({ id: nodeId, name }),\n ]);\n\n const drive = await reactorClient.get<DocumentDriveDocument>(driveId);\n return drive.state.global.nodes.find((n: Node) => n.id === nodeId);\n}\n\nexport async function moveNode(\n driveId: string,\n src: Node,\n target: Node | undefined,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to move documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Get current parent folder from source node\n const sourceParent = src.parentFolder ?? driveId;\n const targetParent = target?.id ?? driveId;\n\n return await reactorClient.moveChildren(sourceParent, targetParent, [src.id]);\n}\n\nasync function _duplicateDocument(\n reactor: IReactorClient,\n document: PHDocument,\n newId = generateId(),\n) {\n const documentModule = await reactor.getDocumentModelModule(\n document.header.documentType,\n );\n\n return replayDocument(\n document.initialState,\n document.operations,\n documentModule.reducer,\n createPresignedHeader(newId, document.header.documentType),\n );\n}\n\nexport async function copyNode(\n driveId: string,\n src: Node,\n target: Node | undefined,\n) {\n const reactor = window.ph?.reactorClient;\n if (!reactor) {\n return;\n }\n const { isAllowedToCreateDocuments } = getUserPermissions();\n\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to copy documents\");\n }\n\n const drive = await reactor.get<DocumentDriveDocument>(driveId);\n\n const copyNodesInput = generateNodesCopy(\n {\n srcId: src.id,\n targetParentFolder: target?.id,\n targetName: src.name,\n },\n () => generateId(),\n drive.state.global.nodes,\n );\n\n // Pre-calculate collision-resolved names for all nodes to be copied\n const resolvedNamesMap = new Map<string, string>();\n for (const copyNodeInput of copyNodesInput) {\n const node = drive.state.global.nodes.find(\n (n) => n.id === copyNodeInput.srcId,\n );\n if (node) {\n const resolvedName = handleTargetNameCollisions({\n nodes: drive.state.global.nodes,\n srcName: copyNodeInput.targetName || node.name,\n targetParentFolder: copyNodeInput.targetParentFolder || null,\n });\n resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);\n }\n }\n\n const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {\n const node = drive.state.global.nodes.find(\n (node) => node.id === copyNodeInput.srcId,\n );\n return node !== undefined && isFileNode(node);\n });\n\n for (const fileNodeToCopy of fileNodesToCopy) {\n try {\n const document = await reactor.get(fileNodeToCopy.srcId);\n\n const duplicatedDocument = await _duplicateDocument(\n reactor,\n document,\n fileNodeToCopy.targetId,\n );\n\n // Set the header name to match the collision-resolved node name\n const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);\n if (resolvedName) {\n duplicatedDocument.header.name = resolvedName;\n }\n\n await reactor.createDocumentInDrive(\n driveId,\n duplicatedDocument,\n target?.id,\n );\n } catch (e) {\n logger.error(\n `Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`,\n );\n }\n }\n\n const copyActions = copyNodesInput.map((copyNodeInput) =>\n baseCopyNode(copyNodeInput),\n );\n return await queueActions(drive, copyActions);\n}\n","import { driveCollectionId } from \"@powerhousedao/reactor\";\nimport {\n driveCreateDocument,\n setAvailableOffline,\n setSharingType,\n type DocumentDriveDocument,\n type DriveInput,\n type SharingType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { getUserPermissions } from \"../utils/user.js\";\n\nexport async function addDrive(input: DriveInput, preferredEditor?: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create drives\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const driveDoc = driveCreateDocument({\n global: {\n name: input.global.name || \"\",\n icon: input.global.icon ?? null,\n nodes: [],\n },\n });\n\n if (preferredEditor) {\n driveDoc.header.meta = { preferredEditor };\n }\n\n return await reactorClient.create<DocumentDriveDocument>(driveDoc);\n}\n\nexport async function addRemoteDrive(url: string, driveId?: string) {\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const sync =\n window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n if (!sync) {\n throw new Error(\"Sync not initialized\");\n }\n\n // Fetch drive info from the REST endpoint to get both id and graphqlEndpoint\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to resolve drive info from ${url}`);\n }\n const driveInfo = (await response.json()) as {\n id: string;\n graphqlEndpoint: string;\n };\n\n const resolvedDriveId = driveId ?? driveInfo.id;\n const collectionId = driveCollectionId(\"main\", resolvedDriveId);\n\n const existingRemote = sync\n .list()\n .find((remote) => remote.collectionId === collectionId);\n if (existingRemote) {\n return resolvedDriveId;\n }\n\n const remoteName = crypto.randomUUID();\n\n await sync.add(remoteName, collectionId, {\n type: \"gql\",\n parameters: {\n url: driveInfo.graphqlEndpoint,\n },\n });\n\n return resolvedDriveId;\n}\n\nexport async function deleteDrive(driveId: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to delete drives\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n await reactorClient.deleteDocument(driveId);\n}\n\nexport async function renameDrive(\n driveId: string,\n name: string,\n): Promise<PHDocument | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename drives\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n return await reactorClient.rename(driveId, name);\n}\n\nexport async function setDriveAvailableOffline(\n driveId: string,\n availableOffline: boolean,\n): Promise<PHDocument | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to change drive availability\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n return await reactorClient.execute(driveId, \"main\", [\n setAvailableOffline({ availableOffline }),\n ]);\n}\n\nexport async function setDriveSharingType(\n driveId: string,\n sharingType: SharingType,\n): Promise<PHDocument | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to change drive sharing type\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n return await reactorClient.execute(driveId, \"main\", [\n setSharingType({ type: sharingType }),\n ]);\n}\n","import type { PowerhouseGlobal } from \"./types.js\";\n\nexport function getGlobal<K extends keyof PowerhouseGlobal>(\n namespace: K,\n): PowerhouseGlobal[K] | undefined {\n if (typeof window === \"undefined\") return undefined;\n return window.powerhouse?.[namespace];\n}\n\nexport function setGlobal<K extends keyof PowerhouseGlobal>(\n namespace: K,\n value: PowerhouseGlobal[K],\n): void {\n if (typeof window === \"undefined\") return;\n window.powerhouse = window.powerhouse || {};\n window.powerhouse[namespace] = value;\n}\n\nexport function clearGlobal(namespace: keyof PowerhouseGlobal): void {\n if (typeof window === \"undefined\") return;\n\n if (window.powerhouse?.[namespace]) {\n delete window.powerhouse[namespace];\n if (Object.keys(window.powerhouse).length === 0) {\n delete window.powerhouse;\n }\n }\n}\n","import type { BrowserAnalyticsStoreOptions } from \"@powerhousedao/analytics-engine-browser\";\nimport { BrowserAnalyticsStore } from \"@powerhousedao/analytics-engine-browser\";\nimport type { IAnalyticsStore } from \"@powerhousedao/analytics-engine-core\";\nimport { AnalyticsQueryEngine } from \"@powerhousedao/analytics-engine-core\";\nimport {\n QueryClient,\n QueryClientProvider,\n useMutation,\n useQuery,\n useQueryClient,\n useSuspenseQuery,\n} from \"@tanstack/react-query\";\nimport { childLogger } from \"document-model\";\nimport type { PropsWithChildren } from \"react\";\nimport { useEffect } from \"react\";\nimport { getGlobal } from \"../global/core.js\";\n\nconst logger = childLogger([\"reactor-browser\", \"analytics\", \"provider\"]);\n\nconst defaultQueryClient = new QueryClient();\n\ntype CreateStoreOptions = BrowserAnalyticsStoreOptions;\n\nexport const analyticsOptionsKey = [\"analytics\", \"options\"] as const;\nexport const analyticsStoreKey = [\"analytics\", \"store\"] as const;\nexport const analyticsEngineKey = [\"analytics\", \"store\"] as const;\n\nexport async function createAnalyticsStore(options: CreateStoreOptions) {\n const store = new BrowserAnalyticsStore(options);\n await store.init();\n\n const engine = new AnalyticsQueryEngine(store);\n return {\n store,\n engine,\n options,\n };\n}\n\nexport async function getAnalyticsStore(): Promise<IAnalyticsStore | null> {\n const globalAnalytics = await getGlobal(\"analytics\");\n\n return globalAnalytics?.store ?? null;\n}\n\nexport function useAnalyticsStoreOptions() {\n return useQuery<CreateStoreOptions | undefined>({\n queryKey: analyticsOptionsKey,\n }).data;\n}\n\nexport function useCreateAnalyticsStore(options?: CreateStoreOptions) {\n const queryClient = useQueryClient();\n useEffect(() => {\n queryClient.setQueryDefaults(analyticsOptionsKey, {\n queryFn: () => options,\n staleTime: Infinity,\n gcTime: Infinity,\n });\n }, [queryClient, options]);\n\n return useMutation({\n mutationFn: async () => {\n const store = getAnalyticsStore();\n queryClient.setQueryDefaults(analyticsStoreKey, {\n queryFn: () => store,\n staleTime: Infinity,\n gcTime: Infinity,\n });\n return store;\n },\n });\n}\n\nexport function useAnalyticsStoreQuery(options?: CreateStoreOptions) {\n return useSuspenseQuery({\n queryKey: [analyticsStoreKey, options],\n queryFn: () => getAnalyticsStore(),\n retry: true,\n });\n}\n\nexport function useAnalyticsStore(options?: CreateStoreOptions) {\n const store = useAnalyticsStoreQuery(options);\n return store.data;\n}\n\nexport function useAnalyticsStoreAsync(options?: CreateStoreOptions) {\n return useQuery({\n queryKey: [analyticsStoreKey, options],\n queryFn: () => getAnalyticsStore(),\n retry: true,\n throwOnError: false,\n });\n}\n\ninterface BaseAnalyticsProviderProps extends PropsWithChildren {\n /**\n * Custom QueryClient instance\n * @default undefined\n */\n queryClient?: QueryClient;\n}\n\ntype CreateAnalyticsStoreProps =\n | {\n options?: CreateStoreOptions;\n }\n | {\n databaseName?: string;\n };\n\ntype AnalyticsProviderProps = BaseAnalyticsProviderProps &\n CreateAnalyticsStoreProps;\n\nfunction CreateAnalyticsStore() {\n const { mutate } = useCreateAnalyticsStore();\n\n useEffect(() => {\n mutate();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsProvider({\n children,\n queryClient = defaultQueryClient,\n ...props\n}: AnalyticsProviderProps) {\n return (\n <QueryClientProvider client={queryClient}>\n <CreateAnalyticsStore />\n {children}\n </QueryClientProvider>\n );\n}\n\nexport function useAnalyticsEngine(): AnalyticsQueryEngine | undefined {\n return useSuspenseQuery({\n queryKey: analyticsEngineKey,\n queryFn: async () => {\n const globalAnalytics = getGlobal(\"analytics\");\n if (!globalAnalytics) {\n throw new Error(\"No analytics store available\");\n }\n return (await globalAnalytics).engine;\n },\n retry: false,\n }).data;\n}\n\nexport function useAnalyticsEngineAsync() {\n return useQuery({\n queryKey: analyticsEngineKey,\n queryFn: async () => {\n const globalAnalytics = getGlobal(\"analytics\");\n if (!globalAnalytics) {\n throw new Error(\"No analytics store available\");\n }\n return (await globalAnalytics).engine;\n },\n retry: false,\n });\n}\n","import type {\n AnalyticsQuery,\n AnalyticsQueryEngine,\n AnalyticsSeries,\n AnalyticsSeriesInput,\n AnalyticsSeriesQuery,\n GroupedPeriodResults,\n IAnalyticsStore,\n} from \"@powerhousedao/analytics-engine-core\";\nimport { AnalyticsPath } from \"@powerhousedao/analytics-engine-core\";\nimport type {\n UseMutationOptions,\n UseQueryOptions,\n UseQueryResult,\n} from \"@tanstack/react-query\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect } from \"react\";\nimport {\n getAnalyticsStore,\n useAnalyticsEngineAsync,\n useAnalyticsStoreAsync,\n useAnalyticsStoreOptions,\n} from \"../context.js\";\n\nfunction useAnalyticsQueryWrapper<TQueryFnData = unknown, TData = TQueryFnData>(\n options: Omit<UseQueryOptions<TQueryFnData, Error, TData>, \"queryFn\"> & {\n queryFn: (analytics: {\n store: IAnalyticsStore;\n engine: AnalyticsQueryEngine;\n }) => Promise<TQueryFnData> | TQueryFnData;\n },\n) {\n const { queryFn, ...queryOptions } = options;\n const { data: store } = useAnalyticsStoreAsync();\n const { data: engine } = useAnalyticsEngineAsync();\n const enabled =\n \"enabled\" in queryOptions ? queryOptions.enabled : !!store && !!engine;\n\n return useQuery({\n ...queryOptions,\n enabled,\n queryFn: async () => {\n if (!store || !engine) {\n throw new Error(\n \"No analytics store available. Use within an AnalyticsProvider.\",\n );\n }\n return await queryFn({ store, engine });\n },\n });\n}\n\nfunction useAnalyticsMutationWrapper<TVariables, TData>(\n options: Omit<UseMutationOptions<TData, Error, TVariables>, \"mutationFn\"> & {\n mutationFn: (\n variables: TVariables,\n context: {\n store: IAnalyticsStore;\n },\n ) => Promise<TData> | TData;\n },\n) {\n const { mutationFn, ...mutationOptions } = options;\n const storeOptions = useAnalyticsStoreOptions();\n\n return useMutation({\n ...mutationOptions,\n mutationFn: async (value: TVariables) => {\n let store: IAnalyticsStore | null = null;\n try {\n store = await getAnalyticsStore();\n } catch (e) {\n console.error(e);\n }\n\n if (!store) {\n throw new Error(\n \"No analytics store available. Use within an AnalyticsProvider.\",\n );\n }\n return await mutationFn(value, { store });\n },\n });\n}\n\nexport type UseAnalyticsQueryOptions<TData = GroupedPeriodResults> = Omit<\n UseQueryOptions<GroupedPeriodResults, Error, TData>,\n \"queryKey\" | \"queryFn\"\n> & {\n sources?: AnalyticsPath[];\n};\n\nexport type UseAnalyticsQueryResult<TData = GroupedPeriodResults> =\n UseQueryResult<TData>;\n\nconst DEBOUNCE_INTERVAL = 200;\n\nexport function useAnalyticsQuery<TData = GroupedPeriodResults>(\n query: AnalyticsQuery,\n options?: UseAnalyticsQueryOptions<TData>,\n): UseAnalyticsQueryResult<TData> {\n const { data: store } = useAnalyticsStoreAsync();\n const queryClient = useQueryClient();\n const sources = options?.sources ?? [];\n\n const result = useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"query\", query],\n queryFn: ({ engine }) => engine.execute(query),\n ...options,\n });\n\n useEffect(() => {\n if (!sources.length || !store) {\n return;\n }\n\n const subscriptions = new Array<() => void>();\n // Debounce invalidateQueries so it's not called too frequently\n let invalidateTimeout: ReturnType<typeof setTimeout> | null = null;\n const debouncedInvalidate = () => {\n if (invalidateTimeout) clearTimeout(invalidateTimeout);\n invalidateTimeout = setTimeout(() => {\n queryClient\n .invalidateQueries({\n queryKey: [\"analytics\", \"query\", query],\n })\n .catch((e) => {\n console.error(e);\n });\n }, DEBOUNCE_INTERVAL);\n };\n\n sources.forEach((path) => {\n const unsub = store.subscribeToSource(path, debouncedInvalidate);\n subscriptions.push(unsub);\n });\n\n // Unsubscribes from store when component unmounts or dependencies change\n return () => {\n subscriptions.forEach((unsub) => unsub());\n };\n }, [query, store, sources]);\n\n return result;\n}\n\nexport type UseAnalyticsSeriesOptions = Omit<\n UseQueryOptions<AnalyticsSeries[], Error, AnalyticsSeries[]>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useAnalyticsSeries(\n query: AnalyticsSeriesQuery,\n options?: UseAnalyticsSeriesOptions,\n) {\n return useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"series\", query],\n queryFn: ({ store }) => store.getMatchingSeries(query),\n ...options,\n });\n}\n\nexport type UseAddSeriesValueOptions = Omit<\n UseMutationOptions<void, Error, AnalyticsSeriesInput>,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useAddSeriesValue(options?: UseAddSeriesValueOptions) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"addSeries\"],\n mutationFn: async (value, { store }) => {\n return await store.addSeriesValue(value);\n },\n ...options,\n });\n}\n\nexport type UseClearSeriesBySourceOptions = Omit<\n UseMutationOptions<\n number,\n Error,\n { source: AnalyticsPath; cleanUpDimensions?: boolean }\n >,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useClearSeriesBySource(\n options?: UseClearSeriesBySourceOptions,\n) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"clearSeries\"],\n mutationFn: async ({ source, cleanUpDimensions }, { store }) => {\n return store.clearSeriesBySource(source, cleanUpDimensions);\n },\n ...options,\n });\n}\n\nexport type UseClearEmptyAnalyticsDimensionsOptions = Omit<\n UseMutationOptions<number>,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useClearEmptyAnalyticsDimensions(\n options?: UseClearEmptyAnalyticsDimensionsOptions,\n) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"clearEmptyDimensions\"],\n mutationFn: async (_, { store }) => {\n return store.clearEmptyAnalyticsDimensions();\n },\n ...options,\n });\n}\n\nexport type UseAddSeriesValuesOptions = Omit<\n UseMutationOptions<void, Error, AnalyticsSeriesInput[]>,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useAddSeriesValues(options?: UseAddSeriesValuesOptions) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"addSeriesValues\"],\n mutationFn: async (values, { store }) => {\n return store.addSeriesValues(values);\n },\n ...options,\n });\n}\n\nexport type UseGetDimensionsOptions<TData> = Omit<\n UseQueryOptions<any, Error, TData>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useGetDimensions<TData = any>(\n options?: UseGetDimensionsOptions<TData>,\n) {\n return useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"dimensions\"],\n queryFn: ({ store }) => store.getDimensions(),\n ...options,\n });\n}\n\nexport type UseMatchingSeriesOptions = Omit<\n UseQueryOptions<AnalyticsSeries[], Error, AnalyticsSeries[]>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useMatchingSeries(\n query: AnalyticsSeriesQuery,\n options?: UseMatchingSeriesOptions,\n) {\n const result = useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"matchingSeries\", query],\n queryFn: ({ store }) => store.getMatchingSeries(query),\n ...options,\n });\n\n return result;\n}\n\nexport type UseQuerySourcesOptions = Omit<\n UseQueryOptions<AnalyticsPath[] | undefined>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useQuerySources(\n query: AnalyticsSeriesQuery,\n options?: UseQuerySourcesOptions,\n) {\n const { data: matchingSeries } = useMatchingSeries(query);\n\n return useQuery({\n queryKey: [\"analytics\", \"sources\", query],\n queryFn: () => {\n if (!matchingSeries?.length) {\n return [];\n }\n const uniqueSources = [\n ...new Set(matchingSeries.map((s) => s.source.toString())),\n ];\n return uniqueSources.map((source) => AnalyticsPath.fromString(source));\n },\n enabled: !!matchingSeries,\n ...options,\n });\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 logger.error,\n );\n }\n return [document, dispatch] as const;\n}\n","import {\n DocumentChangeType,\n type DocumentChangeEvent,\n type IReactorClient,\n} from \"@powerhousedao/reactor\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport type {\n FulfilledPromise,\n IDocumentCache,\n PromiseState,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.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 * Document cache implementation that uses the new ReactorClient API.\n *\n * This cache subscribes to document change events via IReactorClient.subscribe()\n * and automatically updates the cache when documents are created, updated, or deleted.\n */\nexport class DocumentCache implements IDocumentCache {\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 private unsubscribe: (() => void) | null = null;\n\n constructor(private client: IReactorClient) {\n this.unsubscribe = client.subscribe({}, (event: DocumentChangeEvent) => {\n this.handleDocumentChange(event);\n });\n }\n\n private handleDocumentChange(event: DocumentChangeEvent): void {\n if (event.type === DocumentChangeType.Deleted) {\n const documentId = event.context?.childId;\n if (documentId) {\n this.handleDocumentDeleted(documentId);\n }\n } else if (event.type === DocumentChangeType.Updated) {\n for (const doc of event.documents) {\n this.handleDocumentUpdated(doc.header.id).catch(console.warn);\n }\n }\n }\n\n private handleDocumentDeleted(documentId: string): void {\n const listeners = this.listeners.get(documentId);\n this.documents.delete(documentId);\n this.invalidateBatchesContaining(documentId);\n if (listeners) {\n listeners.forEach((listener) => listener());\n }\n this.listeners.delete(documentId);\n }\n\n private async handleDocumentUpdated(documentId: string): Promise<void> {\n if (this.documents.has(documentId)) {\n await this.get(documentId, true);\n const listeners = this.listeners.get(documentId);\n if (listeners) {\n listeners.forEach((listener) => listener());\n }\n }\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) {\n if (currentData.status === \"pending\") {\n return currentData;\n }\n if (!refetch) {\n return currentData;\n }\n }\n\n const documentPromise = this.client.get(id);\n this.documents.set(id, addPromiseState(documentPromise));\n return documentPromise;\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 = Promise.all(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 allFulfilled = states.every((s) => s.status === \"fulfilled\");\n\n if (allFulfilled) {\n const values = states.map(\n (s) => (s as { status: \"fulfilled\"; value: PHDocument }).value,\n );\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 = Promise.all(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 /**\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 }\n}\n","import type {\n PHGlobal,\n PHGlobalKey,\n SetEvent,\n} from \"@powerhousedao/reactor-browser\";\nimport { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\n\n// guard condition for server side rendering\nconst isServer = typeof window === \"undefined\";\n\nexport function makePHEventFunctions<TKey extends PHGlobalKey>(key: TKey) {\n const setEventName = `ph:set${capitalCase(key)}` as const;\n const updateEventName = `ph:${key}Updated` as const;\n\n function setValue(value: PHGlobal[TKey] | undefined) {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(setEventName, {\n detail: { [key]: value },\n });\n window.dispatchEvent(event);\n }\n\n function dispatchUpdatedEvent() {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(updateEventName);\n window.dispatchEvent(event);\n }\n\n function handleSetValueEvent(event: SetEvent<TKey>) {\n if (isServer) {\n return;\n }\n const value = event.detail[key];\n if (!window.ph) {\n window.ph = {};\n }\n window.ph[key] = value;\n dispatchUpdatedEvent();\n }\n\n function addEventHandler() {\n if (isServer) {\n return;\n }\n window.addEventListener(setEventName, handleSetValueEvent as EventListener);\n }\n\n function subscribeToValue(onStoreChange: () => void) {\n if (isServer) return () => {};\n window.addEventListener(updateEventName, onStoreChange);\n return () => {\n window.removeEventListener(updateEventName, onStoreChange);\n };\n }\n\n function getSnapshot() {\n if (isServer) {\n return undefined;\n }\n if (!window.ph) {\n console.warn(\n `ph global store is not initialized. Did you call set${capitalCase(key)}?`,\n );\n return undefined;\n }\n return window.ph[key];\n }\n\n function getServerSnapshot() {\n return undefined;\n }\n\n function useValue() {\n return useSyncExternalStore(\n subscribeToValue,\n getSnapshot,\n getServerSnapshot,\n );\n }\n\n return {\n useValue,\n setValue,\n addEventHandler,\n };\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { use, useCallback, useSyncExternalStore } from \"react\";\nimport { readPromiseState } from \"../document-cache.js\";\nimport type { IDocumentCache } 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 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 */\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 } as const;\n }\n\n const promise = documentCache.get(id);\n const state = getDocumentQueryState(promise);\n\n return { ...state, reload: () => documentCache.get(id, true) } 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","import type { GroupedPeriodResults } from \"@powerhousedao/analytics-engine-core\";\nimport {\n AnalyticsGranularity,\n AnalyticsPath,\n} from \"@powerhousedao/analytics-engine-core\";\nimport { DateTime } from \"luxon\";\nimport type { UseAnalyticsQueryResult } from \"./analytics-query.js\";\nimport { useAnalyticsQuery } from \"./analytics-query.js\";\n\nconst getBarSize = (value: number) => {\n if (value <= 0) return 0;\n if (value > 0 && value <= 50) return 1;\n if (value > 50 && value <= 100) return 2;\n if (value > 100 && value <= 250) return 3;\n return 4;\n};\n\n// Define types for our timeline items\ntype BarItem = {\n id: string;\n type: \"bar\";\n addSize: 0 | 1 | 2 | 3 | 4;\n delSize: 0 | 1 | 2 | 3 | 4;\n additions: number;\n deletions: number;\n timestampUtcMs: string;\n startDate: Date;\n endDate: Date;\n revision?: number;\n};\n\ntype DividerItem = {\n id: string;\n type: \"divider\";\n revision?: number;\n startDate?: Date;\n endDate?: Date;\n};\n\ntype TimelineItem = BarItem | DividerItem;\n\nfunction addItemsDividers(items: BarItem[]): TimelineItem[] {\n if (!items.length) return [];\n\n const result: TimelineItem[] = [];\n items.forEach((item, index) => {\n result.push(item);\n\n // Check if there's a next item and if they're not in consecutive hours\n if (index < items.length - 1) {\n const currentDate = new Date(item.startDate);\n const nextDate = new Date(items[index + 1].startDate);\n\n const currentHour = currentDate.getHours();\n const nextHour = nextDate.getHours();\n\n // Get day parts (without time) for comparison\n const currentDay = currentDate.toDateString();\n const nextDay = nextDate.toDateString();\n\n // If different days or non-consecutive hours on the same day\n if (\n currentDay !== nextDay ||\n (currentDay === nextDay && Math.abs(nextHour - currentHour) > 1)\n ) {\n result.push({\n id: `divider-${item.id}-${items[index + 1].id}`,\n type: \"divider\" as const,\n revision: 0,\n });\n }\n }\n });\n\n return result;\n}\n\nfunction metricsToItems(metrics: GroupedPeriodResults): TimelineItem[] {\n if (!metrics) return [];\n\n const items = metrics\n .sort((a, b) => {\n const aDate = new Date(a.start as unknown as Date);\n const bDate = new Date(b.start as unknown as Date);\n return aDate.getTime() - bDate.getTime();\n })\n .filter((result) => {\n return result.rows.every((row) => row.value > 0);\n })\n .map((result) => {\n const { additions, deletions } = result.rows.reduce(\n (acc, row) => {\n if (\n (row.dimensions.changes.path as unknown as string) ===\n \"ph/diff/changes/add\"\n ) {\n acc.additions += row.value;\n } else if (\n (row.dimensions.changes.path as unknown as string) ===\n \"ph/diff/changes/remove\"\n ) {\n acc.deletions += row.value;\n }\n return acc;\n },\n { additions: 0, deletions: 0 },\n );\n\n const startDate = new Date(result.start as unknown as Date);\n\n return {\n id: startDate.toISOString(),\n type: \"bar\" as const,\n addSize: getBarSize(additions),\n delSize: getBarSize(deletions),\n additions,\n deletions,\n timestampUtcMs: startDate.toISOString(),\n startDate: startDate,\n endDate: new Date(result.end as unknown as Date),\n revision: 0,\n } as const;\n });\n\n return addItemsDividers(items);\n}\n\nexport type UseTimelineItemsResult = UseAnalyticsQueryResult<TimelineItem[]>;\n\nexport const useTimelineItems = (\n documentId?: string,\n startTimestamp?: string,\n driveId?: string,\n): UseTimelineItemsResult => {\n const start = startTimestamp\n ? DateTime.fromISO(startTimestamp)\n : DateTime.now().startOf(\"day\");\n\n return useAnalyticsQuery<TimelineItem[]>(\n {\n start,\n end: DateTime.now().endOf(\"day\"),\n granularity: AnalyticsGranularity.Hourly,\n metrics: [\"Count\"],\n select: {\n changes: [AnalyticsPath.fromString(`ph/diff/changes`)],\n document: [AnalyticsPath.fromString(`ph/diff/document/${documentId}`)],\n },\n lod: {\n changes: 4,\n },\n },\n {\n sources: [AnalyticsPath.fromString(`ph/diff/${driveId}/${documentId}`)],\n select: metricsToItems,\n },\n );\n};\n","import { useDocumentById } from \"../../hooks/document-by-id.js\";\nimport { useTimelineItems } from \"./timeline-items.js\";\n\nexport function useDocumentTimeline(documentId?: string) {\n const [document] = useDocumentById(documentId);\n\n const id = document?.header.id;\n const createdAt = document?.header.createdAtUtcIso;\n const timelineItems = useTimelineItems(id, createdAt);\n\n return timelineItems.data || [];\n}\n","export const DEFAULT_DRIVE_EDITOR_ID = \"powerhouse/generic-drive-explorer\";\nexport const COMMON_PACKAGE_ID = \"powerhouse/common\";\n","import type {\n DocumentModelModule,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"document-model\";\n\nexport const baseDocumentModelsMap: Record<\n string,\n DocumentModelModule<DocumentModelPHState>\n> = {\n DocumentModel:\n documentModelDocumentModelModule as DocumentModelModule<DocumentModelPHState>,\n};\n\nexport const baseDocumentModels = Object.values(baseDocumentModelsMap);\n","import type { GraphQLClient, RequestOptions } from \"graphql-request\";\nimport { gql } from \"graphql-tag\";\nexport type Maybe<T> = T | null | undefined;\nexport type InputMaybe<T> = T | null | undefined;\nexport type Exact<T extends { [key: string]: unknown }> = {\n [K in keyof T]: T[K];\n};\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & {\n [SubKey in K]?: Maybe<T[SubKey]>;\n};\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {\n [SubKey in K]: Maybe<T[SubKey]>;\n};\nexport type MakeEmpty<\n T extends { [key: string]: unknown },\n K extends keyof T,\n> = { [_ in K]?: never };\nexport type Incremental<T> =\n | T\n | {\n [P in keyof T]?: P extends \" $fragmentName\" | \"__typename\" ? T[P] : never;\n };\ntype GraphQLClientRequestHeaders = RequestOptions[\"requestHeaders\"];\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n ID: { input: string; output: string };\n String: { input: string; output: string };\n Boolean: { input: boolean; output: boolean };\n Int: { input: number; output: number };\n Float: { input: number; output: number };\n DateTime: { input: string | Date; output: string | Date };\n JSONObject: { input: NonNullable<unknown>; output: NonNullable<unknown> };\n};\n\nexport type Action = {\n readonly attachments?: Maybe<ReadonlyArray<Attachment>>;\n readonly context?: Maybe<ActionContext>;\n readonly id: Scalars[\"String\"][\"output\"];\n readonly input: Scalars[\"JSONObject\"][\"output\"];\n readonly scope: Scalars[\"String\"][\"output\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"output\"];\n readonly type: Scalars[\"String\"][\"output\"];\n};\n\nexport type ActionContext = {\n readonly signer?: Maybe<ReactorSigner>;\n};\n\nexport type ActionContextInput = {\n readonly signer?: InputMaybe<ReactorSignerInput>;\n};\n\nexport type ActionInput = {\n readonly attachments?: InputMaybe<ReadonlyArray<AttachmentInput>>;\n readonly context?: InputMaybe<ActionContextInput>;\n readonly id: Scalars[\"String\"][\"input\"];\n readonly input: Scalars[\"JSONObject\"][\"input\"];\n readonly scope: Scalars[\"String\"][\"input\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"input\"];\n readonly type: Scalars[\"String\"][\"input\"];\n};\n\nexport type Attachment = {\n readonly data: Scalars[\"String\"][\"output\"];\n readonly extension?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly fileName?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hash: Scalars[\"String\"][\"output\"];\n readonly mimeType: Scalars[\"String\"][\"output\"];\n};\n\nexport type AttachmentInput = {\n readonly data: Scalars[\"String\"][\"input\"];\n readonly extension?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly fileName?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly hash: Scalars[\"String\"][\"input\"];\n readonly mimeType: Scalars[\"String\"][\"input\"];\n};\n\nexport type ChannelMeta = {\n readonly id: Scalars[\"String\"][\"output\"];\n};\n\nexport type ChannelMetaInput = {\n readonly id: Scalars[\"String\"][\"input\"];\n};\n\nexport type DeadLetterInfo = {\n readonly branch: Scalars[\"String\"][\"output\"];\n readonly documentId: Scalars[\"String\"][\"output\"];\n readonly error: Scalars[\"String\"][\"output\"];\n readonly jobId: Scalars[\"String\"][\"output\"];\n readonly operationCount: Scalars[\"Int\"][\"output\"];\n readonly scopes: ReadonlyArray<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type DocumentChangeContext = {\n readonly childId?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly parentId?: Maybe<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type DocumentChangeEvent = {\n readonly context?: Maybe<DocumentChangeContext>;\n readonly documents: ReadonlyArray<PhDocument>;\n readonly type: DocumentChangeType;\n};\n\nexport enum DocumentChangeType {\n ChildAdded = \"CHILD_ADDED\",\n ChildRemoved = \"CHILD_REMOVED\",\n Created = \"CREATED\",\n Deleted = \"DELETED\",\n ParentAdded = \"PARENT_ADDED\",\n ParentRemoved = \"PARENT_REMOVED\",\n Updated = \"UPDATED\",\n}\n\nexport type DocumentModelGlobalState = {\n readonly id: Scalars[\"String\"][\"output\"];\n readonly name: Scalars[\"String\"][\"output\"];\n readonly namespace?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly specification: Scalars[\"JSONObject\"][\"output\"];\n readonly version?: Maybe<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type DocumentModelResultPage = {\n readonly cursor?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hasNextPage: Scalars[\"Boolean\"][\"output\"];\n readonly hasPreviousPage: Scalars[\"Boolean\"][\"output\"];\n readonly items: ReadonlyArray<DocumentModelGlobalState>;\n readonly totalCount: Scalars[\"Int\"][\"output\"];\n};\n\nexport type DocumentOperationsFilterInput = {\n readonly actionTypes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly scopes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly sinceRevision?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n readonly timestampFrom?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly timestampTo?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type DocumentWithChildren = {\n readonly childIds: ReadonlyArray<Scalars[\"String\"][\"output\"]>;\n readonly document: PhDocument;\n};\n\nexport type JobChangeEvent = {\n readonly error?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly jobId: Scalars[\"String\"][\"output\"];\n readonly result: Scalars[\"JSONObject\"][\"output\"];\n readonly status: Scalars[\"String\"][\"output\"];\n};\n\nexport type JobInfo = {\n readonly completedAt?: Maybe<Scalars[\"DateTime\"][\"output\"]>;\n readonly createdAt: Scalars[\"DateTime\"][\"output\"];\n readonly error?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly id: Scalars[\"String\"][\"output\"];\n readonly result: Scalars[\"JSONObject\"][\"output\"];\n readonly status: Scalars[\"String\"][\"output\"];\n};\n\nexport type MoveChildrenResult = {\n readonly source: PhDocument;\n readonly target: PhDocument;\n};\n\nexport type Mutation = {\n readonly addChildren: PhDocument;\n readonly createDocument: PhDocument;\n readonly createEmptyDocument: PhDocument;\n readonly deleteDocument: Scalars[\"Boolean\"][\"output\"];\n readonly deleteDocuments: Scalars[\"Boolean\"][\"output\"];\n readonly moveChildren: MoveChildrenResult;\n readonly mutateDocument: PhDocument;\n readonly mutateDocumentAsync: Scalars[\"String\"][\"output\"];\n readonly pushSyncEnvelopes: Scalars[\"Boolean\"][\"output\"];\n readonly removeChildren: PhDocument;\n readonly renameDocument: PhDocument;\n readonly touchChannel: Scalars[\"Boolean\"][\"output\"];\n};\n\nexport type MutationAddChildrenArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n parentIdentifier: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationCreateDocumentArgs = {\n document: Scalars[\"JSONObject\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type MutationCreateEmptyDocumentArgs = {\n documentType: Scalars[\"String\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type MutationDeleteDocumentArgs = {\n identifier: Scalars[\"String\"][\"input\"];\n propagate?: InputMaybe<PropagationMode>;\n};\n\nexport type MutationDeleteDocumentsArgs = {\n identifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n propagate?: InputMaybe<PropagationMode>;\n};\n\nexport type MutationMoveChildrenArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n sourceParentIdentifier: Scalars[\"String\"][\"input\"];\n targetParentIdentifier: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationMutateDocumentArgs = {\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n documentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type MutationMutateDocumentAsyncArgs = {\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n documentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type MutationPushSyncEnvelopesArgs = {\n envelopes: ReadonlyArray<SyncEnvelopeInput>;\n};\n\nexport type MutationRemoveChildrenArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n parentIdentifier: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationRenameDocumentArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifier: Scalars[\"String\"][\"input\"];\n name: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationTouchChannelArgs = {\n input: TouchChannelInput;\n};\n\nexport type OperationContext = {\n readonly branch: Scalars[\"String\"][\"output\"];\n readonly documentId: Scalars[\"String\"][\"output\"];\n readonly documentType: Scalars[\"String\"][\"output\"];\n readonly ordinal: Scalars[\"Int\"][\"output\"];\n readonly scope: Scalars[\"String\"][\"output\"];\n};\n\nexport type OperationContextInput = {\n readonly branch: Scalars[\"String\"][\"input\"];\n readonly documentId: Scalars[\"String\"][\"input\"];\n readonly documentType: Scalars[\"String\"][\"input\"];\n readonly ordinal: Scalars[\"Int\"][\"input\"];\n readonly scope: Scalars[\"String\"][\"input\"];\n};\n\nexport type OperationInput = {\n readonly action: ActionInput;\n readonly error?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly hash: Scalars[\"String\"][\"input\"];\n readonly id?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly index: Scalars[\"Int\"][\"input\"];\n readonly skip: Scalars[\"Int\"][\"input\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"input\"];\n};\n\nexport type OperationWithContext = {\n readonly context: OperationContext;\n readonly operation: ReactorOperation;\n};\n\nexport type OperationWithContextInput = {\n readonly context: OperationContextInput;\n readonly operation: OperationInput;\n};\n\nexport type OperationsFilterInput = {\n readonly actionTypes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly documentId: Scalars[\"String\"][\"input\"];\n readonly scopes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly sinceRevision?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n readonly timestampFrom?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly timestampTo?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type PhDocument = {\n readonly createdAtUtcIso: Scalars[\"DateTime\"][\"output\"];\n readonly documentType: Scalars[\"String\"][\"output\"];\n readonly id: Scalars[\"String\"][\"output\"];\n readonly lastModifiedAtUtcIso: Scalars[\"DateTime\"][\"output\"];\n readonly name: Scalars[\"String\"][\"output\"];\n readonly operations?: Maybe<ReactorOperationResultPage>;\n readonly revisionsList: ReadonlyArray<Revision>;\n readonly slug?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly state: Scalars[\"JSONObject\"][\"output\"];\n};\n\nexport type PhDocumentOperationsArgs = {\n filter?: InputMaybe<DocumentOperationsFilterInput>;\n paging?: InputMaybe<PagingInput>;\n};\n\nexport type PhDocumentResultPage = {\n readonly cursor?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hasNextPage: Scalars[\"Boolean\"][\"output\"];\n readonly hasPreviousPage: Scalars[\"Boolean\"][\"output\"];\n readonly items: ReadonlyArray<PhDocument>;\n readonly totalCount: Scalars[\"Int\"][\"output\"];\n};\n\nexport type PagingInput = {\n readonly cursor?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly limit?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n readonly offset?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n};\n\nexport type PollSyncEnvelopesResult = {\n readonly ackOrdinal: Scalars[\"Int\"][\"output\"];\n readonly deadLetters: ReadonlyArray<DeadLetterInfo>;\n readonly envelopes: ReadonlyArray<SyncEnvelope>;\n};\n\nexport enum PropagationMode {\n Cascade = \"CASCADE\",\n Orphan = \"ORPHAN\",\n}\n\nexport type Query = {\n readonly document?: Maybe<DocumentWithChildren>;\n readonly documentChildren: PhDocumentResultPage;\n readonly documentModels: DocumentModelResultPage;\n readonly documentOperations: ReactorOperationResultPage;\n readonly documentParents: PhDocumentResultPage;\n readonly findDocuments: PhDocumentResultPage;\n readonly jobStatus?: Maybe<JobInfo>;\n readonly pollSyncEnvelopes: PollSyncEnvelopesResult;\n};\n\nexport type QueryDocumentArgs = {\n identifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryDocumentChildrenArgs = {\n paging?: InputMaybe<PagingInput>;\n parentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryDocumentModelsArgs = {\n namespace?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n paging?: InputMaybe<PagingInput>;\n};\n\nexport type QueryDocumentOperationsArgs = {\n filter: OperationsFilterInput;\n paging?: InputMaybe<PagingInput>;\n};\n\nexport type QueryDocumentParentsArgs = {\n childIdentifier: Scalars[\"String\"][\"input\"];\n paging?: InputMaybe<PagingInput>;\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryFindDocumentsArgs = {\n paging?: InputMaybe<PagingInput>;\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryJobStatusArgs = {\n jobId: Scalars[\"String\"][\"input\"];\n};\n\nexport type QueryPollSyncEnvelopesArgs = {\n channelId: Scalars[\"String\"][\"input\"];\n outboxAck: Scalars[\"Int\"][\"input\"];\n outboxLatest: Scalars[\"Int\"][\"input\"];\n};\n\nexport type ReactorOperation = {\n readonly action: Action;\n readonly error?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hash: Scalars[\"String\"][\"output\"];\n readonly id?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly index: Scalars[\"Int\"][\"output\"];\n readonly skip: Scalars[\"Int\"][\"output\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"output\"];\n};\n\nexport type ReactorOperationResultPage = {\n readonly cursor?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hasNextPage: Scalars[\"Boolean\"][\"output\"];\n readonly hasPreviousPage: Scalars[\"Boolean\"][\"output\"];\n readonly items: ReadonlyArray<ReactorOperation>;\n readonly totalCount: Scalars[\"Int\"][\"output\"];\n};\n\nexport type ReactorSigner = {\n readonly app?: Maybe<ReactorSignerApp>;\n readonly signatures: ReadonlyArray<Scalars[\"String\"][\"output\"]>;\n readonly user?: Maybe<ReactorSignerUser>;\n};\n\nexport type ReactorSignerApp = {\n readonly key: Scalars[\"String\"][\"output\"];\n readonly name: Scalars[\"String\"][\"output\"];\n};\n\nexport type ReactorSignerAppInput = {\n readonly key: Scalars[\"String\"][\"input\"];\n readonly name: Scalars[\"String\"][\"input\"];\n};\n\nexport type ReactorSignerInput = {\n readonly app?: InputMaybe<ReactorSignerAppInput>;\n readonly signatures: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n readonly user?: InputMaybe<ReactorSignerUserInput>;\n};\n\nexport type ReactorSignerUser = {\n readonly address: Scalars[\"String\"][\"output\"];\n readonly chainId: Scalars[\"Int\"][\"output\"];\n readonly networkId: Scalars[\"String\"][\"output\"];\n};\n\nexport type ReactorSignerUserInput = {\n readonly address: Scalars[\"String\"][\"input\"];\n readonly chainId: Scalars[\"Int\"][\"input\"];\n readonly networkId: Scalars[\"String\"][\"input\"];\n};\n\nexport type RemoteCursor = {\n readonly cursorOrdinal: Scalars[\"Int\"][\"output\"];\n readonly lastSyncedAtUtcMs?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly remoteName: Scalars[\"String\"][\"output\"];\n};\n\nexport type RemoteCursorInput = {\n readonly cursorOrdinal: Scalars[\"Int\"][\"input\"];\n readonly lastSyncedAtUtcMs?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly remoteName: Scalars[\"String\"][\"input\"];\n};\n\nexport type RemoteFilterInput = {\n readonly branch: Scalars[\"String\"][\"input\"];\n readonly documentId: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n readonly scope: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type Revision = {\n readonly revision: Scalars[\"Int\"][\"output\"];\n readonly scope: Scalars[\"String\"][\"output\"];\n};\n\nexport type SearchFilterInput = {\n readonly identifiers?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly parentId?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly type?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type Subscription = {\n readonly documentChanges: DocumentChangeEvent;\n readonly jobChanges: JobChangeEvent;\n};\n\nexport type SubscriptionDocumentChangesArgs = {\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type SubscriptionJobChangesArgs = {\n jobId: Scalars[\"String\"][\"input\"];\n};\n\nexport type SyncEnvelope = {\n readonly channelMeta: ChannelMeta;\n readonly cursor?: Maybe<RemoteCursor>;\n readonly dependsOn?: Maybe<ReadonlyArray<Scalars[\"String\"][\"output\"]>>;\n readonly key?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly operations?: Maybe<ReadonlyArray<OperationWithContext>>;\n readonly type: SyncEnvelopeType;\n};\n\nexport type SyncEnvelopeInput = {\n readonly channelMeta: ChannelMetaInput;\n readonly cursor?: InputMaybe<RemoteCursorInput>;\n readonly dependsOn?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly key?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly operations?: InputMaybe<ReadonlyArray<OperationWithContextInput>>;\n readonly type: SyncEnvelopeType;\n};\n\nexport enum SyncEnvelopeType {\n Ack = \"ACK\",\n Operations = \"OPERATIONS\",\n}\n\nexport type TouchChannelInput = {\n readonly collectionId: Scalars[\"String\"][\"input\"];\n readonly filter: RemoteFilterInput;\n readonly id: Scalars[\"String\"][\"input\"];\n readonly name: Scalars[\"String\"][\"input\"];\n readonly sinceTimestampUtcMs: Scalars[\"String\"][\"input\"];\n};\n\nexport type ViewFilterInput = {\n readonly branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly scopes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n};\n\nexport type PhDocumentFieldsFragment = {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n};\n\nexport type GetDocumentModelsQueryVariables = Exact<{\n namespace?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentModelsQuery = {\n readonly documentModels: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly name: string;\n readonly namespace?: string | null | undefined;\n readonly version?: string | null | undefined;\n readonly specification: NonNullable<unknown>;\n }>;\n };\n};\n\nexport type GetDocumentQueryVariables = Exact<{\n identifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type GetDocumentQuery = {\n readonly document?:\n | {\n readonly childIds: ReadonlyArray<string>;\n readonly document: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n }\n | null\n | undefined;\n};\n\nexport type GetDocumentWithOperationsQueryVariables = Exact<{\n identifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n operationsFilter?: InputMaybe<DocumentOperationsFilterInput>;\n operationsPaging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentWithOperationsQuery = {\n readonly document?:\n | {\n readonly childIds: ReadonlyArray<string>;\n readonly document: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly operations?:\n | {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly index: number;\n readonly timestampUtcMs: string;\n readonly hash: string;\n readonly skip: number;\n readonly error?: string | null | undefined;\n readonly id?: string | null | undefined;\n readonly action: {\n readonly id: string;\n readonly type: string;\n readonly timestampUtcMs: string;\n readonly input: NonNullable<unknown>;\n readonly scope: string;\n readonly attachments?:\n | ReadonlyArray<{\n readonly data: string;\n readonly mimeType: string;\n readonly hash: string;\n readonly extension?: string | null | undefined;\n readonly fileName?: string | null | undefined;\n }>\n | null\n | undefined;\n readonly context?:\n | {\n readonly signer?:\n | {\n readonly signatures: ReadonlyArray<string>;\n readonly user?:\n | {\n readonly address: string;\n readonly networkId: string;\n readonly chainId: number;\n }\n | null\n | undefined;\n readonly app?:\n | {\n readonly name: string;\n readonly key: string;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n };\n }>;\n }\n | null\n | undefined;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n }\n | null\n | undefined;\n};\n\nexport type GetDocumentChildrenQueryVariables = Exact<{\n parentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentChildrenQuery = {\n readonly documentChildren: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n };\n};\n\nexport type GetDocumentParentsQueryVariables = Exact<{\n childIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentParentsQuery = {\n readonly documentParents: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n };\n};\n\nexport type FindDocumentsQueryVariables = Exact<{\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type FindDocumentsQuery = {\n readonly findDocuments: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n };\n};\n\nexport type GetDocumentOperationsQueryVariables = Exact<{\n filter: OperationsFilterInput;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentOperationsQuery = {\n readonly documentOperations: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly index: number;\n readonly timestampUtcMs: string;\n readonly hash: string;\n readonly skip: number;\n readonly error?: string | null | undefined;\n readonly id?: string | null | undefined;\n readonly action: {\n readonly id: string;\n readonly type: string;\n readonly timestampUtcMs: string;\n readonly input: NonNullable<unknown>;\n readonly scope: string;\n readonly attachments?:\n | ReadonlyArray<{\n readonly data: string;\n readonly mimeType: string;\n readonly hash: string;\n readonly extension?: string | null | undefined;\n readonly fileName?: string | null | undefined;\n }>\n | null\n | undefined;\n readonly context?:\n | {\n readonly signer?:\n | {\n readonly signatures: ReadonlyArray<string>;\n readonly user?:\n | {\n readonly address: string;\n readonly networkId: string;\n readonly chainId: number;\n }\n | null\n | undefined;\n readonly app?:\n | { readonly name: string; readonly key: string }\n | null\n | undefined;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n };\n }>;\n };\n};\n\nexport type GetJobStatusQueryVariables = Exact<{\n jobId: Scalars[\"String\"][\"input\"];\n}>;\n\nexport type GetJobStatusQuery = {\n readonly jobStatus?:\n | {\n readonly id: string;\n readonly status: string;\n readonly result: NonNullable<unknown>;\n readonly error?: string | null | undefined;\n readonly createdAt: string | Date;\n readonly completedAt?: string | Date | null | undefined;\n }\n | null\n | undefined;\n};\n\nexport type CreateDocumentMutationVariables = Exact<{\n document: Scalars[\"JSONObject\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type CreateDocumentMutation = {\n readonly createDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type CreateEmptyDocumentMutationVariables = Exact<{\n documentType: Scalars[\"String\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type CreateEmptyDocumentMutation = {\n readonly createEmptyDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type MutateDocumentMutationVariables = Exact<{\n documentIdentifier: Scalars[\"String\"][\"input\"];\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type MutateDocumentMutation = {\n readonly mutateDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type MutateDocumentAsyncMutationVariables = Exact<{\n documentIdentifier: Scalars[\"String\"][\"input\"];\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type MutateDocumentAsyncMutation = {\n readonly mutateDocumentAsync: string;\n};\n\nexport type RenameDocumentMutationVariables = Exact<{\n documentIdentifier: Scalars[\"String\"][\"input\"];\n name: Scalars[\"String\"][\"input\"];\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type RenameDocumentMutation = {\n readonly renameDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type AddChildrenMutationVariables = Exact<{\n parentIdentifier: Scalars[\"String\"][\"input\"];\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type AddChildrenMutation = {\n readonly addChildren: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type RemoveChildrenMutationVariables = Exact<{\n parentIdentifier: Scalars[\"String\"][\"input\"];\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type RemoveChildrenMutation = {\n readonly removeChildren: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type MoveChildrenMutationVariables = Exact<{\n sourceParentIdentifier: Scalars[\"String\"][\"input\"];\n targetParentIdentifier: Scalars[\"String\"][\"input\"];\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type MoveChildrenMutation = {\n readonly moveChildren: {\n readonly source: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n readonly target: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n };\n};\n\nexport type DeleteDocumentMutationVariables = Exact<{\n identifier: Scalars[\"String\"][\"input\"];\n propagate?: InputMaybe<PropagationMode>;\n}>;\n\nexport type DeleteDocumentMutation = { readonly deleteDocument: boolean };\n\nexport type DeleteDocumentsMutationVariables = Exact<{\n identifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n propagate?: InputMaybe<PropagationMode>;\n}>;\n\nexport type DeleteDocumentsMutation = { readonly deleteDocuments: boolean };\n\nexport type DocumentChangesSubscriptionVariables = Exact<{\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type DocumentChangesSubscription = {\n readonly documentChanges: {\n readonly type: DocumentChangeType;\n readonly documents: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n readonly context?:\n | {\n readonly parentId?: string | null | undefined;\n readonly childId?: string | null | undefined;\n }\n | null\n | undefined;\n };\n};\n\nexport type JobChangesSubscriptionVariables = Exact<{\n jobId: Scalars[\"String\"][\"input\"];\n}>;\n\nexport type JobChangesSubscription = {\n readonly jobChanges: {\n readonly jobId: string;\n readonly status: string;\n readonly result: NonNullable<unknown>;\n readonly error?: string | null | undefined;\n };\n};\n\nexport type PollSyncEnvelopesQueryVariables = Exact<{\n channelId: Scalars[\"String\"][\"input\"];\n outboxAck: Scalars[\"Int\"][\"input\"];\n outboxLatest: Scalars[\"Int\"][\"input\"];\n}>;\n\nexport type PollSyncEnvelopesQuery = {\n readonly pollSyncEnvelopes: {\n readonly ackOrdinal: number;\n readonly envelopes: ReadonlyArray<{\n readonly type: SyncEnvelopeType;\n readonly key?: string | null | undefined;\n readonly dependsOn?: ReadonlyArray<string> | null | undefined;\n readonly channelMeta: { readonly id: string };\n readonly operations?:\n | ReadonlyArray<{\n readonly operation: {\n readonly index: number;\n readonly timestampUtcMs: string;\n readonly hash: string;\n readonly skip: number;\n readonly error?: string | null | undefined;\n readonly id?: string | null | undefined;\n readonly action: {\n readonly id: string;\n readonly type: string;\n readonly timestampUtcMs: string;\n readonly input: NonNullable<unknown>;\n readonly scope: string;\n readonly attachments?:\n | ReadonlyArray<{\n readonly data: string;\n readonly mimeType: string;\n readonly hash: string;\n readonly extension?: string | null | undefined;\n readonly fileName?: string | null | undefined;\n }>\n | null\n | undefined;\n readonly context?:\n | {\n readonly signer?:\n | {\n readonly signatures: ReadonlyArray<string>;\n readonly user?:\n | {\n readonly address: string;\n readonly networkId: string;\n readonly chainId: number;\n }\n | null\n | undefined;\n readonly app?:\n | { readonly name: string; readonly key: string }\n | null\n | undefined;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n };\n };\n readonly context: {\n readonly documentId: string;\n readonly documentType: string;\n readonly scope: string;\n readonly branch: string;\n };\n }>\n | null\n | undefined;\n readonly cursor?:\n | {\n readonly remoteName: string;\n readonly cursorOrdinal: number;\n readonly lastSyncedAtUtcMs?: string | null | undefined;\n }\n | null\n | undefined;\n }>;\n readonly deadLetters: ReadonlyArray<{\n readonly documentId: string;\n readonly error: string;\n }>;\n };\n};\n\nexport type TouchChannelMutationVariables = Exact<{\n input: TouchChannelInput;\n}>;\n\nexport type TouchChannelMutation = { readonly touchChannel: boolean };\n\nexport type PushSyncEnvelopesMutationVariables = Exact<{\n envelopes: ReadonlyArray<SyncEnvelopeInput>;\n}>;\n\nexport type PushSyncEnvelopesMutation = { readonly pushSyncEnvelopes: boolean };\n\nexport const PhDocumentFieldsFragmentDoc = gql`\n fragment PHDocumentFields on PHDocument {\n id\n slug\n name\n documentType\n state\n revisionsList {\n scope\n revision\n }\n createdAtUtcIso\n lastModifiedAtUtcIso\n }\n`;\nexport const GetDocumentModelsDocument = gql`\n query GetDocumentModels($namespace: String, $paging: PagingInput) {\n documentModels(namespace: $namespace, paging: $paging) {\n items {\n id\n name\n namespace\n version\n specification\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n`;\nexport const GetDocumentDocument = gql`\n query GetDocument($identifier: String!, $view: ViewFilterInput) {\n document(identifier: $identifier, view: $view) {\n document {\n ...PHDocumentFields\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentWithOperationsDocument = gql`\n query GetDocumentWithOperations(\n $identifier: String!\n $view: ViewFilterInput\n $operationsFilter: DocumentOperationsFilterInput\n $operationsPaging: PagingInput\n ) {\n document(identifier: $identifier, view: $view) {\n document {\n ...PHDocumentFields\n operations(filter: $operationsFilter, paging: $operationsPaging) {\n items {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n attachments {\n data\n mimeType\n hash\n extension\n fileName\n }\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentChildrenDocument = gql`\n query GetDocumentChildren(\n $parentIdentifier: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentChildren(\n parentIdentifier: $parentIdentifier\n view: $view\n paging: $paging\n ) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentParentsDocument = gql`\n query GetDocumentParents(\n $childIdentifier: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentParents(\n childIdentifier: $childIdentifier\n view: $view\n paging: $paging\n ) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const FindDocumentsDocument = gql`\n query FindDocuments(\n $search: SearchFilterInput!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n findDocuments(search: $search, view: $view, paging: $paging) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentOperationsDocument = gql`\n query GetDocumentOperations(\n $filter: OperationsFilterInput!\n $paging: PagingInput\n ) {\n documentOperations(filter: $filter, paging: $paging) {\n items {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n attachments {\n data\n mimeType\n hash\n extension\n fileName\n }\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n`;\nexport const GetJobStatusDocument = gql`\n query GetJobStatus($jobId: String!) {\n jobStatus(jobId: $jobId) {\n id\n status\n result\n error\n createdAt\n completedAt\n }\n }\n`;\nexport const CreateDocumentDocument = gql`\n mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {\n createDocument(document: $document, parentIdentifier: $parentIdentifier) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const CreateEmptyDocumentDocument = gql`\n mutation CreateEmptyDocument(\n $documentType: String!\n $parentIdentifier: String\n ) {\n createEmptyDocument(\n documentType: $documentType\n parentIdentifier: $parentIdentifier\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const MutateDocumentDocument = gql`\n mutation MutateDocument(\n $documentIdentifier: String!\n $actions: [JSONObject!]!\n $view: ViewFilterInput\n ) {\n mutateDocument(\n documentIdentifier: $documentIdentifier\n actions: $actions\n view: $view\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const MutateDocumentAsyncDocument = gql`\n mutation MutateDocumentAsync(\n $documentIdentifier: String!\n $actions: [JSONObject!]!\n $view: ViewFilterInput\n ) {\n mutateDocumentAsync(\n documentIdentifier: $documentIdentifier\n actions: $actions\n view: $view\n )\n }\n`;\nexport const RenameDocumentDocument = gql`\n mutation RenameDocument(\n $documentIdentifier: String!\n $name: String!\n $branch: String\n ) {\n renameDocument(\n documentIdentifier: $documentIdentifier\n name: $name\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const AddChildrenDocument = gql`\n mutation AddChildren(\n $parentIdentifier: String!\n $documentIdentifiers: [String!]!\n $branch: String\n ) {\n addChildren(\n parentIdentifier: $parentIdentifier\n documentIdentifiers: $documentIdentifiers\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const RemoveChildrenDocument = gql`\n mutation RemoveChildren(\n $parentIdentifier: String!\n $documentIdentifiers: [String!]!\n $branch: String\n ) {\n removeChildren(\n parentIdentifier: $parentIdentifier\n documentIdentifiers: $documentIdentifiers\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const MoveChildrenDocument = gql`\n mutation MoveChildren(\n $sourceParentIdentifier: String!\n $targetParentIdentifier: String!\n $documentIdentifiers: [String!]!\n $branch: String\n ) {\n moveChildren(\n sourceParentIdentifier: $sourceParentIdentifier\n targetParentIdentifier: $targetParentIdentifier\n documentIdentifiers: $documentIdentifiers\n branch: $branch\n ) {\n source {\n ...PHDocumentFields\n }\n target {\n ...PHDocumentFields\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const DeleteDocumentDocument = gql`\n mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {\n deleteDocument(identifier: $identifier, propagate: $propagate)\n }\n`;\nexport const DeleteDocumentsDocument = gql`\n mutation DeleteDocuments(\n $identifiers: [String!]!\n $propagate: PropagationMode\n ) {\n deleteDocuments(identifiers: $identifiers, propagate: $propagate)\n }\n`;\nexport const DocumentChangesDocument = gql`\n subscription DocumentChanges(\n $search: SearchFilterInput!\n $view: ViewFilterInput\n ) {\n documentChanges(search: $search, view: $view) {\n type\n documents {\n ...PHDocumentFields\n }\n context {\n parentId\n childId\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const JobChangesDocument = gql`\n subscription JobChanges($jobId: String!) {\n jobChanges(jobId: $jobId) {\n jobId\n status\n result\n error\n }\n }\n`;\nexport const PollSyncEnvelopesDocument = gql`\n query PollSyncEnvelopes(\n $channelId: String!\n $outboxAck: Int!\n $outboxLatest: Int!\n ) {\n pollSyncEnvelopes(\n channelId: $channelId\n outboxAck: $outboxAck\n outboxLatest: $outboxLatest\n ) {\n envelopes {\n type\n channelMeta {\n id\n }\n operations {\n operation {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n attachments {\n data\n mimeType\n hash\n extension\n fileName\n }\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n context {\n documentId\n documentType\n scope\n branch\n }\n }\n cursor {\n remoteName\n cursorOrdinal\n lastSyncedAtUtcMs\n }\n key\n dependsOn\n }\n ackOrdinal\n deadLetters {\n documentId\n error\n }\n }\n }\n`;\nexport const TouchChannelDocument = gql`\n mutation TouchChannel($input: TouchChannelInput!) {\n touchChannel(input: $input)\n }\n`;\nexport const PushSyncEnvelopesDocument = gql`\n mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {\n pushSyncEnvelopes(envelopes: $envelopes)\n }\n`;\n\nexport type SdkFunctionWrapper = <T>(\n action: (requestHeaders?: Record<string, string>) => Promise<T>,\n operationName: string,\n operationType?: string,\n variables?: any,\n) => Promise<T>;\n\nconst defaultWrapper: SdkFunctionWrapper = (\n action,\n _operationName,\n _operationType,\n _variables,\n) => action();\n\nexport function getSdk(\n client: GraphQLClient,\n withWrapper: SdkFunctionWrapper = defaultWrapper,\n) {\n return {\n GetDocumentModels(\n variables?: GetDocumentModelsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentModelsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentModelsQuery>({\n document: GetDocumentModelsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentModels\",\n \"query\",\n variables,\n );\n },\n GetDocument(\n variables: GetDocumentQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentQuery>({\n document: GetDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocument\",\n \"query\",\n variables,\n );\n },\n GetDocumentWithOperations(\n variables: GetDocumentWithOperationsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentWithOperationsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentWithOperationsQuery>({\n document: GetDocumentWithOperationsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentWithOperations\",\n \"query\",\n variables,\n );\n },\n GetDocumentChildren(\n variables: GetDocumentChildrenQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentChildrenQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentChildrenQuery>({\n document: GetDocumentChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentChildren\",\n \"query\",\n variables,\n );\n },\n GetDocumentParents(\n variables: GetDocumentParentsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentParentsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentParentsQuery>({\n document: GetDocumentParentsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentParents\",\n \"query\",\n variables,\n );\n },\n FindDocuments(\n variables: FindDocumentsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<FindDocumentsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<FindDocumentsQuery>({\n document: FindDocumentsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"FindDocuments\",\n \"query\",\n variables,\n );\n },\n GetDocumentOperations(\n variables: GetDocumentOperationsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentOperationsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentOperationsQuery>({\n document: GetDocumentOperationsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentOperations\",\n \"query\",\n variables,\n );\n },\n GetJobStatus(\n variables: GetJobStatusQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetJobStatusQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetJobStatusQuery>({\n document: GetJobStatusDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetJobStatus\",\n \"query\",\n variables,\n );\n },\n CreateDocument(\n variables: CreateDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<CreateDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<CreateDocumentMutation>({\n document: CreateDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"CreateDocument\",\n \"mutation\",\n variables,\n );\n },\n CreateEmptyDocument(\n variables: CreateEmptyDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<CreateEmptyDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<CreateEmptyDocumentMutation>({\n document: CreateEmptyDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"CreateEmptyDocument\",\n \"mutation\",\n variables,\n );\n },\n MutateDocument(\n variables: MutateDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<MutateDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<MutateDocumentMutation>({\n document: MutateDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"MutateDocument\",\n \"mutation\",\n variables,\n );\n },\n MutateDocumentAsync(\n variables: MutateDocumentAsyncMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<MutateDocumentAsyncMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<MutateDocumentAsyncMutation>({\n document: MutateDocumentAsyncDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"MutateDocumentAsync\",\n \"mutation\",\n variables,\n );\n },\n RenameDocument(\n variables: RenameDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<RenameDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<RenameDocumentMutation>({\n document: RenameDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"RenameDocument\",\n \"mutation\",\n variables,\n );\n },\n AddChildren(\n variables: AddChildrenMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<AddChildrenMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<AddChildrenMutation>({\n document: AddChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"AddChildren\",\n \"mutation\",\n variables,\n );\n },\n RemoveChildren(\n variables: RemoveChildrenMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<RemoveChildrenMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<RemoveChildrenMutation>({\n document: RemoveChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"RemoveChildren\",\n \"mutation\",\n variables,\n );\n },\n MoveChildren(\n variables: MoveChildrenMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<MoveChildrenMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<MoveChildrenMutation>({\n document: MoveChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"MoveChildren\",\n \"mutation\",\n variables,\n );\n },\n DeleteDocument(\n variables: DeleteDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<DeleteDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<DeleteDocumentMutation>({\n document: DeleteDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"DeleteDocument\",\n \"mutation\",\n variables,\n );\n },\n DeleteDocuments(\n variables: DeleteDocumentsMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<DeleteDocumentsMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<DeleteDocumentsMutation>({\n document: DeleteDocumentsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"DeleteDocuments\",\n \"mutation\",\n variables,\n );\n },\n DocumentChanges(\n variables: DocumentChangesSubscriptionVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<DocumentChangesSubscription> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<DocumentChangesSubscription>({\n document: DocumentChangesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"DocumentChanges\",\n \"subscription\",\n variables,\n );\n },\n JobChanges(\n variables: JobChangesSubscriptionVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<JobChangesSubscription> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<JobChangesSubscription>({\n document: JobChangesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"JobChanges\",\n \"subscription\",\n variables,\n );\n },\n PollSyncEnvelopes(\n variables: PollSyncEnvelopesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<PollSyncEnvelopesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<PollSyncEnvelopesQuery>({\n document: PollSyncEnvelopesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"PollSyncEnvelopes\",\n \"query\",\n variables,\n );\n },\n TouchChannel(\n variables: TouchChannelMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<TouchChannelMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<TouchChannelMutation>({\n document: TouchChannelDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"TouchChannel\",\n \"mutation\",\n variables,\n );\n },\n PushSyncEnvelopes(\n variables: PushSyncEnvelopesMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<PushSyncEnvelopesMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<PushSyncEnvelopesMutation>({\n document: PushSyncEnvelopesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"PushSyncEnvelopes\",\n \"mutation\",\n variables,\n );\n },\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;\n","import {\n GetDocumentDocument,\n GetDocumentOperationsDocument,\n type OperationsFilterInput,\n type PagingInput,\n type ViewFilterInput,\n} from \"./gen/schema.js\";\n\n/** Get the source string from a GraphQL document (string or DocumentNode). */\nfunction getDocumentSource(doc: unknown): string {\n return typeof doc === \"string\"\n ? doc\n : ((doc as { loc?: { source: { body: string } } }).loc?.source.body ?? \"\");\n}\n\n/**\n * Extract the inner selection set of a named field from a GraphQL document source.\n * Returns the `{ ... }` block including braces.\n */\nfunction extractSelectionSet(\n doc: unknown,\n fieldName: string,\n fallback: string,\n): string {\n const source = getDocumentSource(doc);\n\n const regex = new RegExp(\n `${fieldName}\\\\([^)]*\\\\)\\\\s*(\\\\{[\\\\s\\\\S]*\\\\})\\\\s*\\\\}`,\n );\n return regex.exec(source)?.[1] ?? fallback;\n}\n\n/**\n * Extract the query body and any fragment definitions from a GraphQL document.\n * Returns { body, fragments } where body is the content inside the query `{ ... }`\n * and fragments are any trailing fragment definitions.\n */\nfunction extractQueryParts(\n doc: unknown,\n fallbackBody: string,\n): { body: string; fragments: string } {\n const source = getDocumentSource(doc);\n\n // Match the query body: everything between the first `{` and its closing `}`\n // before any fragment definitions\n const queryMatch = /^[^{]*\\{([\\s\\S]*?)\\}\\s*(fragment[\\s\\S]*)?$/.exec(source);\n const body = queryMatch?.[1]?.trim() ?? fallbackBody;\n const fragments = queryMatch?.[2]?.trim() ?? \"\";\n\n return { body, fragments };\n}\n\nconst operationsSelectionSet = extractSelectionSet(\n GetDocumentOperationsDocument,\n \"documentOperations\",\n \"{ items { index } }\",\n);\n\nconst documentParts = extractQueryParts(\n GetDocumentDocument,\n \"document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }\",\n);\n\n/**\n * Build a single GraphQL query that fetches documentOperations for\n * multiple filters using aliases. Each filter gets its own alias\n * (`scope_0`, `scope_1`, …) so all scopes are fetched in one HTTP request.\n */\nexport function buildBatchOperationsQuery(\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined | null)[],\n) {\n const varDefs = filters\n .flatMap((_, i) => [\n `$filter_${i}: OperationsFilterInput!`,\n `$paging_${i}: PagingInput`,\n ])\n .join(\", \");\n\n const fields = filters\n .map(\n (_, i) =>\n `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`,\n )\n .join(\"\\n \");\n\n const query = `query BatchGetDocumentOperations(${varDefs}) {\n ${fields}\n }`;\n\n const variables: Record<string, unknown> = {};\n for (let i = 0; i < filters.length; i++) {\n variables[`filter_${i}`] = filters[i];\n variables[`paging_${i}`] = pagings[i] ?? null;\n }\n\n return { query, variables };\n}\n\n/**\n * Build a single GraphQL query that fetches a document AND\n * documentOperations for multiple filters, all in one HTTP request.\n */\nexport function buildBatchDocumentWithOperationsQuery(\n identifier: string,\n view: ViewFilterInput | undefined,\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined)[],\n) {\n const docVarDefs = \"$identifier: String!, $view: ViewFilterInput\";\n const opsVarDefs = filters\n .flatMap((_, i) => [\n `$filter_${i}: OperationsFilterInput!`,\n `$paging_${i}: PagingInput`,\n ])\n .join(\", \");\n\n const opsFields = filters\n .map(\n (_, i) =>\n `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`,\n )\n .join(\"\\n \");\n\n const query = `query BatchGetDocumentWithOperations(${docVarDefs}, ${opsVarDefs}) {\n ${documentParts.body}\n ${opsFields}\n }\n ${documentParts.fragments}`;\n\n const variables: Record<string, unknown> = {\n identifier,\n view: view ?? null,\n };\n for (let i = 0; i < filters.length; i++) {\n variables[`filter_${i}`] = filters[i];\n variables[`paging_${i}`] = pagings[i] ?? null;\n }\n\n return { query, variables };\n}\n","import { GraphQLClient } from \"graphql-request\";\nimport {\n buildBatchDocumentWithOperationsQuery,\n buildBatchOperationsQuery,\n} from \"./batch-queries.js\";\nimport {\n getSdk,\n type GetDocumentOperationsQuery,\n type GetDocumentQuery,\n type OperationsFilterInput,\n type PagingInput,\n type SdkFunctionWrapper,\n type ViewFilterInput,\n} from \"./gen/schema.js\";\nimport type { ReactorGraphQLClient } from \"./types.js\";\n\nexport type { ReactorGraphQLClient } from \"./types.js\";\n\ntype DocumentOperationsPage = GetDocumentOperationsQuery[\"documentOperations\"];\n\ntype DocumentResult = NonNullable<GetDocumentQuery[\"document\"]>;\n\n/**\n * Creates a GraphQL client for the Reactor Subgraph API.\n * @param urlOrGQLClient The URL of the GraphQL API or a GraphQL client instance.\n * @param middleware An optional middleware function to wrap the GraphQL client calls.\n * @returns A GraphQL client for the Reactor Subgraph API.\n */\nexport function createClient(\n urlOrGQLClient: string | GraphQLClient,\n middleware?: SdkFunctionWrapper,\n): ReactorGraphQLClient {\n const client =\n typeof urlOrGQLClient === \"string\"\n ? new GraphQLClient(urlOrGQLClient)\n : urlOrGQLClient;\n return {\n ...getSdk(client, middleware),\n\n /**\n * Fetch documentOperations for multiple filters in a single HTTP request\n * using GraphQL aliases. Each filter has its own paging parameters.\n * Returns one result page per filter, in order.\n */\n async BatchGetDocumentOperations(\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined | null)[],\n ): Promise<DocumentOperationsPage[]> {\n const { query, variables } = buildBatchOperationsQuery(filters, pagings);\n const data = await client.request<Record<string, DocumentOperationsPage>>(\n query,\n variables,\n );\n return filters.map((_, i) => data[`scope_${i}`]);\n },\n\n /**\n * Fetch a document AND documentOperations for multiple filters\n * in a single HTTP request. Combines GetDocument + BatchGetDocumentOperations.\n */\n async BatchGetDocumentWithOperations(\n identifier: string,\n view: ViewFilterInput | undefined,\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined)[],\n ): Promise<{\n document: DocumentResult | null;\n operations: DocumentOperationsPage[];\n }> {\n const { query, variables } = buildBatchDocumentWithOperationsQuery(\n identifier,\n view,\n filters,\n pagings,\n );\n const data = await client.request<\n Record<string, unknown> & { document?: DocumentResult }\n >(query, variables);\n return {\n document: data.document ?? null,\n operations: filters.map(\n (_, i) => data[`scope_${i}`] as DocumentOperationsPage,\n ),\n };\n },\n };\n}\n","import type { LOADING } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nexport const {\n useValue: useLoading,\n setValue: setLoading,\n addEventHandler: addLoadingEventHandler,\n} = makePHEventFunctions(\"loading\");\n\nexport const loading: LOADING = null;\n","import type { IRenown, LoginStatus, User } from \"@renown/sdk\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport type { LOADING } from \"../types/global.js\";\nimport { loading } from \"./loading.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst renownEventFunctions = makePHEventFunctions(\"renown\");\n\n/** Adds an event handler for the renown instance */\nexport const addRenownEventHandler: () => void =\n renownEventFunctions.addEventHandler;\n\n/** Returns the renown instance */\nexport const useRenown: () => IRenown | LOADING | undefined =\n renownEventFunctions.useValue;\n\n/** Sets the renown instance */\nexport const setRenown: (value: IRenown | LOADING | undefined) => void =\n renownEventFunctions.setValue;\n\n/** Returns the DID from the renown instance */\nexport function useDid() {\n const renown = useRenown();\n return renown?.did;\n}\n\n/** Returns the current user from the renown instance, subscribing to user events */\nexport function useUser(): User | undefined {\n const renown = useRenown();\n const [user, setUser] = useState<User | undefined>(renown?.user);\n\n useEffect(() => {\n setUser(renown?.user);\n if (!renown) return;\n return renown.on(\"user\", setUser);\n }, [renown]);\n\n return user;\n}\n\n/** Returns the login status, subscribing to renown status events */\nexport function useLoginStatus(): LoginStatus | \"loading\" | undefined {\n const renown = useRenown();\n return useSyncExternalStore(\n (cb) => {\n if (!renown) {\n return () => {};\n }\n return renown.on(\"status\", cb);\n },\n () => (renown === loading ? \"loading\" : renown?.status),\n () => undefined,\n );\n}\n","export const RENOWN_URL = \"https://www.renown.id\";\nexport const RENOWN_NETWORK_ID = \"eip155\";\nexport const RENOWN_CHAIN_ID = \"1\";\n\nexport const DOMAIN_TYPE = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nexport const VERIFIABLE_CREDENTIAL_EIP712_TYPE = [\n { name: \"@context\", type: \"string[]\" },\n { name: \"type\", type: \"string[]\" },\n { name: \"id\", type: \"string\" },\n { name: \"issuer\", type: \"Issuer\" },\n { name: \"credentialSubject\", type: \"CredentialSubject\" },\n { name: \"credentialSchema\", type: \"CredentialSchema\" },\n { name: \"issuanceDate\", type: \"string\" },\n { name: \"expirationDate\", type: \"string\" },\n] as const;\n\nexport const CREDENTIAL_SCHEMA_EIP712_TYPE = [\n { name: \"id\", type: \"string\" },\n { name: \"type\", type: \"string\" },\n] as const;\n\nexport const CREDENTIAL_SUBJECT_TYPE = [\n { name: \"app\", type: \"string\" },\n { name: \"id\", type: \"string\" },\n { name: \"name\", type: \"string\" },\n] as const;\n\nexport const ISSUER_TYPE = [\n { name: \"id\", type: \"string\" },\n { name: \"ethereumAddress\", type: \"string\" },\n] as const;\n\nexport const CREDENTIAL_TYPES = {\n EIP712Domain: DOMAIN_TYPE,\n VerifiableCredential: VERIFIABLE_CREDENTIAL_EIP712_TYPE,\n CredentialSchema: CREDENTIAL_SCHEMA_EIP712_TYPE,\n CredentialSubject: CREDENTIAL_SUBJECT_TYPE,\n Issuer: ISSUER_TYPE,\n} as const;\n","import type { IRenown, User } from \"@renown/sdk\";\nimport { logger } from \"document-model\";\nimport { RENOWN_CHAIN_ID, RENOWN_NETWORK_ID, RENOWN_URL } from \"./constants.js\";\n\nexport function openRenown(documentId?: string) {\n const renown = window.ph?.renown;\n let renownUrl = renown?.baseUrl;\n if (!renownUrl) {\n logger.warn(\"Renown instance not found, falling back to: \", RENOWN_URL);\n renownUrl = RENOWN_URL;\n }\n\n if (documentId) {\n window.open(`${renownUrl}/profile/${documentId}`, \"_blank\")?.focus();\n return;\n }\n\n const url = new URL(renownUrl);\n url.searchParams.set(\"app\", renown?.did ?? \"\");\n url.searchParams.set(\"connect\", renown?.did ?? \"\");\n url.searchParams.set(\"network\", RENOWN_NETWORK_ID);\n url.searchParams.set(\"chain\", RENOWN_CHAIN_ID);\n\n const returnUrl = new URL(window.location.pathname, window.location.origin);\n url.searchParams.set(\"returnUrl\", returnUrl.toJSON());\n window.open(url, \"_self\")?.focus();\n}\n\n/**\n * Reads the `?user=` DID from the URL if present.\n * Returns the DID and cleans up the URL parameter.\n */\nfunction consumeDidFromUrl(): string | undefined {\n if (typeof window === \"undefined\") return;\n\n const urlParams = new URLSearchParams(window.location.search);\n const userParam = urlParams.get(\"user\");\n if (!userParam) return;\n\n const userDid = decodeURIComponent(userParam);\n\n // Clean up the URL parameter\n const cleanUrl = new URL(window.location.href);\n cleanUrl.searchParams.delete(\"user\");\n window.history.replaceState({}, \"\", cleanUrl.toString());\n\n return userDid;\n}\n\n/**\n * Log in the user. Resolves the user DID from (in order):\n * 1. Explicit `userDid` argument\n * 2. `?user=` URL parameter (from Renown portal redirect)\n * 3. Previously stored session in the Renown instance\n */\nexport async function login(\n userDid: string | undefined,\n renown: IRenown | undefined,\n): Promise<User | undefined> {\n if (!renown) {\n return;\n }\n\n const did = userDid ?? consumeDidFromUrl();\n\n try {\n const user = renown.user;\n\n if (user?.did && (user.did === did || !did)) {\n return user;\n }\n\n if (!did) {\n return;\n }\n\n return await renown.login(did);\n } catch (error) {\n logger.error(\n error instanceof Error ? error.message : JSON.stringify(error),\n );\n }\n}\n\nexport async function logout() {\n const renown = window.ph?.renown;\n await renown?.logout();\n\n // Clear the user parameter from URL to prevent auto-login on refresh\n const url = new URL(window.location.href);\n if (url.searchParams.has(\"user\")) {\n url.searchParams.delete(\"user\");\n window.history.replaceState(null, \"\", url.toString());\n }\n}\n","import type { LoginStatus, User } from \"@renown/sdk\";\nimport { useCallback } from \"react\";\nimport { useLoginStatus, useUser } from \"../hooks/renown.js\";\nimport { logout as logoutUtil, openRenown } from \"./utils.js\";\n\nexport type RenownAuthStatus = LoginStatus | \"loading\";\n\nexport interface RenownAuth {\n status: RenownAuthStatus | undefined;\n user: User | undefined;\n address: string | undefined;\n ensName: string | undefined;\n avatarUrl: string | undefined;\n profileId: string | undefined;\n displayName: string | undefined;\n displayAddress: string | undefined;\n login: () => void;\n logout: () => Promise<void>;\n openProfile: () => void;\n}\n\nfunction truncateAddress(address: string): string {\n if (address.length <= 13) return address;\n return `${address.slice(0, 7)}...${address.slice(-5)}`;\n}\n\nfunction toRenownAuthStatus(\n loginStatus: LoginStatus | \"loading\" | undefined,\n user: User | undefined,\n): RenownAuthStatus | undefined {\n if (loginStatus === \"authorized\") {\n return user ? \"authorized\" : \"checking\";\n }\n return loginStatus;\n}\n\nexport function useRenownAuth(): RenownAuth {\n const user = useUser();\n const loginStatus = useLoginStatus();\n\n // syncs user with login status\n const status = toRenownAuthStatus(loginStatus, user);\n\n const address = user?.address;\n const ensName = user?.ens?.name;\n const avatarUrl = user?.profile?.userImage ?? user?.ens?.avatarUrl;\n const profileId = user?.profile?.documentId;\n\n const displayName = ensName ?? user?.profile?.username ?? undefined;\n const displayAddress = address ? truncateAddress(address) : undefined;\n\n const login = useCallback(() => {\n openRenown();\n }, []);\n\n const logout = useCallback(async () => {\n await logoutUtil();\n }, []);\n\n const openProfile = useCallback(() => {\n if (profileId) {\n openRenown(profileId);\n }\n }, [profileId]);\n\n return {\n status,\n user,\n address,\n ensName,\n avatarUrl,\n profileId,\n displayName,\n displayAddress,\n login,\n logout,\n openProfile,\n };\n}\n","import type {\n PHAppConfigHooks,\n PHAppConfigSetters,\n PHDocumentEditorConfigHooks,\n PHDocumentEditorConfigSetters,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"../make-ph-event-functions.js\";\n\nexport const isExternalControlsEnabledEventFunctions = makePHEventFunctions(\n \"isExternalControlsEnabled\",\n);\n\n/** Sets whether external controls are enabled for a given editor. */\nexport const setIsExternalControlsEnabled =\n isExternalControlsEnabledEventFunctions.setValue;\n\n/** Gets whether external controls are enabled for a given editor. */\nexport const useIsExternalControlsEnabled =\n isExternalControlsEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the external controls enabled state changes. */\nexport const addIsExternalControlsEnabledEventHandler =\n isExternalControlsEnabledEventFunctions.addEventHandler;\n\nconst isDragAndDropEnabledEventFunctions = makePHEventFunctions(\n \"isDragAndDropEnabled\",\n);\n\n/** Sets whether drag and drop is enabled for a given app. */\nexport const setIsDragAndDropEnabled =\n isDragAndDropEnabledEventFunctions.setValue;\n\n/** Gets whether drag and drop is enabled for a given app. */\nexport const useIsDragAndDropEnabled =\n isDragAndDropEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the drag and drop enabled state changes. */\nexport const addIsDragAndDropEnabledEventHandler =\n isDragAndDropEnabledEventFunctions.addEventHandler;\n\nconst allowedDocumentTypesEventFunctions = makePHEventFunctions(\n \"allowedDocumentTypes\",\n);\n\n/** Sets the allowed document types for a given app. */\nexport const setAllowedDocumentTypes =\n allowedDocumentTypesEventFunctions.setValue;\n\n/** Defines the document types a drive supports.\n *\n * Defaults to all of the document types registered in the reactor.\n */\nexport function useAllowedDocumentTypes() {\n const definedAllowedDocumentTypes =\n allowedDocumentTypesEventFunctions.useValue();\n return definedAllowedDocumentTypes;\n}\n\n/** Adds an event handler for when the allowed document types for a given app changes. */\nexport const addAllowedDocumentTypesEventHandler =\n allowedDocumentTypesEventFunctions.addEventHandler;\n\nexport const phAppConfigSetters: PHAppConfigSetters = {\n allowedDocumentTypes: setAllowedDocumentTypes,\n isDragAndDropEnabled: setIsDragAndDropEnabled,\n};\n\nexport const phDocumentEditorConfigSetters: PHDocumentEditorConfigSetters = {\n isExternalControlsEnabled: setIsExternalControlsEnabled,\n};\n\nexport const phAppConfigHooks: PHAppConfigHooks = {\n allowedDocumentTypes: useAllowedDocumentTypes,\n isDragAndDropEnabled: useIsDragAndDropEnabled,\n};\n\nexport const phDocumentEditorConfigHooks: PHDocumentEditorConfigHooks = {\n isExternalControlsEnabled: useIsExternalControlsEnabled,\n};\n","import type {\n PHAppConfigKey,\n PHDocumentEditorConfigKey,\n PHGlobalConfigHooks,\n PHGlobalConfigHooksForKey,\n PHGlobalConfigKey,\n PHGlobalConfigSetters,\n PHGlobalConfigSettersForKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"../make-ph-event-functions.js\";\nimport {\n phAppConfigHooks,\n phAppConfigSetters,\n phDocumentEditorConfigHooks,\n phDocumentEditorConfigSetters,\n} from \"./editor.js\";\n\nexport const {\n useValue: useRouterBasename,\n setValue: setRouterBasename,\n addEventHandler: addRouterBasenameEventHandler,\n} = makePHEventFunctions(\"routerBasename\");\n\nexport const {\n useValue: useVersion,\n setValue: setVersion,\n addEventHandler: addVersionEventHandler,\n} = makePHEventFunctions(\"version\");\n\nexport const {\n useValue: useRequiresHardRefresh,\n setValue: setRequiresHardRefresh,\n addEventHandler: addRequiresHardRefreshEventHandler,\n} = makePHEventFunctions(\"requiresHardRefresh\");\n\nexport const {\n useValue: useWarnOutdatedApp,\n setValue: setWarnOutdatedApp,\n addEventHandler: addWarnOutdatedAppEventHandler,\n} = makePHEventFunctions(\"warnOutdatedApp\");\n\nexport const {\n useValue: useStudioMode,\n setValue: setStudioMode,\n addEventHandler: addStudioModeEventHandler,\n} = makePHEventFunctions(\"studioMode\");\n\nexport const {\n useValue: useBasePath,\n setValue: setBasePath,\n addEventHandler: addBasePathEventHandler,\n} = makePHEventFunctions(\"basePath\");\n\nexport const {\n useValue: useVersionCheckInterval,\n setValue: setVersionCheckInterval,\n addEventHandler: addVersionCheckIntervalEventHandler,\n} = makePHEventFunctions(\"versionCheckInterval\");\n\nexport const {\n useValue: useCliVersion,\n setValue: setCliVersion,\n addEventHandler: addCliVersionEventHandler,\n} = makePHEventFunctions(\"cliVersion\");\n\nexport const {\n useValue: useFileUploadOperationsChunkSize,\n setValue: setFileUploadOperationsChunkSize,\n addEventHandler: addFileUploadOperationsChunkSizeEventHandler,\n} = makePHEventFunctions(\"fileUploadOperationsChunkSize\");\n\nexport const {\n useValue: useIsDocumentModelSelectionSettingsEnabled,\n setValue: setIsDocumentModelSelectionSettingsEnabled,\n addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler,\n} = makePHEventFunctions(\"isDocumentModelSelectionSettingsEnabled\");\n\nexport const {\n useValue: useGaTrackingId,\n setValue: setGaTrackingId,\n addEventHandler: addGaTrackingIdEventHandler,\n} = makePHEventFunctions(\"gaTrackingId\");\n\nexport const {\n useValue: useDefaultDrivesUrl,\n setValue: setDefaultDrivesUrl,\n addEventHandler: addDefaultDrivesUrlEventHandler,\n} = makePHEventFunctions(\"defaultDrivesUrl\");\n\nexport const {\n useValue: useDrivesPreserveStrategy,\n setValue: setDrivesPreserveStrategy,\n addEventHandler: addDrivesPreserveStrategyEventHandler,\n} = makePHEventFunctions(\"drivesPreserveStrategy\");\n\nexport const {\n useValue: useIsLocalDrivesEnabled,\n setValue: setIsLocalDrivesEnabled,\n addEventHandler: addIsLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsAddDriveEnabled,\n setValue: setIsAddDriveEnabled,\n addEventHandler: addIsAddDriveEnabledEventHandler,\n} = makePHEventFunctions(\"isAddDriveEnabled\");\n\nexport const {\n useValue: useIsPublicDrivesEnabled,\n setValue: setIsPublicDrivesEnabled,\n addEventHandler: addIsPublicDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isPublicDrivesEnabled\");\n\nexport const {\n useValue: useIsAddPublicDrivesEnabled,\n setValue: setIsAddPublicDrivesEnabled,\n addEventHandler: addIsAddPublicDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isAddPublicDrivesEnabled\");\n\nexport const {\n useValue: useIsDeletePublicDrivesEnabled,\n setValue: setIsDeletePublicDrivesEnabled,\n addEventHandler: addIsDeletePublicDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isDeletePublicDrivesEnabled\");\n\nexport const {\n useValue: useIsCloudDrivesEnabled,\n setValue: setIsCloudDrivesEnabled,\n addEventHandler: addIsCloudDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isCloudDrivesEnabled\");\n\nexport const {\n useValue: useIsAddCloudDrivesEnabled,\n setValue: setIsAddCloudDrivesEnabled,\n addEventHandler: addIsAddCloudDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isAddCloudDrivesEnabled\");\n\nexport const {\n useValue: useIsDeleteCloudDrivesEnabled,\n setValue: setIsDeleteCloudDrivesEnabled,\n addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isDeleteCloudDrivesEnabled\");\n\nexport const {\n useValue: useLocalDrivesEnabled,\n setValue: setLocalDrivesEnabled,\n addEventHandler: addLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsAddLocalDrivesEnabled,\n setValue: setIsAddLocalDrivesEnabled,\n addEventHandler: addIsAddLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isAddLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsDeleteLocalDrivesEnabled,\n setValue: setIsDeleteLocalDrivesEnabled,\n addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isDeleteLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsEditorDebugModeEnabled,\n setValue: setIsEditorDebugModeEnabled,\n addEventHandler: addIsEditorDebugModeEnabledEventHandler,\n} = makePHEventFunctions(\"isEditorDebugModeEnabled\");\n\nexport const {\n useValue: useIsEditorReadModeEnabled,\n setValue: setIsEditorReadModeEnabled,\n addEventHandler: addIsEditorReadModeEnabledEventHandler,\n} = makePHEventFunctions(\"isEditorReadModeEnabled\");\n\nexport const {\n useValue: useIsAnalyticsDatabaseWorkerEnabled,\n setValue: setIsAnalyticsDatabaseWorkerEnabled,\n addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n} = makePHEventFunctions(\"isAnalyticsDatabaseWorkerEnabled\");\n\nexport const {\n useValue: useIsDiffAnalyticsEnabled,\n setValue: setIsDiffAnalyticsEnabled,\n addEventHandler: addIsDiffAnalyticsEnabledEventHandler,\n} = makePHEventFunctions(\"isDiffAnalyticsEnabled\");\n\nexport const {\n useValue: useIsDriveAnalyticsEnabled,\n setValue: setIsDriveAnalyticsEnabled,\n addEventHandler: addIsDriveAnalyticsEnabledEventHandler,\n} = makePHEventFunctions(\"isDriveAnalyticsEnabled\");\n\nexport const {\n useValue: useRenownUrl,\n setValue: setRenownUrl,\n addEventHandler: addRenownUrlEventHandler,\n} = makePHEventFunctions(\"renownUrl\");\n\nexport const {\n useValue: useRenownNetworkId,\n setValue: setRenownNetworkId,\n addEventHandler: addRenownNetworkIdEventHandler,\n} = makePHEventFunctions(\"renownNetworkId\");\n\nexport const {\n useValue: useRenownChainId,\n setValue: setRenownChainId,\n addEventHandler: addRenownChainIdEventHandler,\n} = makePHEventFunctions(\"renownChainId\");\n\nexport const {\n useValue: useSentryRelease,\n setValue: setSentryRelease,\n addEventHandler: addSentryReleaseEventHandler,\n} = makePHEventFunctions(\"sentryRelease\");\n\nexport const {\n useValue: useSentryDsn,\n setValue: setSentryDsn,\n addEventHandler: addSentryDsnEventHandler,\n} = makePHEventFunctions(\"sentryDsn\");\n\nexport const {\n useValue: useSentryEnv,\n setValue: setSentryEnv,\n addEventHandler: addSentryEnvEventHandler,\n} = makePHEventFunctions(\"sentryEnv\");\n\nexport const {\n useValue: useIsSentryTracingEnabled,\n setValue: setIsSentryTracingEnabled,\n addEventHandler: addIsSentryTracingEnabledEventHandler,\n} = makePHEventFunctions(\"isSentryTracingEnabled\");\n\nexport const {\n useValue: useIsExternalProcessorsEnabled,\n setValue: setIsExternalProcessorsEnabled,\n addEventHandler: addIsExternalProcessorsEnabledEventHandler,\n} = makePHEventFunctions(\"isExternalProcessorsEnabled\");\n\nexport const {\n useValue: useIsExternalPackagesEnabled,\n setValue: setIsExternalPackagesEnabled,\n addEventHandler: addIsExternalPackagesEnabledEventHandler,\n} = makePHEventFunctions(\"isExternalPackagesEnabled\");\n\nconst enabledEditorsEventFunctions = makePHEventFunctions(\"enabledEditors\");\n\n/** Sets the enabled editors for Connect. */\nexport const setEnabledEditors = enabledEditorsEventFunctions.setValue;\n\n/** Gets the enabled editors for Connect. */\nexport const useEnabledEditors = enabledEditorsEventFunctions.useValue;\n\n/** Adds an event handler for when the enabled editors for Connect changes. */\nexport const addEnabledEditorsEventHandler =\n enabledEditorsEventFunctions.addEventHandler;\n\nconst disabledEditorsEventFunctions = makePHEventFunctions(\"disabledEditors\");\n\n/** Sets the disabled editors for Connect. */\nexport const setDisabledEditors = disabledEditorsEventFunctions.setValue;\n\n/** Gets the disabled editors for Connect. */\nexport const useDisabledEditors = disabledEditorsEventFunctions.useValue;\n\n/** Adds an event handler for when the disabled editors for Connect changes. */\nexport const addDisabledEditorsEventHandler =\n disabledEditorsEventFunctions.addEventHandler;\n\nconst isRelationalProcessorsEnabled = makePHEventFunctions(\n \"isRelationalProcessorsEnabled\",\n);\n\n/** Sets the isRelationalProcessorsEnabled for Connect. */\nexport const setIsRelationalProcessorsEnabled =\n isRelationalProcessorsEnabled.setValue;\n\n/** Gets the isRelationalProcessorsEnabled for Connect. */\nexport const useIsRelationalProcessorsEnabled =\n isRelationalProcessorsEnabled.useValue;\n\n/** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */\nexport const addIsRelationalProcessorsEnabledEventHandler =\n isRelationalProcessorsEnabled.addEventHandler;\n\nconst isExternalRelationalProcessorsEnabled = makePHEventFunctions(\n \"isExternalRelationalProcessorsEnabled\",\n);\n\n/** Sets the isExternalRelationalProcessorsEnabled for Connect. */\nexport const setIsExternalRelationalProcessorsEnabled =\n isExternalRelationalProcessorsEnabled.setValue;\n\n/** Gets the isExternalRelationalProcessorsEnabled for Connect. */\nexport const useIsExternalRelationalProcessorsEnabled =\n isExternalRelationalProcessorsEnabled.useValue;\n\n/** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */\nexport const addIsExternalRelationalProcessorsEnabledEventHandler =\n isExternalRelationalProcessorsEnabled.addEventHandler;\n\nconst isAnalyticsEnabledEventFunctions =\n makePHEventFunctions(\"isAnalyticsEnabled\");\n\n/** Sets the isAnalyticsEnabled for Connect. */\nexport const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;\n\n/** Gets the isAnalyticsEnabled for Connect. */\nexport const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */\nexport const addIsAnalyticsEnabledEventHandler =\n isAnalyticsEnabledEventFunctions.addEventHandler;\n\nconst isAnalyticsExternalProcessorsEnabled = makePHEventFunctions(\n \"isAnalyticsExternalProcessorsEnabled\",\n);\n\n/** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */\nexport const setIsAnalyticsExternalProcessorsEnabled =\n isAnalyticsExternalProcessorsEnabled.setValue;\n\n/** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */\nexport const useIsAnalyticsExternalProcessorsEnabled =\n isAnalyticsExternalProcessorsEnabled.useValue;\n\n/** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */\nexport const addIsAnalyticsExternalProcessorsEnabledEventHandler =\n isAnalyticsExternalProcessorsEnabled.addEventHandler;\n\nconst analyticsDatabaseNameEventFunctions = makePHEventFunctions(\n \"analyticsDatabaseName\",\n);\n\n/** Sets the analytics database name for Connect. */\nexport const setAnalyticsDatabaseName =\n analyticsDatabaseNameEventFunctions.setValue;\n\n/** Gets the analytics database name for Connect. */\nexport const useAnalyticsDatabaseName =\n analyticsDatabaseNameEventFunctions.useValue;\n\n/** Adds an event handler for when the analytics database name for Connect changes. */\nexport const addAnalyticsDatabaseNameEventHandler =\n analyticsDatabaseNameEventFunctions.addEventHandler;\n\nconst logLevelEventFunctions = makePHEventFunctions(\"logLevel\");\n\n/** Sets the log level for Connect. */\nexport const setLogLevel = logLevelEventFunctions.setValue;\n\n/** Gets the log level for Connect. */\nexport const useLogLevel = logLevelEventFunctions.useValue;\n\n/** Adds an event handler for when the log level for Connect changes. */\nexport const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;\n\nconst allowListEventFunctions = makePHEventFunctions(\"allowList\");\n\n/** Sets the allow list for Connect. */\nexport const setAllowList = allowListEventFunctions.setValue;\n\n/** Gets the allow list for Connect. */\nexport const useAllowList = allowListEventFunctions.useValue;\n\n/** Adds an event handler for when the allow list for Connect changes. */\nexport const addAllowListEventHandler = allowListEventFunctions.addEventHandler;\n\ntype NonUserConfigKey = Exclude<\n PHGlobalConfigKey,\n PHAppConfigKey | PHDocumentEditorConfigKey\n>;\ntype NonUserConfigSetters = PHGlobalConfigSettersForKey<NonUserConfigKey>;\ntype NonUserConfigHooks = PHGlobalConfigHooksForKey<NonUserConfigKey>;\n\nconst nonUserConfigSetters: NonUserConfigSetters = {\n routerBasename: setRouterBasename,\n version: setVersion,\n requiresHardRefresh: setRequiresHardRefresh,\n warnOutdatedApp: setWarnOutdatedApp,\n studioMode: setStudioMode,\n basePath: setBasePath,\n versionCheckInterval: setVersionCheckInterval,\n cliVersion: setCliVersion,\n fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,\n isDocumentModelSelectionSettingsEnabled:\n setIsDocumentModelSelectionSettingsEnabled,\n gaTrackingId: setGaTrackingId,\n defaultDrivesUrl: setDefaultDrivesUrl,\n drivesPreserveStrategy: setDrivesPreserveStrategy,\n isLocalDrivesEnabled: setIsLocalDrivesEnabled,\n isAddDriveEnabled: setIsAddDriveEnabled,\n isPublicDrivesEnabled: setIsPublicDrivesEnabled,\n isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,\n isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,\n isCloudDrivesEnabled: setIsCloudDrivesEnabled,\n isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,\n isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,\n isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,\n isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,\n isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,\n isEditorReadModeEnabled: setIsEditorReadModeEnabled,\n isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,\n isExternalRelationalProcessorsEnabled:\n setIsExternalRelationalProcessorsEnabled,\n isAnalyticsEnabled: setIsAnalyticsEnabled,\n analyticsDatabaseName: setAnalyticsDatabaseName,\n isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,\n isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,\n isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,\n isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,\n renownUrl: setRenownUrl,\n renownNetworkId: setRenownNetworkId,\n renownChainId: setRenownChainId,\n sentryRelease: setSentryRelease,\n sentryDsn: setSentryDsn,\n sentryEnv: setSentryEnv,\n isSentryTracingEnabled: setIsSentryTracingEnabled,\n isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,\n isExternalPackagesEnabled: setIsExternalPackagesEnabled,\n allowList: setAllowList,\n logLevel: setLogLevel,\n disabledEditors: setDisabledEditors,\n enabledEditors: setEnabledEditors,\n};\n\nexport const phGlobalConfigSetters: PHGlobalConfigSetters = {\n ...phAppConfigSetters,\n ...phDocumentEditorConfigSetters,\n ...nonUserConfigSetters,\n};\n\nconst nonUserConfigHooks: NonUserConfigHooks = {\n routerBasename: useRouterBasename,\n version: useVersion,\n requiresHardRefresh: useRequiresHardRefresh,\n warnOutdatedApp: useWarnOutdatedApp,\n studioMode: useStudioMode,\n basePath: useBasePath,\n versionCheckInterval: useVersionCheckInterval,\n cliVersion: useCliVersion,\n fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,\n isDocumentModelSelectionSettingsEnabled:\n useIsDocumentModelSelectionSettingsEnabled,\n gaTrackingId: useGaTrackingId,\n defaultDrivesUrl: useDefaultDrivesUrl,\n drivesPreserveStrategy: useDrivesPreserveStrategy,\n isAddDriveEnabled: useIsAddDriveEnabled,\n isPublicDrivesEnabled: useIsPublicDrivesEnabled,\n isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,\n isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,\n isCloudDrivesEnabled: useIsCloudDrivesEnabled,\n isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,\n isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,\n isLocalDrivesEnabled: useIsLocalDrivesEnabled,\n isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,\n isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,\n isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,\n isEditorReadModeEnabled: useIsEditorReadModeEnabled,\n isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,\n isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,\n isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,\n renownUrl: useRenownUrl,\n renownNetworkId: useRenownNetworkId,\n renownChainId: useRenownChainId,\n sentryRelease: useSentryRelease,\n sentryDsn: useSentryDsn,\n sentryEnv: useSentryEnv,\n isSentryTracingEnabled: useIsSentryTracingEnabled,\n isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,\n isExternalPackagesEnabled: useIsExternalPackagesEnabled,\n allowList: useAllowList,\n isAnalyticsEnabled: useIsAnalyticsEnabled,\n isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,\n isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,\n isExternalRelationalProcessorsEnabled:\n useIsExternalRelationalProcessorsEnabled,\n analyticsDatabaseName: useAnalyticsDatabaseName,\n logLevel: useLogLevel,\n disabledEditors: useDisabledEditors,\n enabledEditors: useEnabledEditors,\n};\n\nexport const phGlobalConfigHooks: PHGlobalConfigHooks = {\n ...phAppConfigHooks,\n ...phDocumentEditorConfigHooks,\n ...nonUserConfigHooks,\n};\n","import type {\n AddPHGlobalEventHandler,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst featuresEventFunctions = makePHEventFunctions(\"features\");\n\nexport const useFeatures: UsePHGlobalValue<Map<string, boolean>> =\n featuresEventFunctions.useValue;\n\nexport const setFeatures: SetPHGlobalValue<Map<string, boolean>> =\n featuresEventFunctions.setValue;\n\nexport const addFeaturesEventHandler: AddPHGlobalEventHandler =\n featuresEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst packageDiscoveryFunctions = makePHEventFunctions(\n \"packageDiscoveryService\",\n);\n\nexport const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;\nexport const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;\nexport const addPackageDiscoveryServiceEventHandler =\n packageDiscoveryFunctions.addEventHandler;\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 { PHModal } from \"@powerhousedao/reactor-browser\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst modalEventFunctions = makePHEventFunctions(\"modal\");\n\n/** Returns the current modal */\nexport const usePHModal = modalEventFunctions.useValue;\n\n/** Sets the current modal */\nexport const setPHModal = modalEventFunctions.setValue;\n\n/** Adds an event handler for the modal */\nexport const addModalEventHandler = modalEventFunctions.addEventHandler;\n\n/** Shows a modal */\nexport function showPHModal(modal: PHModal) {\n setPHModal(modal);\n}\n\n/** Closes the current modal */\nexport function closePHModal() {\n setPHModal(undefined);\n}\n\n/** Shows the create document modal */\nexport function showCreateDocumentModal(documentType: string) {\n setPHModal({ type: \"createDocument\", documentType });\n}\n\n/** Shows the delete node modal */\nexport function showDeleteNodeModal(nodeOrId: Node | string) {\n const id = typeof nodeOrId === \"string\" ? nodeOrId : nodeOrId.id;\n setPHModal({ type: \"deleteItem\", id });\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport type {\n Database,\n IDocumentModelRegistry,\n IReactorClient,\n ISyncManager,\n} from \"@powerhousedao/reactor\";\nimport type {\n AddPHGlobalEventHandler,\n BrowserReactorClientModule,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"@powerhousedao/reactor-browser\";\nimport type { Kysely } from \"kysely\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst reactorClientModuleEventFunctions = makePHEventFunctions(\n \"reactorClientModule\",\n);\nconst reactorClientEventFunctions = makePHEventFunctions(\"reactorClient\");\n\n/** Returns the reactor client module */\nexport const useReactorClientModule: UsePHGlobalValue<BrowserReactorClientModule> =\n reactorClientModuleEventFunctions.useValue;\n\n/** Sets the reactor client module */\nexport const setReactorClientModule: SetPHGlobalValue<BrowserReactorClientModule> =\n reactorClientModuleEventFunctions.setValue;\n\n/** Adds an event handler for the reactor client module */\nexport const addReactorClientModuleEventHandler: AddPHGlobalEventHandler =\n reactorClientModuleEventFunctions.addEventHandler;\n\n/** Returns the reactor client */\nexport const useReactorClient: UsePHGlobalValue<IReactorClient> =\n reactorClientEventFunctions.useValue;\n\n/** Sets the reactor client */\nexport const setReactorClient: SetPHGlobalValue<IReactorClient> =\n reactorClientEventFunctions.setValue;\n\n/** Adds an event handler for the reactor client */\nexport const addReactorClientEventHandler: AddPHGlobalEventHandler =\n reactorClientEventFunctions.addEventHandler;\n\n// The following are derived from the reactor client module:\n\nexport const useSync = (): ISyncManager | undefined =>\n useReactorClientModule()?.reactorModule?.syncModule?.syncManager;\n\nexport const useSyncList = () => {\n const sync = useSync();\n return sync?.list() ?? [];\n};\n\nexport const useModelRegistry = (): IDocumentModelRegistry | undefined =>\n useReactorClientModule()?.reactorModule?.documentModelRegistry;\n\nexport const useDatabase = (): Kysely<Database> | undefined =>\n useReactorClientModule()?.reactorModule?.database;\n\nexport const usePGlite = (): PGlite | undefined => useReactorClientModule()?.pg;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst revisionHistoryEventFunctions = makePHEventFunctions(\n \"revisionHistoryVisible\",\n);\n\n/** Returns whether revision history is visible */\nexport const useRevisionHistoryVisible = revisionHistoryEventFunctions.useValue;\n\n/** Sets revision history visibility */\nexport const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;\n\n/** Adds event handler for revision history visibility */\nexport const addRevisionHistoryVisibleEventHandler =\n revisionHistoryEventFunctions.addEventHandler;\n\n/** Shows the revision history */\nexport function showRevisionHistory() {\n setRevisionHistoryVisible(true);\n}\n\n/** Hides the revision history */\nexport function hideRevisionHistory() {\n setRevisionHistoryVisible(false);\n}\n","import type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport slug from \"slug\";\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/** Makes a URL component for a node. */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n const nodeName = node.name;\n if (!nodeName) return slug(node.id);\n return slug(`${nodeName}-${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\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n const nodeId = findUuid(nodeSlug);\n return nodeId;\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 const driveId = findUuid(driveSlug);\n return driveId;\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 { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n createUrlWithPreservedParams,\n extractDriveIdFromPath,\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\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n\n/** Returns the selected drive id */\nexport const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Sets the selected drive id */\nconst 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 // Find the drive by slug to get its actual ID\n const drive = window.ph?.drives?.find((d) => d.header.slug === driveSlug);\n const driveId = drive?.header.id;\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\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 {\n createUrlWithPreservedParams,\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n extractNodeSlugFromPath,\n makeNodeSlug,\n resolveUrlPathname,\n} from \"../utils/url.js\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\nconst setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\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\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 const selectedNodeId = window.ph?.selectedNodeId;\n if (nodeSlug !== selectedNodeId) {\n setSelectedNode(nodeSlug);\n }\n });\n}\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedTimelineItemEventFunctions = makePHEventFunctions(\n \"selectedTimelineItem\",\n);\n\n/** Returns the selected timeline item */\nexport const useSelectedTimelineItem =\n selectedTimelineItemEventFunctions.useValue;\n\n/** Sets the selected timeline item */\nexport const setSelectedTimelineItem =\n selectedTimelineItemEventFunctions.setValue;\n\n/** Adds event handler for selected timeline item */\nexport const addSelectedTimelineItemEventHandler =\n selectedTimelineItemEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedTimelineRevisionEventFunctions = makePHEventFunctions(\n \"selectedTimelineRevision\",\n);\n\n/** Returns the selected timeline revision. */\nexport const useSelectedTimelineRevision =\n selectedTimelineRevisionEventFunctions.useValue;\n\n/** Sets the selected timeline revision. */\nexport const setSelectedTimelineRevision =\n selectedTimelineRevisionEventFunctions.setValue;\n\n/** Adds an event handler for the selected timeline revision. */\nexport const addSelectedTimelineRevisionEventHandler =\n selectedTimelineRevisionEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst toastEventFunctions = makePHEventFunctions(\"toast\");\n\n/** Returns the toast function */\nexport const usePHToast = toastEventFunctions.useValue;\n\n/** Sets the toast function */\nexport const setPHToast = toastEventFunctions.setValue;\n\n/** Adds an event handler for the toast */\nexport const addToastEventHandler = toastEventFunctions.addEventHandler;\n","import { DuplicateModuleError } from \"@powerhousedao/reactor\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\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\n/** Returns all of the Vetra packages loaded by the Connect instance */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n\n return useSyncExternalStore(\n (cb) => (packageManager ? packageManager.subscribe(cb) : () => {}),\n () => packageManager?.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 packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages.flatMap((pkg) => pkg.documentModels);\n\n const registry =\n window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n for (const module of documentModelModules) {\n try {\n registry.registerModules(module);\n } catch (error) {\n if (DuplicateModuleError.isError(error)) {\n const documentType = module.documentModel.global.id;\n registry.unregisterModules(documentType);\n registry.registerModules(module);\n continue;\n }\n throw error;\n }\n }\n}\n","import type { PHGlobalEventHandlerAdders } from \"../types/global.js\";\nimport {\n addAllowListEventHandler,\n addAnalyticsDatabaseNameEventHandler,\n addBasePathEventHandler,\n addCliVersionEventHandler,\n addDefaultDrivesUrlEventHandler,\n addDisabledEditorsEventHandler,\n addDrivesPreserveStrategyEventHandler,\n addEnabledEditorsEventHandler,\n addFileUploadOperationsChunkSizeEventHandler,\n addGaTrackingIdEventHandler,\n addIsAddCloudDrivesEnabledEventHandler,\n addIsAddDriveEnabledEventHandler,\n addIsAddLocalDrivesEnabledEventHandler,\n addIsAddPublicDrivesEnabledEventHandler,\n addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n addIsAnalyticsEnabledEventHandler,\n addIsAnalyticsExternalProcessorsEnabledEventHandler,\n addIsCloudDrivesEnabledEventHandler,\n addIsDeleteCloudDrivesEnabledEventHandler,\n addIsDeleteLocalDrivesEnabledEventHandler,\n addIsDeletePublicDrivesEnabledEventHandler,\n addIsDiffAnalyticsEnabledEventHandler,\n addIsDocumentModelSelectionSettingsEnabledEventHandler,\n addIsDriveAnalyticsEnabledEventHandler,\n addIsEditorDebugModeEnabledEventHandler,\n addIsEditorReadModeEnabledEventHandler,\n addIsExternalPackagesEnabledEventHandler,\n addIsExternalProcessorsEnabledEventHandler,\n addIsExternalRelationalProcessorsEnabledEventHandler,\n addIsLocalDrivesEnabledEventHandler,\n addIsPublicDrivesEnabledEventHandler,\n addIsRelationalProcessorsEnabledEventHandler,\n addIsSentryTracingEnabledEventHandler,\n addLogLevelEventHandler,\n addRenownChainIdEventHandler,\n addRenownNetworkIdEventHandler,\n addRenownUrlEventHandler,\n addRequiresHardRefreshEventHandler,\n addRouterBasenameEventHandler,\n addSentryDsnEventHandler,\n addSentryEnvEventHandler,\n addSentryReleaseEventHandler,\n addStudioModeEventHandler,\n addVersionCheckIntervalEventHandler,\n addVersionEventHandler,\n addWarnOutdatedAppEventHandler,\n} from \"./config/connect.js\";\nimport { addFeaturesEventHandler } from \"./features.js\";\n\nimport {\n addAllowedDocumentTypesEventHandler,\n addIsDragAndDropEnabledEventHandler,\n addIsExternalControlsEnabledEventHandler,\n} from \"./config/editor.js\";\nimport { addDocumentCacheEventHandler } from \"./document-cache.js\";\nimport { addPackageDiscoveryServiceEventHandler } from \"./package-discovery.js\";\nimport { addDrivesEventHandler } from \"./drives.js\";\nimport { addLoadingEventHandler } from \"./loading.js\";\nimport { addModalEventHandler } from \"./modals.js\";\nimport {\n addReactorClientEventHandler,\n addReactorClientModuleEventHandler,\n} from \"./reactor.js\";\nimport { addRenownEventHandler } from \"./renown.js\";\nimport { addRevisionHistoryVisibleEventHandler } from \"./revision-history.js\";\nimport {\n addSelectedDriveIdEventHandler,\n addSetSelectedDriveOnPopStateEventHandler,\n} from \"./selected-drive.js\";\nimport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n addSetSelectedNodeOnPopStateEventHandler,\n} from \"./selected-node.js\";\nimport { addSelectedTimelineItemEventHandler } from \"./selected-timeline-item.js\";\nimport { addSelectedTimelineRevisionEventHandler } from \"./timeline-revision.js\";\nimport { addToastEventHandler } from \"./toast.js\";\nimport { addVetraPackageManagerEventHandler } from \"./vetra-packages.js\";\n\nconst phGlobalEventHandlerRegisterFunctions: PHGlobalEventHandlerAdders = {\n loading: addLoadingEventHandler,\n reactorClientModule: addReactorClientModuleEventHandler,\n reactorClient: addReactorClientEventHandler,\n features: addFeaturesEventHandler,\n modal: addModalEventHandler,\n renown: addRenownEventHandler,\n drives: addDrivesEventHandler,\n documentCache: addDocumentCacheEventHandler,\n selectedDriveId: () => {\n addSelectedDriveIdEventHandler();\n addSetSelectedDriveOnPopStateEventHandler();\n addResetSelectedNodeEventHandler();\n },\n selectedNodeId: () => {\n addSelectedNodeIdEventHandler();\n addSetSelectedNodeOnPopStateEventHandler();\n },\n vetraPackageManager: addVetraPackageManagerEventHandler,\n packageDiscoveryService: addPackageDiscoveryServiceEventHandler,\n selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,\n revisionHistoryVisible: addRevisionHistoryVisibleEventHandler,\n selectedTimelineItem: addSelectedTimelineItemEventHandler,\n routerBasename: addRouterBasenameEventHandler,\n version: addVersionEventHandler,\n logLevel: addLogLevelEventHandler,\n requiresHardRefresh: addRequiresHardRefreshEventHandler,\n warnOutdatedApp: addWarnOutdatedAppEventHandler,\n studioMode: addStudioModeEventHandler,\n basePath: addBasePathEventHandler,\n versionCheckInterval: addVersionCheckIntervalEventHandler,\n cliVersion: addCliVersionEventHandler,\n fileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,\n isDocumentModelSelectionSettingsEnabled:\n addIsDocumentModelSelectionSettingsEnabledEventHandler,\n gaTrackingId: addGaTrackingIdEventHandler,\n allowList: addAllowListEventHandler,\n defaultDrivesUrl: addDefaultDrivesUrlEventHandler,\n drivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,\n allowedDocumentTypes: addAllowedDocumentTypesEventHandler,\n enabledEditors: addEnabledEditorsEventHandler,\n disabledEditors: addDisabledEditorsEventHandler,\n isAddDriveEnabled: addIsAddDriveEnabledEventHandler,\n isLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,\n isPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,\n isAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,\n isDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,\n isCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,\n isAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,\n isDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,\n isAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,\n isDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,\n isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,\n isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,\n isEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,\n isEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,\n isRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,\n isExternalRelationalProcessorsEnabled:\n addIsExternalRelationalProcessorsEnabledEventHandler,\n isAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,\n isAnalyticsExternalProcessorsEnabled:\n addIsAnalyticsExternalProcessorsEnabledEventHandler,\n analyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,\n isAnalyticsDatabaseWorkerEnabled:\n addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n isDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,\n isDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,\n renownUrl: addRenownUrlEventHandler,\n renownNetworkId: addRenownNetworkIdEventHandler,\n renownChainId: addRenownChainIdEventHandler,\n sentryRelease: addSentryReleaseEventHandler,\n sentryDsn: addSentryDsnEventHandler,\n sentryEnv: addSentryEnvEventHandler,\n isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,\n isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,\n isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,\n toast: addToastEventHandler,\n};\nexport function addPHEventHandlers() {\n for (const fn of Object.values(phGlobalEventHandlerRegisterFunctions)) {\n fn();\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.flatMap((pkg) => pkg.documentModels);\n}\n\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n return documentModelModules?.find(\n (module) => module.documentModel.global.id === id,\n );\n}\n","import { useAllowedDocumentTypes } from \"./config/editor.js\";\nimport { useDocumentModelModules } from \"./document-model-modules.js\";\n\nexport function useAllowedDocumentModelModules() {\n const documentModelModules = useDocumentModelModules();\n const allowedDocumentTypes = useAllowedDocumentTypes();\n if (!allowedDocumentTypes?.length) return documentModelModules;\n return documentModelModules?.filter((module) =>\n allowedDocumentTypes.includes(module.documentModel.global.id),\n );\n}\n","import type { FolderNode } from \"@powerhousedao/shared/document-drive\";\nimport { isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected folder. */\nexport function useSelectedFolder(): FolderNode | undefined {\n const selectedNode = useSelectedNode();\n if (isFolderNodeKind(selectedNode)) return selectedNode;\n return undefined;\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { sortNodesByName } from \"../utils/nodes.js\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\n\n/** Returns the child nodes for the selected drive or folder. */\nexport function useNodesInSelectedDriveOrFolder(): Node[] {\n const nodes = useNodesInSelectedDrive();\n const selectedFolder = useSelectedFolder();\n const selectedFolderId = selectedFolder?.id;\n if (!nodes) return [];\n if (!selectedFolderId)\n return sortNodesByName(nodes.filter((n) => !n.parentFolder));\n return sortNodesByName(\n nodes.filter((n) => n.parentFolder === selectedFolderId),\n );\n}\n","import type {\n PHAppConfig,\n PHAppConfigKey,\n PHDocumentEditorConfig,\n PHDocumentEditorConfigKey,\n PHGlobalConfig,\n PHGlobalConfigKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { phGlobalConfigSetters } from \"./connect.js\";\nimport { phAppConfigSetters, phDocumentEditorConfigSetters } from \"./editor.js\";\n\nexport function setPHGlobalConfigByKey<TKey extends PHGlobalConfigKey>(\n key: TKey,\n value: PHGlobalConfig[TKey] | undefined,\n) {\n const setter = phGlobalConfigSetters[key];\n setter(value);\n}\n\nexport function setPHAppConfigByKey<TKey extends PHAppConfigKey>(\n key: TKey,\n value: PHAppConfig[TKey] | undefined,\n) {\n const setter = phAppConfigSetters[key];\n setter(value);\n}\n\nexport function setPHDocumentEditorConfigByKey<\n TKey extends PHDocumentEditorConfigKey,\n>(key: TKey, value: PHDocumentEditorConfig[TKey] | undefined) {\n const setter = phDocumentEditorConfigSetters[key];\n setter(value);\n}\n","import type {\n PHGlobalConfig,\n PHGlobalConfigKey,\n PHGlobalConfigSetters,\n} from \"@powerhousedao/reactor-browser\";\nimport { phGlobalConfigSetters } from \"./connect.js\";\n\nexport function callGlobalSetterForKey<TKey extends PHGlobalConfigKey>(\n key: TKey,\n value: PHGlobalConfig[TKey] | undefined,\n) {\n const setter = phGlobalConfigSetters[key] as PHGlobalConfigSetters[TKey];\n setter(value);\n}\n","import type {\n PHAppConfig,\n PHAppConfigKey,\n PHDocumentEditorConfig,\n PHDocumentEditorConfigKey,\n PHGlobalConfig,\n PHGlobalConfigKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useState } from \"react\";\nimport { callGlobalSetterForKey } from \"./utils.js\";\n\nexport function setDefaultPHGlobalConfig(config: PHGlobalConfig) {\n for (const key of Object.keys(config) as PHGlobalConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\nexport function useSetDefaultPHGlobalConfig(config: PHGlobalConfig) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setDefaultPHGlobalConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n\nexport function useResetPHGlobalConfig(defaultConfigForReset: PHGlobalConfig) {\n return function reset() {\n setPHGlobalConfig(defaultConfigForReset);\n };\n}\n\nexport function setPHGlobalConfig(config: Partial<PHGlobalConfig>) {\n for (const key of Object.keys(config) as PHGlobalConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\nexport function useSetPHGlobalConfig(config: Partial<PHGlobalConfig>) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setPHGlobalConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n\n/** Sets the global drive config.\n *\n * Pass in a partial object of the global drive config to set.\n */\nexport function setPHAppConfig(config: Partial<PHAppConfig>) {\n for (const key of Object.keys(config) as PHAppConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\n/** Sets the global document config.\n *\n * Pass in a partial object of the global document config to set.\n */\nexport function setPHDocumentEditorConfig(\n config: Partial<PHDocumentEditorConfig>,\n) {\n for (const key of Object.keys(config) as PHDocumentEditorConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\n/** Wrapper hook for setting the global app config.\n *\n * Automatically sets the global app config when the component mounts.\n *\n * Pass in a partial object of the global app config to set.\n */\nexport function useSetPHAppConfig(config: Partial<PHAppConfig>) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setPHAppConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n\n/** Wrapper hook for setting the global document editor config.\n *\n * Automatically sets the global document editor config when the component mounts.\n *\n * Pass in a partial object of the global document editor config to set.\n */\nexport function useSetPHDocumentEditorConfig(\n config: Partial<PHDocumentEditorConfig>,\n) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setPHDocumentEditorConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n","import type {\n PHAppConfigKey,\n PHDocumentEditorConfigKey,\n PHGlobalConfigKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { phGlobalConfigHooks } from \"./connect.js\";\nimport { phAppConfigHooks, phDocumentEditorConfigHooks } from \"./editor.js\";\n\nexport function usePHGlobalConfigByKey<TKey extends PHGlobalConfigKey>(\n key: TKey,\n) {\n const useValueHook = phGlobalConfigHooks[key];\n return useValueHook();\n}\n\n/** Gets the value of an item in the global drive config for a given key.\n *\n * Strongly typed, inferred from type definition for the key.\n */\nexport function usePHAppConfigByKey<TKey extends PHAppConfigKey>(key: TKey) {\n const useValueHook = phAppConfigHooks[key];\n return useValueHook();\n}\n\n/** Gets the value of an item in the global document config for a given key.\n *\n * Strongly typed, inferred from type definition for the key.\n */\nexport function usePHDocumentEditorConfigByKey<\n TKey extends PHDocumentEditorConfigKey,\n>(key: TKey) {\n const useValueHook = phDocumentEditorConfigHooks[key];\n return useValueHook();\n}\n","import type { ConnectionStateSnapshot } from \"@powerhousedao/reactor\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useSync } from \"./reactor.js\";\n\n/**\n * Returns a map of remote name to connection state snapshot for all remotes.\n * Re-renders when any remote's connection state changes.\n */\nexport function useConnectionStates(): ReadonlyMap<\n string,\n ConnectionStateSnapshot\n> {\n const syncManager = useSync();\n const [states, setStates] = useState<\n ReadonlyMap<string, ConnectionStateSnapshot>\n >(() => buildSnapshot(syncManager));\n const unsubscribesRef = useRef<Array<() => void>>([]);\n\n useEffect(() => {\n if (!syncManager) return;\n\n function subscribe() {\n // Clean up previous subscriptions\n for (const unsub of unsubscribesRef.current) {\n unsub();\n }\n unsubscribesRef.current = [];\n\n const remotes = syncManager!.list();\n for (const remote of remotes) {\n const unsub = remote.channel.onConnectionStateChange(() => {\n setStates(buildSnapshot(syncManager));\n });\n unsubscribesRef.current.push(unsub);\n }\n\n // Set initial state\n setStates(buildSnapshot(syncManager));\n }\n\n subscribe();\n\n // Re-subscribe periodically to pick up added/removed remotes\n const interval = setInterval(subscribe, 5000);\n\n return () => {\n clearInterval(interval);\n for (const unsub of unsubscribesRef.current) {\n unsub();\n }\n unsubscribesRef.current = [];\n };\n }, [syncManager]);\n\n return states;\n}\n\n/**\n * Returns the connection state snapshot for a specific remote by name.\n */\nexport function useConnectionState(\n remoteName: string,\n): ConnectionStateSnapshot | undefined {\n const states = useConnectionStates();\n return states.get(remoteName);\n}\n\nfunction buildSnapshot(\n syncManager: ReturnType<typeof useSync>,\n): ReadonlyMap<string, ConnectionStateSnapshot> {\n const map = new Map<string, ConnectionStateSnapshot>();\n if (!syncManager) return map;\n for (const remote of syncManager.list()) {\n map.set(remote.name, remote.channel.getConnectionState());\n }\n return map;\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useReactorClient } from \"./reactor.js\";\n\ntype InternalState = {\n globalOperations: Operation[];\n localOperations: Operation[];\n isLoading: boolean;\n error: Error | undefined;\n};\n\ntype DocumentOperationsState = InternalState & {\n refetch: () => void;\n};\n\n/**\n * Hook to fetch document operations via the reactor client.\n * Operations are no longer auto-populated on documents and must be fetched explicitly.\n *\n * @param documentId - The document ID to fetch operations for\n * @returns Object containing globalOperations, localOperations, isLoading, and error\n */\nexport function useDocumentOperations(\n documentId: string | null | undefined,\n): DocumentOperationsState {\n const reactorClient = useReactorClient();\n const hasFetchedRef = useRef(false);\n const [state, setState] = useState<InternalState>(() => ({\n globalOperations: [],\n localOperations: [],\n isLoading: !!documentId,\n error: undefined,\n }));\n\n const fetchOperations = useCallback(\n async (retryCount = 0): Promise<void> => {\n const MAX_RETRIES = 5;\n const RETRY_DELAY_MS = 500;\n\n if (!documentId || !reactorClient) {\n setState({\n globalOperations: [],\n localOperations: [],\n isLoading: false,\n error: undefined,\n });\n return;\n }\n\n setState((prev) => ({ ...prev, isLoading: true, error: undefined }));\n\n let globalOps: Operation[] = [];\n let localOps: Operation[] = [];\n let fetchError: Error | undefined;\n\n try {\n const globalResult = await reactorClient.getOperations(documentId, {\n scopes: [\"global\"],\n });\n globalOps = globalResult.results;\n } catch (err) {\n fetchError = err instanceof Error ? err : new Error(String(err));\n }\n\n if (!fetchError) {\n try {\n const localResult = await reactorClient.getOperations(documentId, {\n scopes: [\"local\"],\n });\n localOps = localResult.results;\n } catch (err) {\n fetchError = err instanceof Error ? err : new Error(String(err));\n }\n }\n\n // If no operations found and we haven't exhausted retries, wait and try again\n // This handles eventual consistency where operations may not be immediately available\n if (\n !fetchError &&\n globalOps.length === 0 &&\n localOps.length === 0 &&\n retryCount < MAX_RETRIES\n ) {\n await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));\n return fetchOperations(retryCount + 1);\n }\n\n setState({\n globalOperations: globalOps,\n localOperations: localOps,\n isLoading: false,\n error: fetchError,\n });\n hasFetchedRef.current = true;\n },\n [documentId, reactorClient],\n );\n\n useEffect(() => {\n if (documentId && reactorClient) {\n void fetchOperations();\n } else if (!documentId) {\n setState({\n globalOperations: [],\n localOperations: [],\n isLoading: false,\n error: undefined,\n });\n hasFetchedRef.current = false;\n }\n }, [documentId, reactorClient, fetchOperations]);\n\n // Wrap fetchOperations to hide the internal retry parameter\n const refetch = useCallback(() => {\n void fetchOperations(0);\n }, [fetchOperations]);\n\n return { ...state, refetch };\n}\n","import { useDocumentModelModules } from \"./document-model-modules.js\";\n\n/** Returns the supported document types for the reactor (derived from the document model modules) */\nexport function useSupportedDocumentTypesInReactor() {\n const documentModelModules = useDocumentModelModules();\n return documentModelModules?.map((module) => module.documentModel.global.id);\n}\n","import { useAllowedDocumentTypes } from \"./config/editor.js\";\nimport { useSupportedDocumentTypesInReactor } from \"./supported-document-types.js\";\n\n/** Returns the document types a app supports.\n *\n * If present, uses the `allowedDocumentTypes` config value.\n * Otherwise, uses the supported document types from the reactor.\n */\nexport function useDocumentTypes() {\n const allowedDocumentTypes = useAllowedDocumentTypes();\n const supportedDocumentTypes = useSupportedDocumentTypesInReactor();\n return allowedDocumentTypes ?? supportedDocumentTypes;\n}\n","import type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentDispatch } from \"../types/documents.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDrives } from \"./drives.js\";\n\nexport function useDriveById(\n driveId: string | undefined | null,\n): [DocumentDriveDocument, DocumentDispatch<DocumentDriveAction>] {\n const drives = useDrives();\n const foundDrive = drives?.find((drive) => drive.header.id === driveId);\n const [drive, dispatch] = useDispatch(foundDrive);\n if (!foundDrive) {\n throw new Error(`Drive with id ${driveId} not found`);\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n","import type { EditorModule } from \"document-model\";\nimport { DEFAULT_DRIVE_EDITOR_ID } from \"../constants.js\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useEditorModules(): EditorModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.editors)\n .filter(\n (module) => !module.documentTypes.includes(\"powerhouse/document-drive\"),\n );\n}\n\nexport function useAppModules(): EditorModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.editors)\n .filter((module) =>\n module.documentTypes.includes(\"powerhouse/document-drive\"),\n );\n}\n\nexport function useFallbackEditorModule(\n documentType: string | null | undefined,\n): EditorModule | undefined {\n const editorModules = useEditorModules();\n if (!documentType) return undefined;\n if (editorModules?.length === 0) return undefined;\n\n const modulesForType = editorModules?.filter((module) =>\n module.documentTypes.includes(documentType),\n );\n return modulesForType?.[0];\n}\n\nexport function useAppModuleById(\n id: string | null | undefined,\n): EditorModule | undefined {\n const appModules = useAppModules();\n return appModules?.find((module) => module.config.id === id);\n}\n\nexport function useDefaultAppModule(): EditorModule | undefined {\n const defaultAppModule = useAppModuleById(DEFAULT_DRIVE_EDITOR_ID);\n return defaultAppModule;\n}\n\nexport function useEditorModuleById(\n id: string | null | undefined,\n): EditorModule | undefined {\n const editorModules = useEditorModules();\n return editorModules?.find((module) => module.config.id === id);\n}\n\nexport function useEditorModulesForDocumentType(\n documentType: string | null | undefined,\n) {\n const editorModules = useEditorModules();\n if (!documentType) return undefined;\n\n const modulesForType = editorModules?.filter((module) =>\n module.documentTypes.includes(documentType),\n );\n return modulesForType;\n}\n","import type { FolderNode } from \"@powerhousedao/shared/document-drive\";\nimport { useFolderNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\n\nexport function useFolderById(\n id: string | null | undefined,\n): FolderNode | undefined {\n const folders = useFolderNodesInSelectedDrive();\n return folders?.find((n) => n.id === id);\n}\n","import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport {\n useDocumentsInSelectedDrive,\n useNodesInSelectedDrive,\n} from \"./items-in-selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\n\n/** Returns the nodes in the selected folder. */\nexport function useNodesInSelectedFolder(): Node[] | undefined {\n const selectedFolder = useSelectedFolder();\n const nodes = useNodesInSelectedDrive();\n if (!selectedFolder || !nodes) return undefined;\n\n return nodes.filter((n) => n.parentFolder === selectedFolder.id);\n}\n\n/** Returns the file nodes in the selected folder. */\nexport function useFileNodesInSelectedFolder(): FileNode[] | undefined {\n const nodes = useNodesInSelectedFolder();\n if (!nodes) return undefined;\n return nodes.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected folder. */\nexport function useFolderNodesInSelectedFolder(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedFolder();\n if (!nodes) return undefined;\n return nodes.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected folder. */\nexport function useDocumentsInSelectedFolder(): PHDocument[] | undefined {\n const documents = useDocumentsInSelectedDrive();\n const fileNodes = useFileNodesInSelectedFolder();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return documents?.filter((d) => fileNodeIds?.includes(d.header.id));\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport {\n addFile,\n addFolder,\n copyNode,\n moveNode,\n renameDriveNode,\n renameNode,\n} from \"../actions/document.js\";\nimport { useDrives } from \"./drives.js\";\nimport { useFolderById } from \"./folder-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\nimport { setSelectedNode, useSelectedNode } from \"./selected-node.js\";\n\nfunction resolveNode(driveId: string, node: Node | undefined) {\n return node?.id !== driveId ? node : undefined;\n}\n\nexport function useNodeActions() {\n const [selectedDrive] = useSelectedDriveSafe();\n const selectedFolder = useSelectedFolder();\n const selectedNode = useSelectedNode();\n const selectedParentFolder = useFolderById(selectedNode?.parentFolder);\n const selectedDriveId = selectedDrive?.header.id;\n const drives = useDrives();\n\n async function onAddFile(file: File, parent: Node | undefined) {\n if (!selectedDriveId) return;\n\n const fileName = file.name.replace(/\\..+/gim, \"\");\n\n return addFile(\n file,\n selectedDriveId,\n fileName,\n resolveNode(selectedDriveId, parent)?.id,\n );\n }\n\n async function onAddFolder(name: string, parent: Node | undefined) {\n if (!selectedDriveId) return;\n\n return addFolder(\n selectedDriveId,\n name,\n resolveNode(selectedDriveId, parent)?.id,\n );\n }\n\n async function onRenameNode(\n newName: string,\n node: Node,\n ): Promise<Node | undefined> {\n if (!selectedDriveId) return;\n\n const resolvedNode = resolveNode(selectedDriveId, node);\n if (!resolvedNode) {\n console.error(`Node ${node.id} not found`);\n return;\n }\n\n return await renameNode(selectedDriveId, node.id, newName);\n }\n\n async function onCopyNode(src: Node, target: Node | undefined) {\n if (!selectedDriveId) return;\n const resolvedSrc = resolveNode(selectedDriveId, src);\n if (!resolvedSrc) {\n console.error(`Node ${src.id} not found`);\n return;\n }\n const resolvedTarget = resolveNode(selectedDriveId, target);\n\n await copyNode(selectedDriveId, resolvedSrc, resolvedTarget);\n }\n\n async function onMoveNode(src: Node, target: Node | undefined) {\n if (!selectedDriveId) return;\n\n const resolvedSrc = resolveNode(selectedDriveId, src);\n if (!resolvedSrc) {\n console.error(`Node ${src.id} not found`);\n return;\n }\n const resolvedTarget = resolveNode(selectedDriveId, target);\n\n // if node is already on target then ignore move\n if (\n (!resolvedTarget?.id && !src.parentFolder) ||\n resolvedTarget?.id === src.parentFolder\n ) {\n return;\n }\n await moveNode(selectedDriveId, resolvedSrc, resolvedTarget);\n }\n\n async function onDuplicateNode(src: Node) {\n if (!selectedDriveId) return;\n\n const resolvedSrc = resolveNode(selectedDriveId, src);\n if (!resolvedSrc) {\n console.error(`Node ${src.id} not found`);\n return;\n }\n\n const target = resolveNode(\n selectedDriveId,\n selectedFolder ?? selectedParentFolder,\n );\n await copyNode(selectedDriveId, resolvedSrc, target);\n }\n async function onAddAndSelectNewFolder(name: string) {\n if (!name) return;\n if (!selectedDriveId) return;\n\n const resolvedTarget = resolveNode(\n selectedDriveId,\n selectedFolder ?? selectedParentFolder,\n );\n if (!resolvedTarget) return;\n\n const newFolder = await onAddFolder(name, resolvedTarget);\n\n if (newFolder) {\n setSelectedNode(newFolder);\n }\n }\n\n async function onRenameDriveNodes(\n newName: string,\n nodeId: string,\n ): Promise<void> {\n if (!drives) return;\n\n // Find all drives that contain this node\n const drivesWithNode = drives.filter((drive) =>\n drive.state.global.nodes.some((n) => n.id === nodeId),\n );\n\n // Update node name in all parent drives\n await Promise.all(\n drivesWithNode.map((drive) =>\n renameDriveNode(drive.header.id, nodeId, newName),\n ),\n );\n }\n\n return {\n onAddFile,\n onAddFolder,\n onRenameNode,\n onCopyNode,\n onMoveNode,\n onDuplicateNode,\n onAddAndSelectNewFolder,\n onRenameDriveNodes,\n };\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\n\n/** Returns a node in the selected drive by id. */\nexport function useNodeById(id: string | null | undefined): Node | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === id);\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the path to a node in the selected drive */\nexport function useNodePathById(id: string | null | undefined) {\n const nodes = useNodesInSelectedDrive();\n if (!nodes) return [];\n\n const path: Node[] = [];\n let current = nodes.find((n) => n.id === id);\n\n while (current) {\n path.push(current);\n if (!current.parentFolder) break;\n current = nodes.find((n) => n.id === current?.parentFolder);\n }\n\n return path.reverse();\n}\n\n/** Returns the path to the currently selected node in the selected drive. */\nexport function useSelectedNodePath() {\n const selectedNode = useSelectedNode();\n return useNodePathById(selectedNode?.id);\n}\n","import type { FolderNode } from \"@powerhousedao/shared/document-drive\";\nimport { useFolderById } from \"./folder-by-id.js\";\nimport { useNodeById } from \"./node-by-id.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\nexport function useNodeParentFolderById(\n id: string | null | undefined,\n): FolderNode | undefined {\n const node = useNodeById(id);\n const parentFolder = useFolderById(node?.parentFolder);\n return parentFolder;\n}\n\nexport function useParentFolderForSelectedNode() {\n const node = useSelectedNode();\n return useNodeParentFolderById(node?.id);\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { NoSelectedDocumentError } from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id */\nexport function useSelectedDocumentId(): string | undefined {\n const selectedNode = useSelectedNode();\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const selectedDocumentId = useSelectedDocumentId();\n const [document, dispatch] = useDocumentById(selectedDocumentId);\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const selectedDocumentId = useSelectedDocumentId();\n return useDocumentById(selectedDocumentId);\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const documentId = useSelectedDocumentId();\n\n if (!documentType) {\n return [];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return useDocumentOfType<TDocument, TAction>(documentId, documentType);\n}\n","import type { SubgraphModule } from \"@powerhousedao/shared/document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useSubgraphModules(): SubgraphModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages.flatMap((pkg) => pkg.subgraphs || []);\n}\n","import { useFeatures } from \"./features.js\";\n\nconst FEATURE_INSPECTOR_ENABLED = \"FEATURE_INSPECTOR_ENABLED\";\nconst FEATURE_INSPECTOR_ENABLED_DEFAULT = false;\n\n/**\n * Synchronous helper to check if inspector is enabled.\n */\nexport function isInspectorEnabledSync(): boolean {\n return (\n window.ph?.features?.get(FEATURE_INSPECTOR_ENABLED) ??\n FEATURE_INSPECTOR_ENABLED_DEFAULT\n );\n}\n\n/**\n * React hook to check if inspector is enabled.\n */\nexport function useInspectorEnabled(): boolean {\n const features = useFeatures();\n return (\n features?.get(FEATURE_INSPECTOR_ENABLED) ??\n FEATURE_INSPECTOR_ENABLED_DEFAULT\n );\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { SyncStatus } from \"@powerhousedao/reactor\";\nimport type {\n DocumentDriveDocument,\n SharingType,\n} from \"@powerhousedao/shared/document-drive\";\n\n// legacy sync status types\nexport type UISyncStatus =\n | \"INITIAL_SYNC\"\n | \"SUCCESS\"\n | \"CONFLICT\"\n | \"MISSING\"\n | \"ERROR\"\n | \"SYNCING\";\n\nconst syncStatusToUI: Record<SyncStatus, UISyncStatus> = {\n [SyncStatus.Synced]: \"SUCCESS\",\n [SyncStatus.Outgoing]: \"SYNCING\",\n [SyncStatus.Incoming]: \"SYNCING\",\n [SyncStatus.OutgoingAndIncoming]: \"SYNCING\",\n [SyncStatus.Error]: \"ERROR\",\n};\n\nexport async function getDrives(\n reactor: IReactorClient,\n): Promise<DocumentDriveDocument[]> {\n const results = await reactor.find({\n type: \"powerhouse/document-drive\",\n });\n return results.results as DocumentDriveDocument[];\n}\n\nexport function getSyncStatus(\n documentId: string,\n sharingType: SharingType,\n): Promise<UISyncStatus | undefined> {\n return Promise.resolve(getSyncStatusSync(documentId, sharingType));\n}\n\nexport function getSyncStatusSync(\n documentId: string,\n sharingType: SharingType,\n): UISyncStatus | undefined {\n if (sharingType === \"LOCAL\") return;\n\n const syncManager =\n window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n if (!syncManager) return;\n\n const status = syncManager.getSyncStatus(documentId);\n if (status === undefined) return;\n\n return syncStatusToUI[status];\n}\n","import type {\n DocumentModelDocument,\n PHDocument,\n ValidationError,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n validateInitialState,\n validateModules,\n validateStateSchemaName,\n} from \"@powerhousedao/shared/document-model\";\n\nexport const validateDocument = (document: PHDocument) => {\n const errors: ValidationError[] = [];\n\n if (document.header.documentType !== \"powerhouse/document-model\") {\n return errors;\n }\n\n const doc = document as DocumentModelDocument;\n const specs = doc.state.global.specifications[0];\n\n // validate initial state errors\n const initialStateErrors = Object.keys(specs.state).reduce<ValidationError[]>(\n (acc, scopeKey) => {\n const scope = scopeKey as keyof typeof specs.state;\n\n return [\n ...acc,\n ...validateInitialState(\n specs.state[scope].initialValue,\n scope !== \"global\",\n ).map((err) => ({\n ...err,\n message: `${err.message}. Scope: ${scope}`,\n details: { ...err.details, scope },\n })),\n ];\n },\n [],\n );\n\n // validate schema state errors\n const schemaStateErrors = Object.keys(specs.state).reduce<ValidationError[]>(\n (acc, scopeKey) => {\n const scope = scopeKey as keyof typeof specs.state;\n const isGlobalScope = scope === \"global\";\n\n return [\n ...acc,\n ...validateStateSchemaName(\n specs.state[scope].schema,\n doc.state.global?.name || doc.header.name || \"\",\n !isGlobalScope ? scope : \"\",\n !isGlobalScope,\n ).map((err) => ({\n ...err,\n message: `${err.message}. Scope: ${scope}`,\n details: { ...err.details, scope },\n })),\n ];\n },\n [],\n );\n\n // modules validation\n const modulesErrors = validateModules(specs.modules);\n\n return [...initialStateErrors, ...schemaStateErrors, ...modulesErrors];\n};\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { exportFile } from \"../actions/document.js\";\nimport { showPHModal } from \"../hooks/modals.js\";\nimport { validateDocument } from \"./validate-document.js\";\n\nexport const exportDocument = (document?: PHDocument) => {\n if (!document) return;\n const validationErrors = validateDocument(document);\n\n if (validationErrors.length) {\n showPHModal({\n type: \"exportDocumentWithErrors\",\n documentId: document.header.id,\n });\n } else {\n return exportFile(document);\n }\n};\n","import type { Operation } from \"@powerhousedao/shared/document-model\";\n\nexport const getRevisionFromDate = (\n startDate?: Date,\n endDate?: Date,\n operations: Operation[] = [],\n) => {\n if (!startDate || !endDate) return 0;\n\n const operation = operations.find((operation) => {\n const operationDate = new Date(operation.timestampUtcMs);\n return operationDate >= startDate && operationDate <= endDate;\n });\n\n return operation ? operation.index : 0;\n};\n","import * as lzString from \"lz-string\";\n\nexport async function getDriveIdBySlug(driveUrl: string, slug: string) {\n if (!driveUrl) {\n return;\n }\n\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"drives\"); // add /drives\n const drivesUrl = urlParts.join(\"/\");\n const result = await fetch(drivesUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n query: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n variables: {\n slug,\n },\n }),\n });\n\n const data = (await result.json()) as {\n data: { driveIdBySlug: string };\n };\n\n return data.data.driveIdBySlug;\n}\n\nexport function getSlugFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n return urlParts.pop();\n}\n\nexport function getSwitchboardGatewayUrlFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"graphql\"); // add /graphql\n return urlParts.join(\"/\");\n}\n\nexport function getDocumentGraphqlQuery() {\n return `query getDocument($documentId: String!) {\n document(id: $documentId) {\n id\n documentType\n createdAtUtcIso\n lastModifiedAtUtcIso\n name\n revision\n stateJSON\n }\n }`;\n}\n\nexport function buildDocumentSubgraphQuery(\n driveUrl: string,\n documentId: string,\n authToken?: string,\n) {\n const driveSlug = getSlugFromDriveUrl(driveUrl);\n const query = getDocumentGraphqlQuery();\n const variables = { documentId, driveId: driveSlug };\n const headers = authToken\n ? {\n Authorization: `Bearer ${authToken}`,\n }\n : undefined;\n\n const payload: Record<string, string> = {\n document: query.trim(),\n variables: JSON.stringify(variables, null, 2),\n };\n if (headers) {\n payload.headers = JSON.stringify(headers);\n }\n return lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\n\nexport function buildDocumentSubgraphUrl(\n driveUrl: string,\n documentId: string,\n authToken?: string,\n) {\n const encodedQuery = buildDocumentSubgraphQuery(\n driveUrl,\n documentId,\n authToken,\n );\n return `${driveUrl}?explorerURLState=${encodedQuery}`;\n}\n","import { driveCollectionId, GqlRequestChannel } from \"@powerhousedao/reactor\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { useMemo } from \"react\";\nimport { buildDocumentSubgraphUrl } from \"../utils/index.js\";\nimport { useRenown, useSyncList, useUser } from \"./connect.js\";\nimport { useSelectedDrive } from \"./selected-drive.js\";\n\n/**\n * Hook that returns a function to generate a document's switchboard URL.\n * Only returns a function for documents in remote drives.\n * Returns null for local drives or when the document/drive cannot be determined.\n *\n * The returned function generates a fresh bearer token and builds the switchboard URL\n * with authentication when called.\n *\n * @param document - The document to create a switchboard URL generator for\n * @returns An async function that returns the switchboard URL, or null if not applicable\n */\nexport function useGetSwitchboardLink(\n document: PHDocument | undefined,\n): (() => Promise<string>) | null {\n const [drive] = useSelectedDrive();\n const remotes = useSyncList();\n\n const isRemoteDrive = useMemo(() => {\n return remotes.some(\n (remote) =>\n remote.collectionId === driveCollectionId(\"main\", drive.header.id),\n );\n }, [remotes, drive]);\n const remoteUrl = useMemo(() => {\n const remote = remotes.find(\n (remote) =>\n remote.collectionId === driveCollectionId(\"main\", drive.header.id),\n );\n\n if (remote?.channel instanceof GqlRequestChannel) {\n return (remote.channel as GqlRequestChannel).config.url;\n }\n\n return null;\n }, [remotes, drive]);\n const renown = useRenown();\n const user = useUser();\n\n return useMemo(() => {\n if (!isRemoteDrive || !document?.header.id || !remoteUrl) {\n return null;\n }\n\n return async () => {\n // Get bearer token if user is authenticated\n const token = user?.address\n ? await renown?.getBearerToken({\n expiresIn: 600,\n aud: remoteUrl,\n })\n : undefined;\n\n // Build and return the switchboard URL with the document subgraph query\n return buildDocumentSubgraphUrl(remoteUrl, document.header.id, token);\n };\n }, [isRemoteDrive, remoteUrl, document, user, renown]);\n}\n","import { addFileWithProgress } from \"../actions/document.js\";\nimport type {\n ConflictResolution,\n FileUploadProgressCallback,\n UseOnDropFile,\n} from \"../types/upload.js\";\nimport { useDocumentTypes } from \"./document-types.js\";\nimport { useSelectedDriveId } from \"./selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\n\nexport const useOnDropFile: UseOnDropFile = (\n documentTypesOverride?: string[],\n) => {\n const selectedDriveId = useSelectedDriveId();\n const selectedFolder = useSelectedFolder();\n const documentTypes = useDocumentTypes();\n\n const onDropFile = async (\n file: File,\n onProgress?: FileUploadProgressCallback,\n resolveConflict?: ConflictResolution,\n ) => {\n if (!selectedDriveId) {\n console.warn(\"No selected drive - upload skipped\");\n return;\n }\n\n const fileName = file.name.replace(/\\..+/gim, \"\");\n const targetNodeId = selectedFolder?.id;\n\n // Return the FileNode directly from addFileWithProgress\n return await addFileWithProgress(\n file,\n selectedDriveId,\n fileName,\n targetNodeId,\n onProgress,\n documentTypesOverride ?? documentTypes,\n resolveConflict,\n );\n };\n\n return onDropFile;\n};\n","import { useAllowList } from \"./connect.js\";\nimport { useUser } from \"./renown.js\";\nexport function useUserPermissions() {\n const user = useUser();\n const allowList = useAllowList();\n if (!allowList) {\n return {\n isAllowedToCreateDocuments: true,\n isAllowedToEditDocuments: true,\n };\n }\n\n return {\n isAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n isAllowedToEditDocuments: allowList.includes(user?.address ?? \"\"),\n };\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport { REACTOR_SCHEMA } from \"@powerhousedao/reactor\";\n\nasync function dropTablesInSchema(pg: PGlite, schema: string): Promise<void> {\n await pg.exec(`\nDO $$\nDECLARE\n _schemaname text := '${schema}';\n _tablename text;\nBEGIN\n FOR _tablename IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = _schemaname LOOP\n RAISE INFO 'Dropping table %.%', _schemaname, _tablename;\n EXECUTE format('DROP TABLE %I.%I CASCADE;', _schemaname, _tablename);\n END LOOP;\n IF NOT FOUND THEN\n RAISE WARNING 'Schema % does not exist', _schemaname;\n END IF;\nEND $$;\n`);\n}\n\nexport async function truncateAllTables(\n pg: PGlite,\n schema: string = REACTOR_SCHEMA,\n): Promise<void> {\n await dropTablesInSchema(pg, schema);\n}\n\nexport async function dropAllReactorStorage(pg: PGlite): Promise<void> {\n await dropTablesInSchema(pg, REACTOR_SCHEMA);\n\n // legacy\n await dropTablesInSchema(pg, \"public\");\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { type DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport { BrowserKeyStorage, RenownCryptoBuilder } from \"@renown/sdk\";\nimport { setDrives } from \"./hooks/drives.js\";\nimport { getDrives } from \"./utils/drives.js\";\n\nexport type ReactorDefaultDrivesConfig = {\n defaultDrivesUrl?: string[];\n};\n\nexport type RefreshReactorDataConfig = {\n debounceDelayMs?: number;\n immediateThresholdMs?: number;\n};\n\nconst DEFAULT_DEBOUNCE_DELAY_MS = 200;\nconst DEFAULT_IMMEDIATE_THRESHOLD_MS = 1000;\n\nasync function _refreshReactorData(reactor: IReactorClient) {\n const drives = await getDrives(reactor);\n\n setDrives(drives);\n}\n\nasync function _refreshReactorDataClient(reactor: IReactorClient | undefined) {\n if (!reactor) return;\n\n const result = await reactor.find({ type: \"powerhouse/document-drive\" });\n setDrives(result.results as DocumentDriveDocument[]);\n}\n\nfunction createDebouncedRefreshReactorData(\n debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS,\n immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS,\n) {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let lastRefreshTime = 0;\n\n return (reactor: IReactorClient, immediate = false) => {\n const now = Date.now();\n const timeSinceLastRefresh = now - lastRefreshTime;\n\n // Clear any pending timeout\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n // If caller requests immediate execution or enough time has passed, execute immediately\n if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n lastRefreshTime = now;\n return _refreshReactorData(reactor);\n }\n\n // Otherwise, debounce the call\n return new Promise<void>((resolve) => {\n timeout = setTimeout(() => {\n lastRefreshTime = Date.now();\n void _refreshReactorData(reactor).then(resolve);\n }, debounceDelayMs);\n });\n };\n}\n\nfunction createDebouncedRefreshReactorDataClient(\n debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS,\n immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS,\n) {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let lastRefreshTime = 0;\n\n return (reactor: IReactorClient | undefined, immediate = false) => {\n const now = Date.now();\n const timeSinceLastRefresh = now - lastRefreshTime;\n\n // Clear any pending timeout\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n // If caller requests immediate execution or enough time has passed, execute immediately\n if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n lastRefreshTime = now;\n return _refreshReactorDataClient(reactor);\n }\n\n // Otherwise, debounce the call\n return new Promise<void>((resolve) => {\n timeout = setTimeout(() => {\n lastRefreshTime = Date.now();\n void _refreshReactorDataClient(reactor).then(resolve);\n }, debounceDelayMs);\n });\n };\n}\n\nexport const refreshReactorData = createDebouncedRefreshReactorData();\nexport const refreshReactorDataClient =\n createDebouncedRefreshReactorDataClient();\n\n/**\n * @deprecated Use {@link initRenownCrypto} instead\n *\n * Initialize ConnectCrypto\n * @returns ConnectCrypto instance\n */\nexport async function initConnectCrypto() {\n return initRenownCrypto();\n}\n\n/**\n * Initialize RenownCrypto\n * @returns RenownCrypto instance\n */\nexport async function initRenownCrypto() {\n const keyStorage = await BrowserKeyStorage.create();\n return await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();\n}\n","import type { PackageInfo } from \"@powerhousedao/shared/registry\";\nexport async function getPackages(registryUrl: string) {\n const res = await fetch(`${registryUrl}/packages`);\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n const data = (await res.json()) as PackageInfo[];\n return data;\n}\n\nexport async function getPackagesByDocumentType(\n registryUrl: string,\n documentType: string,\n): Promise<string[]> {\n const encodedType = encodeURIComponent(documentType);\n const res = await fetch(\n `${registryUrl}/packages/by-document-type?type=${encodedType}`,\n );\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n return (await res.json()) as string[];\n}\n","import type { PackageInfo } from \"@powerhousedao/shared/registry\";\nimport { getPackages, getPackagesByDocumentType } from \"./fetchers.js\";\nimport type { PublishEvent } from \"./types.js\";\n\nfunction cdnUrlToApiUrl(cdnUrl: string): string {\n return cdnUrl.replace(/\\/-\\/cdn\\/?$/, \"\");\n}\nexport class RegistryClient {\n readonly apiUrl: string;\n\n constructor(cdnUrl: string) {\n this.apiUrl = cdnUrlToApiUrl(cdnUrl);\n }\n\n async getPackages(): Promise<PackageInfo[]> {\n const data = await getPackages(this.apiUrl);\n return data;\n }\n\n async getPackagesByDocumentType(documentType: string): Promise<string[]> {\n return await getPackagesByDocumentType(this.apiUrl, documentType);\n }\n\n async searchPackages(query: string): Promise<PackageInfo[]> {\n const packages = await this.getPackages();\n if (!query) return packages;\n const lowerQuery = query.toLowerCase();\n return packages.filter(\n (pkg) =>\n pkg.name.toLowerCase().includes(lowerQuery) ||\n pkg.manifest?.description?.toLowerCase().includes(lowerQuery),\n );\n }\n\n onPublish(callback: (event: PublishEvent) => void): () => void {\n const eventSource = new EventSource(`${this.apiUrl}/-/events`);\n\n eventSource.addEventListener(\"publish\", (e: MessageEvent<string>) => {\n const data = JSON.parse(e.data) as PublishEvent;\n callback(data);\n });\n\n return () => {\n eventSource.close();\n };\n }\n}\n","import type { PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { useEffect, useState } from \"react\";\n\nexport const PGLITE_UPDATE_EVENT = \"ph:pglite-update\";\n\nexport interface PGliteState {\n db: PGliteWithLive | null;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst defaultPGliteState: PGliteState = {\n db: null,\n isLoading: true,\n error: null,\n};\n\nexport const usePGliteDB = () => {\n const [state, setState] = useState<PGliteState>(\n () => window.powerhouse?.pglite ?? defaultPGliteState,\n );\n\n useEffect(() => {\n const handlePgliteUpdate = () =>\n setState(window.powerhouse?.pglite ?? defaultPGliteState);\n\n window.addEventListener(PGLITE_UPDATE_EVENT, handlePgliteUpdate);\n\n return () =>\n window.removeEventListener(PGLITE_UPDATE_EVENT, handlePgliteUpdate);\n }, []);\n\n return state;\n};\n\nexport const useSetPGliteDB = () => {\n const setPGliteState = (pglite: Partial<PGliteState>) => {\n const currentPowerhouse = window.powerhouse ?? {};\n const currentPGliteState = window.powerhouse?.pglite ?? defaultPGliteState;\n\n window.powerhouse = {\n ...currentPowerhouse,\n pglite: {\n ...currentPGliteState,\n ...pglite,\n },\n };\n window.dispatchEvent(new CustomEvent(PGLITE_UPDATE_EVENT));\n };\n\n return setPGliteState;\n};\n\nexport const usePGlite = () => {\n const pglite = usePGliteDB();\n const setPGlite = useSetPGliteDB();\n\n return [pglite, setPGlite];\n};\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport type { LiveNamespace, PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { createRelationalDb } from \"@powerhousedao/reactor\";\nimport type { IRelationalDb as IRelationalDbCore } from \"@powerhousedao/shared/processors\";\nimport { Kysely } from \"kysely\";\nimport { PGliteDialect } from \"kysely-pglite-dialect\";\nimport { useMemo } from \"react\";\nimport { usePGliteDB } from \"../../pglite/usePGlite.js\";\n\n// Type for Relational DB instance enhanced with live capabilities\nexport type RelationalDbWithLive<Schema> = IRelationalDbCore<Schema> & {\n live: LiveNamespace;\n};\n\ninterface IRelationalDbState<Schema> {\n db: RelationalDbWithLive<Schema> | null;\n isLoading: boolean;\n error: Error | null;\n}\n\n// Custom initializer that creates enhanced Kysely instance with live capabilities\nfunction createRelationalDbWithLive<Schema>(\n pgliteInstance: PGliteWithLive,\n): RelationalDbWithLive<Schema> {\n const baseDb = new Kysely<Schema>({\n dialect: new PGliteDialect(pgliteInstance as unknown as PGlite),\n });\n const relationalDb = createRelationalDb(baseDb);\n\n // Inject the live namespace with proper typing\n const relationalDBWithLive =\n relationalDb as unknown as RelationalDbWithLive<Schema>;\n relationalDBWithLive.live = pgliteInstance.live;\n\n return relationalDBWithLive;\n}\n\nexport const useRelationalDb = <Schema>(): IRelationalDbState<Schema> => {\n const pglite = usePGliteDB();\n\n const relationalDb = useMemo<IRelationalDbState<Schema>>(() => {\n if (!pglite.db || pglite.isLoading || pglite.error) {\n return {\n db: null,\n isLoading: pglite.isLoading,\n error: pglite.error,\n };\n }\n\n const db = createRelationalDbWithLive<Schema>(pglite.db);\n\n return {\n db,\n isLoading: false,\n error: null,\n };\n }, [pglite]);\n\n return relationalDb;\n};\n","import type { LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport type {\n IRelationalQueryBuilder,\n RelationalDbProcessorClass,\n} from \"@powerhousedao/shared/processors\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useRelationalDb } from \"./useRelationalDb.js\";\n\nexport type QueryCallbackReturnType = {\n sql: string;\n parameters?: readonly unknown[];\n};\n\nexport type useRelationalQueryOptions = {\n // Whether to hash the namespace to avoid namespace size limit. True by default\n hashNamespace?: boolean;\n};\n\nconst MAX_RETRIES = 5;\nconst RETRY_DELAY = 200;\n\nconst isRelationNotExistError = (error: unknown): boolean => {\n const errorMessage =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : String(error);\n\n return (\n errorMessage.toLowerCase().includes(\"relation\") &&\n errorMessage.toLowerCase().includes(\"does not exist\")\n );\n};\n\ntype LiveQueryType = {\n unsubscribe: () => void;\n};\n\nexport function useRelationalQuery<Schema, T = unknown, TParams = undefined>(\n ProcessorClass: RelationalDbProcessorClass<Schema>,\n driveId: string,\n queryCallback: (\n db: IRelationalQueryBuilder<Schema>,\n parameters?: TParams,\n ) => QueryCallbackReturnType,\n parameters?: TParams,\n options?: useRelationalQueryOptions,\n) {\n const [result, setResult] = useState<LiveQueryResults<T> | null>(null);\n const [queryLoading, setQueryLoading] = useState(true);\n const [error, setError] = useState<Error | undefined>(undefined);\n const retryCount = useRef(0);\n const retryTimeoutRef = useRef<NodeJS.Timeout>(null);\n\n const relationalDb = useRelationalDb<Schema>();\n\n const executeLiveQuery = async (\n sql: string,\n queryParameters: readonly unknown[] | undefined,\n retryAttempt = 0,\n ): Promise<LiveQueryType | null> => {\n if (!relationalDb.db) {\n return null;\n }\n\n try {\n const live = await relationalDb.db.live.query<T>(\n sql,\n queryParameters ? [...queryParameters] : [],\n (result) => {\n setResult(result);\n setQueryLoading(false);\n retryCount.current = 0; // Reset retry count on success\n },\n );\n\n return live as LiveQueryType;\n } catch (err: unknown) {\n if (isRelationNotExistError(err) && retryAttempt < MAX_RETRIES) {\n return new Promise((resolve) => {\n retryTimeoutRef.current = setTimeout(() => {\n resolve(executeLiveQuery(sql, queryParameters, retryAttempt + 1));\n }, RETRY_DELAY);\n });\n }\n\n setQueryLoading(false);\n setError(err instanceof Error ? err : new Error(String(err)));\n return null;\n }\n };\n\n useEffect(() => {\n setError(undefined);\n setQueryLoading(true);\n retryCount.current = 0;\n\n if (!relationalDb.db) {\n return;\n }\n\n // Use the processor helper to obtain a typed namespaced query builder\n const db = ProcessorClass.query(driveId, relationalDb.db);\n\n const compiledQuery = queryCallback(db, parameters);\n const { sql, parameters: queryParameters } = compiledQuery;\n\n const liveQueryPromise = executeLiveQuery(sql, queryParameters);\n\n return () => {\n if (retryTimeoutRef.current) {\n clearTimeout(retryTimeoutRef.current);\n }\n void liveQueryPromise.then((live) => {\n if (live?.unsubscribe) {\n live.unsubscribe();\n }\n });\n };\n }, [relationalDb.db, ProcessorClass, driveId, queryCallback, parameters]);\n\n return {\n isLoading: relationalDb.isLoading || queryLoading,\n error: error || relationalDb.error,\n result,\n } as const;\n}\n","import type { LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport type {\n QueryCallbackReturnType,\n useRelationalQueryOptions,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n IRelationalQueryBuilder,\n RelationalDbProcessorClass,\n} from \"@powerhousedao/shared/processors\";\nimport type { CompiledQuery } from \"kysely\";\nimport deepEqual from \"lodash.isequal\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport { useRelationalQuery } from \"../hooks/useRelationalQuery.js\";\n\n// Custom hook for parameter memoization\nfunction useStableParams<T>(params: T): T {\n const prevParamsRef = useRef<T>(null);\n\n return useMemo(() => {\n if (!deepEqual(prevParamsRef.current, params)) {\n prevParamsRef.current = params;\n }\n return prevParamsRef.current as T;\n }, [params]);\n}\n\nexport function createProcessorQuery<TSchema>(\n ProcessorClass: RelationalDbProcessorClass<TSchema>,\n) {\n // Overload for queries without parameters\n function useQuery<\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n };\n\n // Overload for queries with parameters\n function useQuery<\n TParams,\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n parameters: TParams,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n parameters: TParams,\n options?: useRelationalQueryOptions,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n };\n\n function useQuery<\n TParams,\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n parameters?: TParams,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n parameters?: TParams,\n options?: useRelationalQueryOptions,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n } {\n type InferredResult =\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any;\n\n // Automatically memoize parameters using deep comparison\n const stableParams = useStableParams(parameters);\n\n // Memoize the callback to prevent infinite loops, updating when parameters change\n const memoizedCallback = useCallback(queryCallback, [stableParams]);\n\n return useRelationalQuery<TSchema, InferredResult, TParams>(\n ProcessorClass,\n driveId,\n memoizedCallback,\n stableParams,\n options,\n ) as {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<InferredResult> | null;\n };\n }\n\n return useQuery;\n}\n","import type { Action } from \"@powerhousedao/shared/document-model\";\nimport type { TrackedAction } from \"./types.js\";\n\n/**\n * Tracks pending actions with their operation context (prevOpHash, prevOpIndex).\n * Actions are accumulated until flushed (on push).\n */\nexport class ActionTracker {\n private pending: TrackedAction[] = [];\n\n /** Track a new action with its operation context. */\n track(action: Action, prevOpHash: string, prevOpIndex: number): void {\n this.pending.push({ action, prevOpHash, prevOpIndex });\n }\n\n /** Flush all pending actions and return them. Clears the internal queue. */\n flush(): TrackedAction[] {\n const actions = this.pending;\n this.pending = [];\n return actions;\n }\n\n /** Number of pending actions. */\n get count(): number {\n return this.pending.length;\n }\n\n /** Prepend previously flushed actions back to the queue (for retry on failure). */\n restore(actions: TrackedAction[]): void {\n this.pending = [...actions, ...this.pending];\n }\n\n /** Clear all pending actions without returning them. */\n clear(): void {\n this.pending = [];\n }\n}\n","import type {\n GetDocumentResult,\n GetDocumentWithOperationsResult,\n GetOperationsResult,\n IRemoteClient,\n PropagationMode,\n ReactorGraphQLClient,\n RemoteDocumentData,\n RemoteOperation,\n RemoteOperationResultPage,\n} from \"./types.js\";\n\n/**\n * Thin facade over the GraphQL SDK for remote document operations.\n */\nconst DEFAULT_PAGE_SIZE = 100;\n\nexport class RemoteClient implements IRemoteClient {\n private readonly pageSize: number;\n\n constructor(\n private readonly client: ReactorGraphQLClient,\n pageSize?: number,\n ) {\n this.pageSize = pageSize ?? DEFAULT_PAGE_SIZE;\n }\n\n /** Fetch a document by identifier. Returns null if not found. */\n async getDocument(\n identifier: string,\n branch?: string,\n ): Promise<GetDocumentResult | null> {\n const result = await this.client.GetDocument({\n identifier,\n view: branch ? { branch } : undefined,\n });\n return result.document ?? null;\n }\n\n /**\n * Fetch a document and its operations.\n *\n * When scopes are provided and BatchGetDocumentWithOperations is available,\n * fetches the document and per-scope operations in a single HTTP request.\n * Otherwise falls back to GetDocumentWithOperations for the first page,\n * then paginates remaining operations per scope.\n */\n async getDocumentWithOperations(\n identifier: string,\n branch?: string,\n sinceRevision?: Record<string, number>,\n scopes?: string[],\n ): Promise<GetDocumentWithOperationsResult | null> {\n // Fast path: batch document + per-scope operations in one request\n if (\n this.client.BatchGetDocumentWithOperations &&\n scopes &&\n scopes.length > 0\n ) {\n return this.batchGetDocumentWithOperations(\n identifier,\n branch,\n sinceRevision,\n scopes,\n );\n }\n\n // Standard path: GetDocumentWithOperations + paginate if needed\n const result = await this.client.GetDocumentWithOperations({\n identifier,\n view: branch ? { branch } : undefined,\n operationsPaging: {\n limit: this.pageSize,\n cursor: null,\n },\n });\n\n if (!result.document) return null;\n\n const doc = result.document.document;\n const opsPage = doc.operations;\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n\n if (opsPage) {\n for (const op of opsPage.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n }\n\n // Check if we have all expected operations by comparing against revisionsList\n const expectedTotal = doc.revisionsList.reduce(\n (sum, r) => sum + r.revision,\n 0,\n );\n const fetchedTotal = opsPage?.items.length ?? 0;\n\n if (fetchedTotal >= expectedTotal) {\n return {\n document: doc,\n childIds: result.document.childIds,\n operations: { operationsByScope },\n };\n }\n\n // Missing operations — fetch all per scope\n const allScopes = doc.revisionsList.map((r) => r.scope);\n const allOps = await this.getAllOperations(\n doc.id,\n branch,\n sinceRevision,\n allScopes,\n );\n\n return {\n document: doc,\n childIds: result.document.childIds,\n operations: allOps,\n };\n }\n\n /**\n * Fetch document + per-scope operations in a single HTTP request\n * via BatchGetDocumentWithOperations, then paginate any remaining pages.\n */\n private async batchGetDocumentWithOperations(\n identifier: string,\n branch: string | undefined,\n sinceRevision: Record<string, number> | undefined,\n scopes: string[],\n ): Promise<GetDocumentWithOperationsResult | null> {\n const view = branch ? { branch } : undefined;\n const filters = scopes.map((scope) => ({\n documentId: identifier,\n branch: branch ?? null,\n sinceRevision: sinceRevision?.[scope] ?? 0,\n scopes: [scope],\n }));\n const pagings = scopes.map(() => ({\n limit: this.pageSize,\n cursor: null as string | null,\n }));\n\n const result = await this.client.BatchGetDocumentWithOperations!(\n identifier,\n view,\n filters,\n pagings,\n );\n\n if (!result.document) return null;\n\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n let pending: {\n scope: string;\n filter: (typeof filters)[0];\n cursor: string;\n }[] = [];\n\n for (let i = 0; i < scopes.length; i++) {\n const page = result.operations[i];\n for (const op of page.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n if (page.hasNextPage && page.cursor) {\n pending.push({\n scope: scopes[i],\n filter: filters[i],\n cursor: page.cursor,\n });\n }\n }\n\n // Continue pagination for scopes with more pages\n while (pending.length > 0) {\n const pages = await this.fetchOperationPages(\n pending.map((p) => p.filter),\n pending.map((p) => ({ limit: this.pageSize, cursor: p.cursor })),\n );\n\n const nextPending: typeof pending = [];\n for (let i = 0; i < pending.length; i++) {\n const page = pages[i];\n for (const op of page.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n if (page.hasNextPage && page.cursor) {\n nextPending.push({ ...pending[i], cursor: page.cursor });\n }\n }\n pending = nextPending;\n }\n\n return {\n document: result.document.document,\n childIds: result.document.childIds,\n operations: { operationsByScope },\n };\n }\n\n /**\n * Fetch all operations for a document, paginating through all pages.\n * Each scope is queried individually because the API only returns\n * pagination cursors for single-scope queries.\n */\n async getAllOperations(\n documentId: string,\n branch?: string,\n sinceRevision?: Record<string, number>,\n scopes?: string[],\n ): Promise<GetOperationsResult> {\n // When scopes are specified, query each scope in parallel.\n // Uses a single composed request per pagination round when available.\n if (scopes && scopes.length > 0) {\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n\n // Tracks scopes still being paginated, each with its own filter and cursor\n let pending = scopes.map((scope) => ({\n scope,\n filter: {\n documentId,\n branch: branch ?? null,\n sinceRevision: sinceRevision?.[scope] ?? 0,\n scopes: [scope],\n },\n cursor: null as string | null,\n }));\n\n while (pending.length > 0) {\n const pages = await this.fetchOperationPages(\n pending.map((p) => p.filter),\n pending.map((p) => ({ limit: this.pageSize, cursor: p.cursor })),\n );\n\n const nextPending: typeof pending = [];\n\n for (let i = 0; i < pending.length; i++) {\n const page = pages[i];\n for (const op of page.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n if (page.hasNextPage && page.cursor) {\n nextPending.push({ ...pending[i], cursor: page.cursor });\n }\n }\n\n pending = nextPending;\n }\n\n return { operationsByScope };\n }\n\n // No scopes specified — single query for all scopes (no per-scope sinceRevision)\n return this.fetchOperationsForScope(documentId, branch);\n }\n\n /**\n * Fetch one page of operations per filter.\n * Uses the composed query (single HTTP request) when available,\n * otherwise falls back to parallel individual requests.\n */\n private async fetchOperationPages(\n filters: Parameters<\n ReactorGraphQLClient[\"GetDocumentOperations\"]\n >[0][\"filter\"][],\n pagings: Parameters<\n ReactorGraphQLClient[\"GetDocumentOperations\"]\n >[0][\"paging\"][],\n ): Promise<RemoteOperationResultPage[]> {\n if (this.client.BatchGetDocumentOperations) {\n return this.client.BatchGetDocumentOperations(filters, pagings);\n }\n\n return Promise.all(\n filters.map((filter, i) =>\n this.client\n .GetDocumentOperations({ filter, paging: pagings[i] })\n .then((r) => r.documentOperations),\n ),\n );\n }\n\n /** Fetch all pages of operations for a single scope (or all scopes if none specified). */\n private async fetchOperationsForScope(\n documentId: string,\n branch?: string,\n sinceRevision?: number,\n scope?: string,\n ): Promise<GetOperationsResult> {\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n let cursor: string | null | undefined;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const result = await this.client.GetDocumentOperations({\n filter: {\n documentId,\n branch: branch ?? null,\n sinceRevision: sinceRevision ?? 0,\n scopes: scope ? [scope] : null,\n },\n paging: {\n limit: this.pageSize,\n cursor: cursor ?? null,\n },\n });\n\n const page = result.documentOperations;\n\n for (const op of page.items) {\n const s = op.action.scope;\n (operationsByScope[s] ??= []).push(op);\n }\n\n hasNextPage = page.hasNextPage;\n cursor = page.cursor;\n }\n\n return { operationsByScope };\n }\n\n /** Push actions to an existing document via MutateDocument. */\n async pushActions(\n documentIdentifier: string,\n actions: ReadonlyArray<NonNullable<unknown>>,\n branch?: string,\n ): Promise<RemoteDocumentData> {\n const result = await this.client.MutateDocument({\n documentIdentifier,\n actions,\n view: branch ? { branch } : undefined,\n });\n return result.mutateDocument;\n }\n\n /** Create a new document on the remote. */\n async createDocument(\n document: NonNullable<unknown>,\n parentIdentifier?: string,\n ): Promise<RemoteDocumentData> {\n const result = await this.client.CreateDocument({\n document,\n parentIdentifier: parentIdentifier ?? null,\n });\n return result.createDocument;\n }\n\n /** Create an empty document of a given type on the remote. */\n async createEmptyDocument(\n documentType: string,\n parentIdentifier?: string,\n ): Promise<RemoteDocumentData> {\n const result = await this.client.CreateEmptyDocument({\n documentType,\n parentIdentifier: parentIdentifier ?? null,\n });\n return result.createEmptyDocument;\n }\n\n /** Delete a document on the remote. Returns true if successful. */\n async deleteDocument(\n identifier: string,\n propagate?: PropagationMode,\n ): Promise<boolean> {\n const result = await this.client.DeleteDocument({\n identifier,\n propagate,\n });\n return result.deleteDocument;\n }\n}\n","import type {\n DocumentOperations,\n Operation,\n PHBaseState,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n ConflictInfo,\n RemoteDocumentData,\n RemoteOperation,\n} from \"./types.js\";\n\n/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. \"SET_MODEL_NAME\" → \"setModelName\"). */\nexport function screamingSnakeToCamel(s: string): string {\n return s\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** Error thrown when a push conflict is detected with the \"reject\" strategy. */\nexport class ConflictError extends Error {\n constructor(public readonly conflict: ConflictInfo) {\n super(\"Push conflict: remote has new operations since last pull\");\n this.name = \"ConflictError\";\n }\n}\n\n/** Convert a remote operation to the local Operation type. */\nexport function remoteOperationToLocal(remote: RemoteOperation): Operation {\n return {\n id: remote.id ?? \"\",\n index: remote.index,\n skip: remote.skip,\n timestampUtcMs: remote.timestampUtcMs,\n hash: remote.hash,\n error: remote.error ?? undefined,\n action: {\n id: remote.action.id,\n type: remote.action.type,\n timestampUtcMs: remote.action.timestampUtcMs,\n input: remote.action.input,\n scope: remote.action.scope,\n attachments: remote.action.attachments?.map((a) => ({\n data: a.data,\n mimeType: a.mimeType,\n hash: a.hash,\n extension: a.extension ?? undefined,\n fileName: a.fileName ?? undefined,\n })),\n context: remote.action.context?.signer\n ? {\n signer: {\n user: remote.action.context.signer.user ?? {\n address: \"\",\n networkId: \"\",\n chainId: 0,\n },\n app: remote.action.context.signer.app ?? {\n name: \"\",\n key: \"\",\n },\n signatures: remote.action.context.signer.signatures.map((s) =>\n deserializeSignature(s),\n ),\n },\n }\n : undefined,\n },\n };\n}\n\n/**\n * Deserialize a signature string back to a 5-element tuple.\n * The server serializes tuples via `tuple.join(\", \")`.\n */\nexport function deserializeSignature(\n s: string,\n): [string, string, string, string, string] {\n const parts = s.split(\", \");\n return [\n parts[0] ?? \"\",\n parts[1] ?? \"\",\n parts[2] ?? \"\",\n parts[3] ?? \"\",\n parts[4] ?? \"\",\n ];\n}\n\n/** Convert remote operations to local DocumentOperations format. */\nexport function convertRemoteOperations(\n operationsByScope: Record<string, RemoteOperation[]>,\n): DocumentOperations {\n const operations: DocumentOperations = {};\n for (const [scope, remoteOps] of Object.entries(operationsByScope)) {\n operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));\n }\n return operations;\n}\n\n/** Reconstruct a PHDocument from remote document data and operations. */\nexport function buildPulledDocument(\n remoteDoc: RemoteDocumentData,\n operations: DocumentOperations,\n initialDoc: PHDocument<PHBaseState>,\n branch: string,\n): PHDocument<PHBaseState> {\n return {\n header: {\n ...initialDoc.header,\n id: remoteDoc.id,\n name: remoteDoc.name,\n slug: remoteDoc.slug ?? \"\",\n documentType: remoteDoc.documentType,\n createdAtUtcIso:\n typeof remoteDoc.createdAtUtcIso === \"string\"\n ? remoteDoc.createdAtUtcIso\n : remoteDoc.createdAtUtcIso.toISOString(),\n lastModifiedAtUtcIso:\n typeof remoteDoc.lastModifiedAtUtcIso === \"string\"\n ? remoteDoc.lastModifiedAtUtcIso\n : remoteDoc.lastModifiedAtUtcIso.toISOString(),\n revision: Object.fromEntries(\n remoteDoc.revisionsList.map((r) => [r.scope, r.revision]),\n ),\n branch,\n },\n state: remoteDoc.state as PHBaseState,\n initialState: initialDoc.initialState,\n operations,\n clipboard: [],\n };\n}\n\n/** Extract revision map from a remote document's revisionsList. */\nexport function extractRevisionMap(\n revisionsList: RemoteDocumentData[\"revisionsList\"],\n): Record<string, number> {\n return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n\n/**\n * Check if any scope in currentRevision is ahead of knownRevision.\n * When `scopes` is provided, only those scopes are checked.\n */\nexport function hasRevisionConflict(\n currentRevision: Record<string, number>,\n knownRevision: Record<string, number>,\n scopes?: ReadonlySet<string>,\n): boolean {\n for (const scope in currentRevision) {\n if (scopes && !scopes.has(scope)) continue;\n if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) {\n return true;\n }\n }\n return false;\n}\n","import type {\n Action,\n DocumentOperations,\n Operation,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport type { PHDocumentController } from \"document-model\";\nimport { ActionTracker } from \"./action-tracker.js\";\nimport { RemoteClient } from \"./remote-client.js\";\nimport type {\n ConflictStrategy,\n DocumentChangeListener,\n IRemoteClient,\n IRemoteController,\n PropagationMode,\n PushResult,\n RemoteControllerOptions,\n RemoteDocumentChangeEvent,\n RemoteDocumentData,\n RemoteOperation,\n SyncStatus,\n TrackedAction,\n} from \"./types.js\";\nimport {\n ConflictError,\n buildPulledDocument,\n convertRemoteOperations,\n extractRevisionMap,\n hasRevisionConflict,\n screamingSnakeToCamel,\n} from \"./utils.js\";\n\n/** Extract TState from a PHDocumentController subclass. */\ntype InferState<C> = C extends PHDocumentController<infer S> ? S : never;\n\n/**\n * Extract action methods from a controller type.\n * These are the dynamically-added methods (not on the base PHDocumentController prototype).\n */\ntype ActionMethodsOf<C, TRemote> = {\n [K in Exclude<keyof C, keyof PHDocumentController<any>>]: C[K] extends (\n input: infer I,\n ) => unknown\n ? (input: I) => TRemote & ActionMethodsOf<C, TRemote>\n : C[K];\n};\n\n/** The full return type: RemoteDocumentController + action methods. */\nexport type RemoteDocumentControllerWith<C extends PHDocumentController<any>> =\n RemoteDocumentController<C> & ActionMethodsOf<C, RemoteDocumentController<C>>;\n\n/**\n * A controller that wraps a PHDocumentController with remote push/pull capabilities.\n * Composes a local controller and adds GraphQL-based sync with a reactor server.\n */\nexport class RemoteDocumentController<\n TController extends PHDocumentController<any>,\n> implements IRemoteController<InferState<TController>> {\n private inner: TController;\n private readonly remoteClient: IRemoteClient;\n private readonly tracker = new ActionTracker();\n private readonly options: RemoteControllerOptions;\n private documentId: string;\n private remoteRevision: Record<string, number> = {};\n private hasPulled = false;\n private pushScheduled = false;\n private pushQueue: Promise<void> = Promise.resolve();\n private listeners: DocumentChangeListener[] = [];\n\n private constructor(inner: TController, options: RemoteControllerOptions) {\n this.inner = inner;\n this.options = options;\n this.documentId = options.documentId ?? \"\";\n this.remoteClient = new RemoteClient(\n options.client,\n options.operationsPageSize,\n );\n\n this.setupActionInterceptors();\n }\n\n // --- State access (delegated to inner controller) ---\n\n get header(): PHDocumentHeader {\n return this.inner.header;\n }\n\n get state(): InferState<TController> {\n return this.inner.state as InferState<TController>;\n }\n\n get operations(): DocumentOperations {\n return this.inner.operations;\n }\n\n get document(): PHDocument<InferState<TController>> {\n return this.inner.document as PHDocument<InferState<TController>>;\n }\n\n get status(): SyncStatus {\n return {\n pendingActionCount: this.tracker.count,\n connected: this.documentId !== \"\",\n documentId: this.documentId,\n remoteRevision: { ...this.remoteRevision },\n };\n }\n\n /** Register a listener for document changes. Returns an unsubscribe function. */\n onChange(listener: DocumentChangeListener): () => void {\n this.listeners.push(listener);\n return () => {\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n\n private notifyListeners(source: RemoteDocumentChangeEvent[\"source\"]): void {\n if (this.listeners.length === 0) return;\n const event: RemoteDocumentChangeEvent = {\n source,\n document: this.document,\n };\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n\n // --- Remote operations ---\n\n /** Push all pending actions to remote, then pull latest state. */\n async push(): Promise<PushResult> {\n let tracked = this.tracker.flush();\n\n if (tracked.length === 0 && this.documentId !== \"\") {\n // Nothing to push, just pull (reuses the fetched document)\n const remoteDocument = await this.pull();\n return {\n remoteDocument,\n actionCount: 0,\n operations: [],\n };\n }\n\n try {\n await this.ensureRemoteDocument();\n\n // Conflict detection: check if remote has changed since last pull\n if (this.options.onConflict && tracked.length > 0) {\n tracked = await this.handleConflicts(tracked, this.options.onConflict);\n }\n } catch (error) {\n // Pre-push failure: restore actions so they can be retried\n this.tracker.restore(tracked);\n throw error;\n }\n\n let pushedActions: Action[] = [];\n\n try {\n if (tracked.length > 0) {\n const actions = await this.prepareActionsForPush(tracked);\n pushedActions = actions;\n\n await this.remoteClient.pushActions(\n this.documentId,\n actions,\n this.options.branch,\n );\n }\n } catch (error) {\n // Push failed: restore actions so they can be retried\n this.tracker.restore(tracked);\n throw error;\n }\n\n // Pull remote state to reconcile (remote is source of truth).\n // If this fails, actions were already pushed — do NOT restore them.\n const remoteDocument = await this.pull();\n\n return {\n remoteDocument,\n actionCount: tracked.length,\n operations: pushedActions,\n };\n }\n\n /** Delete the document on the remote. */\n async delete(propagate?: PropagationMode): Promise<boolean> {\n if (this.documentId === \"\") {\n throw new Error(\"Cannot delete: no document ID set\");\n }\n const result = await this.remoteClient.deleteDocument(\n this.documentId,\n propagate,\n );\n return result;\n }\n\n /** Pull latest state from remote, replacing local document. Returns the remote document data. */\n async pull(): Promise<RemoteDocumentData> {\n if (this.documentId === \"\") {\n throw new Error(\"Cannot pull: no document ID set\");\n }\n\n const { remoteDoc, operations } = await this.fetchDocumentAndOperations();\n\n // Get module from inner controller\n const initialDoc = this.inner.module.utils.createDocument();\n const pulledDocument = buildPulledDocument(\n remoteDoc,\n operations,\n initialDoc,\n this.options.branch ?? \"main\",\n );\n\n // Recreate inner controller with pulled document\n const ControllerClass = this.inner.constructor as new (\n doc?: PHDocument<PHBaseState>,\n ) => TController;\n this.inner = new ControllerClass(pulledDocument);\n\n // Re-setup interceptors on the new inner instance\n this.setupActionInterceptors();\n\n // Clear tracker (remote is source of truth)\n this.tracker.clear();\n\n // Update remote revision\n this.remoteRevision = extractRevisionMap(remoteDoc.revisionsList);\n\n this.notifyListeners(\"pull\");\n\n return remoteDoc;\n }\n\n // --- Static factories ---\n\n /**\n * Pull an existing document from remote and create a controller for it.\n */\n static async pull<C extends PHDocumentController<any>>(\n ControllerClass: new (doc?: PHDocument<any>) => C,\n options: RemoteControllerOptions,\n ): Promise<RemoteDocumentControllerWith<C>> {\n // Create a temporary instance to access the module\n const temp = new ControllerClass();\n const remote = new RemoteDocumentController(temp, options);\n\n if (options.documentId) {\n await remote.pull();\n }\n\n return remote as RemoteDocumentControllerWith<C>;\n }\n\n /**\n * Wrap an existing controller instance with remote capabilities.\n * Pending local actions on the inner controller are NOT tracked\n * (only new actions through the remote controller are tracked).\n */\n static from<C extends PHDocumentController<any>>(\n controller: C,\n options: RemoteControllerOptions,\n ): RemoteDocumentControllerWith<C> {\n return new RemoteDocumentController(\n controller,\n options,\n ) as RemoteDocumentControllerWith<C>;\n }\n\n // --- Private methods ---\n\n /** Create the document on the remote if it doesn't exist yet. */\n private async ensureRemoteDocument(): Promise<void> {\n if (this.documentId !== \"\") return;\n const remoteDoc = await this.remoteClient.createEmptyDocument(\n this.inner.header.documentType,\n this.options.parentIdentifier,\n );\n this.documentId = remoteDoc.id;\n }\n\n /** Set up interceptors for all action methods on the inner controller. */\n private setupActionInterceptors(): void {\n // Get the module's action keys from the inner controller\n const module = (this.inner as Record<string, unknown>)[\"module\"] as {\n actions: Record<string, unknown>;\n };\n\n for (const actionType in module.actions) {\n // Skip if it's a property on our own class\n if (actionType in RemoteDocumentController.prototype) {\n continue;\n }\n\n Object.defineProperty(this, actionType, {\n value: (input: unknown) => {\n // Snapshot operation counts per scope BEFORE applying\n const opCountsBefore: Record<string, number> = {};\n for (const scope in this.inner.operations) {\n opCountsBefore[scope] = this.inner.operations[scope].length;\n }\n\n // Apply locally via inner controller\n (\n this.inner as unknown as Record<string, (input: unknown) => unknown>\n )[actionType](input);\n\n // Find which scope got the new operation\n const newOp = this.findNewOperation(opCountsBefore);\n\n // Get prevOp in the SAME scope as the new operation\n const prevOp = newOp\n ? this.getLastOperationInScope(newOp.action.scope, newOp)\n : undefined;\n const prevOpHash = prevOp?.hash ?? \"\";\n const prevOpIndex = prevOp?.index ?? -1;\n\n if (!newOp) {\n // Action produced no operation (NOOP) — nothing to track\n return this;\n }\n\n // Track the action for push\n this.tracker.track(newOp.action, prevOpHash, prevOpIndex);\n this.notifyListeners(\"action\");\n\n if (this.options.mode === \"streaming\") {\n this.schedulePush();\n }\n\n return this;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n /**\n * Find the new operation added after applying an action,\n * by comparing current operation counts against a previous snapshot.\n */\n private findNewOperation(\n opCountsBefore: Record<string, number>,\n ): Operation | undefined {\n const ops = this.inner.operations;\n for (const scope in ops) {\n const scopeOps = ops[scope];\n const prevCount = opCountsBefore[scope] ?? 0;\n if (scopeOps.length > prevCount) {\n return scopeOps[scopeOps.length - 1];\n }\n }\n return undefined;\n }\n\n /**\n * Get the last operation in a specific scope, optionally excluding\n * a given operation (e.g. the one just added).\n */\n private getLastOperationInScope(\n scope: string,\n excludeOp?: Operation,\n ): Operation | undefined {\n const scopeOps = this.inner.operations[scope];\n if (scopeOps.length === 0) return undefined;\n for (let i = scopeOps.length - 1; i >= 0; i--) {\n if (scopeOps[i] !== excludeOp) return scopeOps[i];\n }\n return undefined;\n }\n\n /**\n * Detect and handle conflicts between local pending actions and remote state.\n * Returns the (possibly rebased) tracked actions to push.\n */\n private async handleConflicts(\n localTracked: TrackedAction[],\n strategy: ConflictStrategy,\n ): Promise<TrackedAction[]> {\n // Fetch current remote document to get latest revisions\n const remoteResult = await this.remoteClient.getDocument(\n this.documentId,\n this.options.branch,\n );\n if (!remoteResult) {\n throw new Error(`Document \"${this.documentId}\" not found on remote`);\n }\n\n const currentRevision = extractRevisionMap(\n remoteResult.document.revisionsList,\n );\n\n // Only check scopes that local actions touch\n const localScopes = new Set(localTracked.map((t) => t.action.scope));\n\n if (\n !hasRevisionConflict(currentRevision, this.remoteRevision, localScopes)\n ) {\n return localTracked;\n }\n\n // Fetch new remote operations for conflicting scopes in parallel,\n // using the correct sinceRevision for each scope.\n const conflictingScopes = [...localScopes].filter(\n (scope) =>\n (currentRevision[scope] ?? 0) > (this.remoteRevision[scope] ?? 0),\n );\n const { operationsByScope } = await this.remoteClient.getAllOperations(\n this.documentId,\n this.options.branch,\n this.remoteRevision,\n conflictingScopes,\n );\n const remoteOperations: Record<string, RemoteOperation[]> = {};\n for (const [scope, ops] of Object.entries(operationsByScope)) {\n remoteOperations[scope] = ops;\n }\n\n const conflictInfo = {\n remoteOperations,\n localActions: localTracked,\n knownRevision: { ...this.remoteRevision },\n currentRevision: { ...currentRevision },\n };\n\n if (strategy === \"reject\") {\n throw new ConflictError(conflictInfo);\n }\n\n if (strategy === \"rebase\") {\n return this.pullAndReplay(localTracked.map((t) => t.action));\n }\n\n // Custom merge handler (only possibility left after narrowing)\n const mergedActions = await strategy(conflictInfo);\n return this.pullAndReplay(mergedActions);\n }\n\n /**\n * Pull latest remote state and replay actions through interceptors.\n * Returns newly tracked actions with correct prevOpHash values.\n */\n private async pullAndReplay(actions: Action[]): Promise<TrackedAction[]> {\n await this.pull();\n\n for (const action of actions) {\n // Action types are SCREAMING_SNAKE_CASE but interceptors use camelCase\n const methodName = screamingSnakeToCamel(action.type);\n const method = (\n this as unknown as Record<string, (input: unknown) => unknown>\n )[methodName];\n if (typeof method === \"function\") {\n method.call(this, action.input);\n }\n }\n\n return this.tracker.flush();\n }\n\n /** Prepare actions for push, optionally signing them. */\n private async prepareActionsForPush(\n tracked: { action: Action; prevOpHash: string; prevOpIndex: number }[],\n ) {\n const actions: Action[] = [];\n\n for (const { action, prevOpHash, prevOpIndex } of tracked) {\n let prepared: Action = {\n ...action,\n context: {\n ...action.context,\n prevOpHash,\n prevOpIndex,\n },\n };\n\n if (this.options.signer) {\n prepared = await this.signAction(prepared);\n }\n\n actions.push(prepared);\n }\n\n return actions;\n }\n\n /** Sign an action using the configured signer, preserving existing signatures. */\n private async signAction(action: Action): Promise<Action> {\n const signer = this.options.signer!;\n const signature = await signer.signAction(action);\n const existingSignatures = action.context?.signer?.signatures ?? [];\n return {\n ...action,\n context: {\n ...action.context,\n signer: {\n user: signer.user!,\n app: signer.app!,\n signatures: [...existingSignatures, signature],\n },\n },\n };\n }\n\n /**\n * Fetch document and operations from the remote.\n *\n * On the first pull, uses the combined document+operations query.\n * On subsequent pulls, fetches only new operations per scope using\n * sinceRevision, then merges with existing local operations.\n * Falls back to a full fetch if the merge produces a count mismatch.\n */\n private async fetchDocumentAndOperations(): Promise<{\n remoteDoc: RemoteDocumentData;\n operations: DocumentOperations;\n }> {\n // Incremental fetch: use sinceRevision per scope\n if (this.hasPulled) {\n return this.incrementalFetch();\n }\n\n // Initial fetch: combined document + operations query\n const result = await this.remoteClient.getDocumentWithOperations(\n this.documentId,\n this.options.branch,\n );\n\n if (!result) {\n throw new Error(`Document \"${this.documentId}\" not found on remote`);\n }\n\n this.hasPulled = true;\n return {\n remoteDoc: result.document,\n operations: convertRemoteOperations(result.operations.operationsByScope),\n };\n }\n\n /**\n * Incremental fetch: fetches the document and only new operations per scope\n * using sinceRevision in a single request when possible.\n * Falls back to a full fetch on count mismatch.\n */\n private async incrementalFetch(): Promise<{\n remoteDoc: RemoteDocumentData;\n operations: DocumentOperations;\n }> {\n const scopes = Object.keys(this.remoteRevision);\n\n const result = await this.remoteClient.getDocumentWithOperations(\n this.documentId,\n this.options.branch,\n this.remoteRevision,\n scopes.length > 0 ? scopes : undefined,\n );\n\n if (!result) {\n throw new Error(`Document \"${this.documentId}\" not found on remote`);\n }\n\n const remoteDoc = result.document;\n const expectedRevision = extractRevisionMap(remoteDoc.revisionsList);\n\n const newOps = convertRemoteOperations(result.operations.operationsByScope);\n const merged = this.mergeOperations(this.inner.operations, newOps);\n\n // Validate: merged operation counts must match remote revisions\n if (this.hasExpectedOperationCounts(merged, expectedRevision)) {\n return { remoteDoc, operations: merged };\n }\n\n // Mismatch — do a full fetch\n return this.fullFetch(remoteDoc);\n }\n\n /**\n * Full fetch fallback: fetches all operations from the beginning.\n * Used when an incremental fetch produces a count mismatch.\n */\n private async fullFetch(remoteDoc: RemoteDocumentData): Promise<{\n remoteDoc: RemoteDocumentData;\n operations: DocumentOperations;\n }> {\n const { operationsByScope } = await this.remoteClient.getAllOperations(\n this.documentId,\n this.options.branch,\n );\n\n return {\n remoteDoc,\n operations: convertRemoteOperations(operationsByScope),\n };\n }\n\n /**\n * Validate that the merged operations match the expected revision per scope.\n * Each scope's operation count should equal its revision number.\n */\n private hasExpectedOperationCounts(\n operations: DocumentOperations,\n expectedRevision: Record<string, number>,\n ): boolean {\n for (const [scope, revision] of Object.entries(expectedRevision)) {\n const opCount = scope in operations ? operations[scope].length : 0;\n if (opCount !== revision) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Merge existing local operations with newly fetched operations.\n * Appends new operations to existing ones per scope.\n */\n private mergeOperations(\n existingOps: DocumentOperations,\n newOps: DocumentOperations,\n ): DocumentOperations {\n const merged: DocumentOperations = {};\n\n // Copy existing operations\n for (const [scope, ops] of Object.entries(existingOps)) {\n if (ops.length > 0) {\n merged[scope] = [...ops];\n }\n }\n\n // Append new operations per scope\n for (const [scope, ops] of Object.entries(newOps)) {\n if (ops.length > 0) {\n (merged[scope] ??= []).push(...ops);\n }\n }\n\n return merged;\n }\n\n /** Schedule a push via microtask (for streaming mode coalescing). */\n private schedulePush(): void {\n if (this.pushScheduled) return;\n this.pushScheduled = true;\n queueMicrotask(() => {\n this.pushScheduled = false;\n // Chain onto the push queue to prevent concurrent pushes\n this.pushQueue = this.pushQueue.then(async () => {\n try {\n await this.push();\n } catch (error: unknown) {\n // Actions remain in tracker for retry\n this.options.onPushError?.(error);\n }\n });\n });\n }\n}\n","import type { CSSProperties } from \"react\";\n\ninterface IconProps {\n size?: number;\n width?: number;\n height?: number;\n color?: string;\n style?: CSSProperties;\n className?: string;\n}\n\ninterface RenownLogoProps extends IconProps {\n hovered?: boolean;\n}\n\nexport function RenownLogo({\n width = 71,\n height = 19,\n hovered = false,\n color = \"currentColor\",\n className,\n}: RenownLogoProps) {\n return (\n <svg\n width={width}\n height={height}\n viewBox=\"0 0 71 19\"\n fill={color}\n xmlns=\"http://www.w3.org/2000/svg\"\n className={className}\n >\n <path d=\"M53.6211 18.4887V9.0342H56.435V10.8096H56.4923C56.7377 10.181 57.1085 9.70244 57.6047 9.37398C58.101 9.03986 58.6981 8.8728 59.3962 8.8728C60.4105 8.8728 61.2039 9.1871 61.7765 9.8157C62.3546 10.4443 62.6436 11.3164 62.6436 12.432V18.4887H59.7397V13.0776C59.7397 12.5283 59.6007 12.1007 59.3225 11.7949C59.0499 11.4835 58.6654 11.3277 58.1692 11.3277C57.6784 11.3277 57.2803 11.4976 56.9749 11.8374C56.6695 12.1772 56.5168 12.6161 56.5168 13.1541V18.4887H53.6211Z\" />\n <path d=\"M53.097 9.03394L50.7412 18.4884H47.6164L46.1522 12.075H46.0949L44.6389 18.4884H41.5632L39.1992 9.03394H42.1195L43.3056 15.7532H43.3628L44.7861 9.03394H47.551L48.9906 15.7532H49.0479L50.234 9.03394H53.097Z\" />\n <path d=\"M37.8661 17.3926C37.0427 18.2591 35.9084 18.6923 34.4632 18.6923C33.0181 18.6923 31.8838 18.2591 31.0604 17.3926C30.2369 16.5205 29.8252 15.3086 29.8252 13.7569C29.8252 12.2336 30.2424 11.033 31.0767 10.1552C31.9111 9.2718 33.0399 8.83008 34.4632 8.83008C35.892 8.83008 37.0208 9.26896 37.8497 10.1467C38.6841 11.0188 39.1013 12.2222 39.1013 13.7569C39.1013 15.3143 38.6896 16.5262 37.8661 17.3926ZM33.2117 15.7702C33.5116 16.2402 33.9288 16.4752 34.4632 16.4752C34.9977 16.4752 35.4148 16.2402 35.7148 15.7702C36.0147 15.2945 36.1647 14.6234 36.1647 13.7569C36.1647 12.9131 36.012 12.2506 35.7066 11.7692C35.4012 11.2878 34.9868 11.0472 34.4632 11.0472C33.9343 11.0472 33.5171 11.2878 33.2117 11.7692C32.9118 12.2449 32.7618 12.9075 32.7618 13.7569C32.7618 14.6234 32.9118 15.2945 33.2117 15.7702Z\" />\n <path d=\"M20.0088 18.4887V9.0342H22.8227V10.8096H22.88C23.1254 10.181 23.4962 9.70244 23.9924 9.37398C24.4887 9.03986 25.0858 8.8728 25.7838 8.8728C26.7982 8.8728 27.5916 9.1871 28.1642 9.8157C28.7423 10.4443 29.0313 11.3164 29.0313 12.432V18.4887H26.1274V13.0776C26.1274 12.5283 25.9883 12.1007 25.7102 11.7949C25.4376 11.4835 25.0531 11.3277 24.5569 11.3277C24.0661 11.3277 23.668 11.4976 23.3626 11.8374C23.0572 12.1772 22.9045 12.6161 22.9045 13.1541V18.4887H20.0088Z\" />\n <path d=\"M14.7486 10.9707C14.2851 10.9707 13.8952 11.1321 13.5789 11.4549C13.2626 11.7777 13.0854 12.1911 13.0472 12.6951H16.4337C16.4064 12.1741 16.2374 11.7579 15.9265 11.4464C15.6212 11.1293 15.2285 10.9707 14.7486 10.9707ZM16.4991 15.5153H19.1167C18.9749 16.4837 18.5141 17.2567 17.7343 17.8343C16.9599 18.4063 15.9838 18.6923 14.8059 18.6923C13.3662 18.6923 12.2374 18.2591 11.4194 17.3926C10.6014 16.5262 10.1924 15.3313 10.1924 13.8079C10.1924 12.2845 10.5987 11.0755 11.4112 10.1807C12.2237 9.28029 13.3226 8.83008 14.7077 8.83008C16.0656 8.83008 17.1481 9.26047 17.9552 10.1213C18.7677 10.9764 19.174 12.1231 19.174 13.5616V14.4195H13.0145V14.6064C13.0145 15.184 13.1835 15.6541 13.5216 16.0165C13.8597 16.3733 14.3015 16.5517 14.8468 16.5517C15.2503 16.5517 15.5993 16.461 15.8938 16.2798C16.1883 16.0929 16.3901 15.8381 16.4991 15.5153Z\" />\n <path d=\"M3.00205 8.58396V12.0667H4.7771C5.32789 12.0667 5.7587 11.911 6.06954 11.5995C6.38038 11.2881 6.5358 10.8662 6.5358 10.3338C6.5358 9.80718 6.37492 9.38528 6.05318 9.06815C5.73143 8.74535 5.30335 8.58396 4.76892 8.58396H3.00205ZM3.00205 14.1989V18.4886H0V6.23096H5.07158C6.53307 6.23096 7.65373 6.5849 8.43355 7.29278C9.21337 8.00066 9.60328 8.99453 9.60328 10.2744C9.60328 11.0446 9.42605 11.7439 9.07159 12.3725C8.71712 12.9955 8.2236 13.4514 7.59101 13.7402L9.94684 18.4886H6.5767L4.55624 14.1989H3.00205Z\" />\n <path\n d=\"M65.7255 0.211478C65.0841 2.46724 63.3737 4.2455 61.2041 4.90969C60.932 4.99366 60.932 5.39096 61.2041 5.47492C63.3725 6.13912 65.0841 7.91738 65.7255 10.1731C65.8056 10.4551 66.1932 10.4551 66.2745 10.1731C66.9159 7.91738 68.6263 6.13912 70.7959 5.47492C71.068 5.39096 71.068 4.99366 70.7959 4.90969C68.6276 4.2455 66.9159 2.46724 66.2745 0.211478C66.1944 -0.0704925 65.8068 -0.0704925 65.7255 0.211478Z\"\n fill={hovered ? \"#21FFB4\" : color}\n />\n </svg>\n );\n}\n\nexport function CopyIcon({ size = 14, color = \"#9EA0A1\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <rect\n x=\"5\"\n y=\"5\"\n width=\"9\"\n height=\"9\"\n rx=\"1\"\n stroke={color}\n strokeWidth=\"1.5\"\n />\n <path\n d=\"M11 5V3C11 2.44772 10.5523 2 10 2H3C2.44772 2 2 2.44772 2 3V10C2 10.5523 2.44772 11 3 11H5\"\n stroke={color}\n strokeWidth=\"1.5\"\n />\n </svg>\n );\n}\n\nexport function DisconnectIcon({ size = 14, color = \"#EA4335\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M6 14H3.33333C2.97971 14 2.64057 13.8595 2.39052 13.6095C2.14048 13.3594 2 13.0203 2 12.6667V3.33333C2 2.97971 2.14048 2.64057 2.39052 2.39052C2.64057 2.14048 2.97971 2 3.33333 2H6\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M10.6667 11.3333L14 8L10.6667 4.66667\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M14 8H6\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\nexport function SpinnerIcon({ size = 14, color = \"currentColor\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n style={{ animation: \"spin 1s linear infinite\" }}\n >\n <style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>\n <path d=\"M8 1V4\" stroke={color} strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n <path\n d=\"M8 12V15\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.3\"\n />\n <path\n d=\"M3.05 3.05L5.17 5.17\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.9\"\n />\n <path\n d=\"M10.83 10.83L12.95 12.95\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.4\"\n />\n <path\n d=\"M1 8H4\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.8\"\n />\n <path\n d=\"M12 8H15\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.5\"\n />\n <path\n d=\"M3.05 12.95L5.17 10.83\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.7\"\n />\n <path\n d=\"M10.83 5.17L12.95 3.05\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.6\"\n />\n </svg>\n );\n}\n\nexport function ChevronDownIcon({\n size = 14,\n color = \"currentColor\",\n style,\n}: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n style={style}\n >\n <path\n d=\"M4 6L8 10L12 6\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\nexport function UserIcon({ size = 24, color = \"#6366f1\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <circle cx=\"12\" cy=\"8\" r=\"4\" stroke={color} strokeWidth=\"2\" />\n <path\n d=\"M4 20C4 16.6863 7.58172 14 12 14C16.4183 14 20 16.6863 20 20\"\n stroke={color}\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n />\n </svg>\n );\n}\n","import {\n type HTMLAttributes,\n type ReactElement,\n type ReactNode,\n type Ref,\n Children,\n cloneElement,\n forwardRef,\n isValidElement,\n} from \"react\";\n\ntype AnyProps = Record<string, unknown>;\n\nfunction mergeProps(parentProps: AnyProps, childProps: AnyProps): AnyProps {\n const merged: AnyProps = { ...parentProps };\n\n for (const key of Object.keys(childProps)) {\n const parentValue = parentProps[key];\n const childValue = childProps[key];\n\n if (key === \"style\") {\n merged[key] = { ...(parentValue as object), ...(childValue as object) };\n } else if (key === \"className\") {\n merged[key] = [parentValue, childValue].filter(Boolean).join(\" \");\n } else if (\n typeof parentValue === \"function\" &&\n typeof childValue === \"function\"\n ) {\n merged[key] = (...args: unknown[]) => {\n (childValue as (...a: unknown[]) => void)(...args);\n (parentValue as (...a: unknown[]) => void)(...args);\n };\n } else if (childValue !== undefined) {\n merged[key] = childValue;\n }\n }\n\n return merged;\n}\n\ninterface SlotProps extends HTMLAttributes<HTMLElement> {\n children?: ReactNode;\n ref?: Ref<HTMLElement>;\n}\n\nexport const Slot = forwardRef<HTMLElement, SlotProps>(\n ({ children, ...props }, ref) => {\n const child = Children.only(children);\n\n if (!isValidElement(child)) {\n return null;\n }\n\n const childElement = child as ReactElement<AnyProps>;\n const mergedProps = mergeProps(props, childElement.props);\n\n if (ref) {\n mergedProps.ref = ref;\n }\n\n return cloneElement(childElement, mergedProps);\n },\n);\n\nSlot.displayName = \"Slot\";\n","import type { CSSProperties, ReactNode } from \"react\";\nimport { useCallback, useState } from \"react\";\nimport { openRenown } from \"../utils.js\";\nimport { SpinnerIcon } from \"./icons.js\";\nimport { Slot } from \"./slot.js\";\n\nexport interface RenownLoginButtonProps {\n onLogin?: () => void;\n darkMode?: boolean;\n style?: CSSProperties;\n className?: string;\n asChild?: boolean;\n children?: ReactNode;\n}\n\nconst lightStyles = {\n trigger: {\n backgroundColor: \"#ffffff\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#d1d5db\",\n color: \"#111827\",\n },\n triggerHover: {\n backgroundColor: \"#ecf3f8\",\n borderColor: \"#9ca3af\",\n },\n} as const;\n\nconst darkStyles = {\n trigger: {\n backgroundColor: \"#1f2937\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#4b5563\",\n color: \"#ecf3f8\",\n },\n triggerHover: {\n backgroundColor: \"#374151\",\n borderColor: \"#6b7280\",\n },\n} as const;\n\nconst styles: Record<string, CSSProperties> = {\n wrapper: {\n position: \"relative\",\n display: \"inline-block\",\n },\n trigger: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: \"8px\",\n padding: \"8px 32px\",\n borderRadius: \"8px\",\n cursor: \"pointer\",\n fontSize: \"14px\",\n fontWeight: 500,\n fontFamily: \"inherit\",\n lineHeight: \"20px\",\n transition: \"background-color 150ms, border-color 150ms\",\n },\n};\n\nexport function RenownLoginButton({\n onLogin: onLoginProp,\n darkMode = false,\n style,\n className,\n asChild = false,\n children,\n}: RenownLoginButtonProps) {\n const onLogin = onLoginProp ?? (() => openRenown());\n const [isLoading, setIsLoading] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n\n const handleMouseEnter = useCallback(() => setIsHovered(true), []);\n const handleMouseLeave = useCallback(() => setIsHovered(false), []);\n\n const handleClick = () => {\n if (!isLoading) {\n setIsLoading(true);\n onLogin();\n }\n };\n\n const themeStyles = darkMode ? darkStyles : lightStyles;\n\n const triggerStyle: CSSProperties = {\n ...styles.trigger,\n ...themeStyles.trigger,\n ...(isHovered && !isLoading ? themeStyles.triggerHover : {}),\n cursor: isLoading ? \"wait\" : \"pointer\",\n ...style,\n };\n\n const triggerElement = asChild ? (\n <Slot\n onClick={handleClick}\n data-renown-state=\"login\"\n {...(isLoading ? { \"data-loading\": \"\" } : {})}\n >\n {children}\n </Slot>\n ) : (\n <button\n type=\"button\"\n style={triggerStyle}\n aria-label=\"Log in with Renown\"\n onClick={handleClick}\n data-renown-state=\"login\"\n {...(isLoading ? { \"data-loading\": \"\" } : {})}\n >\n {isLoading ? <SpinnerIcon size={16} /> : <span>Log in</span>}\n </button>\n );\n\n return (\n <div\n style={styles.wrapper}\n className={className}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n {triggerElement}\n </div>\n );\n}\n","import type { CSSProperties, ReactNode } from \"react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useUser } from \"../../hooks/renown.js\";\nimport { logout as defaultLogout, openRenown } from \"../utils.js\";\nimport {\n ChevronDownIcon,\n CopyIcon,\n DisconnectIcon,\n UserIcon,\n} from \"./icons.js\";\nimport { Slot } from \"./slot.js\";\n\nconst POPOVER_GAP = 4;\nconst POPOVER_HEIGHT = 150;\n\nexport interface RenownUserButtonMenuItem {\n label: string;\n icon?: ReactNode;\n onClick: () => void;\n style?: CSSProperties;\n}\n\nexport interface RenownUserButtonProps {\n address?: string;\n username?: string;\n avatarUrl?: string;\n userId?: string;\n onDisconnect?: () => void;\n style?: CSSProperties;\n className?: string;\n asChild?: boolean;\n children?: ReactNode;\n menuItems?: RenownUserButtonMenuItem[];\n}\n\nconst styles: Record<string, CSSProperties> = {\n wrapper: {\n position: \"relative\",\n display: \"inline-block\",\n },\n trigger: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n padding: \"6px 12px\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#e5e7eb\",\n backgroundColor: \"#ffffff\",\n cursor: \"pointer\",\n borderRadius: \"8px\",\n fontSize: \"12px\",\n fontWeight: 500,\n fontFamily: \"inherit\",\n color: \"#111827\",\n transition: \"background-color 150ms, border-color 150ms\",\n },\n triggerHover: {\n backgroundColor: \"#f9fafb\",\n borderColor: \"#9ca3af\",\n },\n avatar: {\n width: \"28px\",\n height: \"28px\",\n borderRadius: \"50%\",\n objectFit: \"cover\",\n flexShrink: 0,\n },\n avatarPlaceholder: {\n width: \"28px\",\n height: \"28px\",\n borderRadius: \"50%\",\n background: \"linear-gradient(135deg, #8b5cf6, #3b82f6)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n flexShrink: 0,\n },\n avatarInitial: {\n fontSize: \"12px\",\n fontWeight: 700,\n color: \"#ffffff\",\n lineHeight: 1,\n },\n displayName: {\n maxWidth: \"120px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n },\n chevron: {\n flexShrink: 0,\n transition: \"transform 150ms\",\n color: \"#6b7280\",\n },\n chevronOpen: {\n transform: \"rotate(180deg)\",\n },\n popoverBase: {\n position: \"absolute\",\n right: 0,\n backgroundColor: \"#ffffff\",\n borderRadius: \"8px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 3px rgba(0, 0, 0, 0.08)\",\n width: \"100%\",\n zIndex: 1000,\n color: \"#111827\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#e5e7eb\",\n overflow: \"hidden\",\n },\n header: {\n padding: \"12px 16px\",\n borderBottom: \"1px solid #e5e7eb\",\n },\n headerUsername: {\n fontSize: \"14px\",\n fontWeight: 600,\n color: \"#111827\",\n margin: 0,\n },\n addressRow: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n marginTop: \"4px\",\n },\n addressButton: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n padding: 0,\n border: \"none\",\n backgroundColor: \"transparent\",\n cursor: \"pointer\",\n fontSize: \"12px\",\n color: \"#6b7280\",\n fontFamily: \"inherit\",\n position: \"relative\",\n width: \"100%\",\n },\n copiedText: {\n fontSize: \"12px\",\n color: \"#059669\",\n position: \"absolute\",\n left: 0,\n transition: \"opacity 150ms\",\n fontWeight: 500,\n },\n addressText: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n transition: \"opacity 150ms\",\n },\n menuSection: {\n padding: \"4px 0\",\n },\n menuItem: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n width: \"100%\",\n padding: \"8px 16px\",\n border: \"none\",\n backgroundColor: \"transparent\",\n cursor: \"pointer\",\n fontSize: \"14px\",\n color: \"#374151\",\n textDecoration: \"none\",\n fontFamily: \"inherit\",\n transition: \"background-color 150ms\",\n },\n menuItemHover: {\n backgroundColor: \"#f3f4f6\",\n },\n disconnectItem: {\n color: \"#dc2626\",\n },\n separator: {\n height: \"1px\",\n backgroundColor: \"#e5e7eb\",\n margin: 0,\n border: \"none\",\n },\n};\n\nfunction truncateAddress(address: string): string {\n if (address.length <= 13) return address;\n return `${address.slice(0, 7)}...${address.slice(-5)}`;\n}\n\nexport function RenownUserButton({\n address: addressProp,\n username: usernameProp,\n avatarUrl: avatarUrlProp,\n userId: userIdProp,\n onDisconnect: onDisconnectProp,\n style,\n className,\n asChild = false,\n children,\n menuItems,\n}: RenownUserButtonProps) {\n const user = useUser();\n\n const address = addressProp ?? user?.address ?? \"\";\n const username = usernameProp ?? user?.profile?.username ?? user?.ens?.name;\n const avatarUrl =\n avatarUrlProp ?? user?.profile?.userImage ?? user?.ens?.avatarUrl;\n const userId = userIdProp ?? user?.profile?.documentId;\n const onDisconnect = onDisconnectProp ?? (() => void defaultLogout());\n const displayName =\n username ?? (address ? truncateAddress(address) : \"Account\");\n const profileId = userId ?? address;\n\n const [isOpen, setIsOpen] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const [isCopied, setIsCopied] = useState(false);\n const [showAbove, setShowAbove] = useState(true);\n const [hoveredItem, setHoveredItem] = useState<string | null>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const closeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const calculatePosition = useCallback(() => {\n if (!wrapperRef.current) return;\n const rect = wrapperRef.current.getBoundingClientRect();\n const spaceAbove = rect.top;\n setShowAbove(spaceAbove >= POPOVER_HEIGHT + POPOVER_GAP);\n }, []);\n\n const handleMouseEnter = useCallback(() => {\n setIsHovered(true);\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = null;\n }\n calculatePosition();\n setIsOpen(true);\n }, [calculatePosition]);\n\n const handleMouseLeave = useCallback(() => {\n closeTimeoutRef.current = setTimeout(() => {\n setIsOpen(false);\n setIsHovered(false);\n setHoveredItem(null);\n }, 150);\n }, []);\n\n useEffect(() => {\n return () => {\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current);\n }\n };\n }, []);\n\n const copyToClipboard = useCallback(async () => {\n try {\n await navigator.clipboard.writeText(address);\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), 2000);\n } catch (err) {\n console.error(\"Failed to copy address:\", err);\n }\n }, [address]);\n\n const triggerElement = asChild ? (\n <Slot data-renown-state=\"authenticated\">{children}</Slot>\n ) : (\n <button\n type=\"button\"\n style={{\n ...styles.trigger,\n ...(isHovered ? styles.triggerHover : {}),\n ...style,\n }}\n aria-label=\"Open account menu\"\n data-renown-state=\"authenticated\"\n >\n {avatarUrl ? (\n <img src={avatarUrl} alt=\"Avatar\" style={styles.avatar} />\n ) : (\n <div style={styles.avatarPlaceholder}>\n <span style={styles.avatarInitial}>\n {(displayName || \"U\")[0].toUpperCase()}\n </span>\n </div>\n )}\n <span style={styles.displayName}>{displayName}</span>\n <ChevronDownIcon\n size={14}\n style={{\n ...styles.chevron,\n ...(isOpen ? styles.chevronOpen : {}),\n }}\n />\n </button>\n );\n\n return (\n <div\n ref={wrapperRef}\n style={styles.wrapper}\n className={className}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n {triggerElement}\n {isOpen && (\n <div\n style={{\n ...styles.popoverBase,\n ...(showAbove\n ? { bottom: `calc(100% + ${POPOVER_GAP}px)` }\n : { top: `calc(100% + ${POPOVER_GAP}px)` }),\n }}\n >\n <div style={styles.header}>\n {username && <div style={styles.headerUsername}>{username}</div>}\n {address && (\n <div style={styles.addressRow}>\n <button\n type=\"button\"\n onClick={() => void copyToClipboard()}\n style={styles.addressButton}\n >\n <div\n style={{\n position: \"relative\",\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n width: \"100%\",\n }}\n >\n <div\n style={{\n ...styles.addressText,\n opacity: isCopied ? 0 : 1,\n }}\n >\n <span>{truncateAddress(address)}</span>\n <CopyIcon size={12} color=\"#9ca3af\" />\n </div>\n <div\n style={{\n ...styles.copiedText,\n opacity: isCopied ? 1 : 0,\n }}\n >\n Copied!\n </div>\n </div>\n </button>\n </div>\n )}\n </div>\n <div style={styles.menuSection}>\n {profileId && (\n <button\n type=\"button\"\n onClick={() => openRenown(profileId)}\n onMouseEnter={() => setHoveredItem(\"profile\")}\n onMouseLeave={() => setHoveredItem(null)}\n style={{\n ...styles.menuItem,\n ...(hoveredItem === \"profile\" ? styles.menuItemHover : {}),\n }}\n >\n <UserIcon size={14} color=\"#6b7280\" />\n View Profile\n </button>\n )}\n {menuItems?.map((item) => (\n <button\n key={item.label}\n type=\"button\"\n onClick={item.onClick}\n onMouseEnter={() => setHoveredItem(item.label)}\n onMouseLeave={() => setHoveredItem(null)}\n style={{\n ...styles.menuItem,\n ...(hoveredItem === item.label ? styles.menuItemHover : {}),\n ...item.style,\n }}\n >\n {item.icon}\n {item.label}\n </button>\n ))}\n </div>\n <hr style={styles.separator} />\n <div style={styles.menuSection}>\n <button\n type=\"button\"\n onClick={onDisconnect}\n onMouseEnter={() => setHoveredItem(\"disconnect\")}\n onMouseLeave={() => setHoveredItem(null)}\n style={{\n ...styles.menuItem,\n ...styles.disconnectItem,\n ...(hoveredItem === \"disconnect\" ? styles.menuItemHover : {}),\n }}\n >\n <DisconnectIcon size={14} color=\"#dc2626\" />\n Log out\n </button>\n </div>\n </div>\n )}\n </div>\n );\n}\n","import type { ReactNode } from \"react\";\nimport { type RenownAuth, useRenownAuth } from \"../use-renown-auth.js\";\nimport { RenownLoginButton } from \"./RenownLoginButton.js\";\nimport { RenownUserButton } from \"./RenownUserButton.js\";\n\nexport interface RenownAuthButtonProps {\n className?: string;\n darkMode?: boolean;\n loginContent?: ReactNode;\n userContent?: ReactNode;\n loadingContent?: ReactNode;\n children?: (auth: RenownAuth) => ReactNode;\n}\n\nexport function RenownAuthButton({\n className = \"\",\n darkMode,\n loginContent,\n userContent,\n loadingContent,\n children,\n}: RenownAuthButtonProps) {\n const auth = useRenownAuth();\n\n if (children) {\n return <>{children(auth)}</>;\n }\n\n if (auth.status === \"loading\" || auth.status === \"checking\") {\n if (loadingContent) {\n return <div className={className}>{loadingContent}</div>;\n }\n\n return (\n <div className={className}>\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n padding: \"6px 12px\",\n borderRadius: \"8px\",\n border: \"1px solid #e5e7eb\",\n animation: \"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite\",\n }}\n >\n <div\n style={{\n width: \"28px\",\n height: \"28px\",\n borderRadius: \"50%\",\n backgroundColor: \"#e5e7eb\",\n }}\n />\n <div\n style={{\n width: \"80px\",\n height: \"14px\",\n borderRadius: \"4px\",\n backgroundColor: \"#e5e7eb\",\n }}\n />\n </div>\n <style>{`@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }`}</style>\n </div>\n );\n }\n\n if (auth.status === \"authorized\") {\n if (userContent) {\n return <div className={className}>{userContent}</div>;\n }\n\n return (\n <div className={className}>\n <RenownUserButton />\n </div>\n );\n }\n\n if (loginContent) {\n return <div className={className}>{loginContent}</div>;\n }\n\n return (\n <div className={className}>\n <RenownLoginButton darkMode={darkMode} />\n </div>\n );\n}\n","import type { IRenown } from \"@renown/sdk\";\nimport { RenownBuilder } from \"@renown/sdk\";\nimport { useRef } from \"react\";\nimport { loading } from \"../hooks/loading.js\";\nimport { addRenownEventHandler, setRenown } from \"../hooks/renown.js\";\nimport { login } from \"./utils.js\";\n\nexport interface RenownInitOptions {\n appName: string;\n /**\n * Prefix for localStorage keys, allowing multiple apps\n * to use Renown on the same domain without conflicts.\n */\n namespace?: string;\n url?: string;\n}\n\nasync function initRenown(\n appName: string,\n namespace: string | undefined,\n url: string | undefined,\n): Promise<IRenown> {\n addRenownEventHandler();\n setRenown(loading);\n\n const builder = new RenownBuilder(appName, {\n basename: namespace,\n baseUrl: url,\n });\n const renown = await builder.build();\n setRenown(renown);\n\n await login(undefined, renown);\n\n return renown;\n}\n\n/**\n * Hook that initializes the Renown SDK.\n * Call once at the top of your app. Options are read only on first mount.\n * Returns a promise that resolves with the Renown instance.\n *\n * @example\n * ```tsx\n * function App() {\n * const renownPromise = useRenownInit({ appName: \"my-app\" });\n * return <MyApp />;\n * }\n * ```\n */\nexport function useRenownInit({\n appName,\n namespace,\n url,\n}: RenownInitOptions): Promise<IRenown> {\n const promiseRef = useRef(Promise.withResolvers<IRenown>());\n const initRef = useRef(false);\n\n if (typeof window === \"undefined\") {\n promiseRef.current.reject(new Error(\"window is undefined\"));\n return promiseRef.current.promise;\n }\n\n if (initRef.current) {\n return promiseRef.current.promise;\n }\n\n initRef.current = true;\n\n initRenown(appName, namespace, url)\n .then(promiseRef.current.resolve)\n .catch(promiseRef.current.reject);\n\n return promiseRef.current.promise;\n}\n","import { type RenownInitOptions, useRenownInit } from \"./use-renown-init.js\";\n\nexport interface RenownProps extends RenownInitOptions {\n onError?: (error: unknown) => void;\n}\n\n/**\n * Side-effect component that initializes the Renown SDK.\n * Renders nothing — place it alongside your app tree.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <>\n * <Renown appName=\"my-app\" onError={console.error} />\n * <MyApp />\n * </>\n * );\n * }\n * ```\n */\nexport function Renown({ onError, ...initOptions }: RenownProps) {\n useRenownInit(initOptions).catch(onError ?? console.error);\n return null;\n}\n","export abstract class BaseStorage<V> implements Iterable<[string, V]> {\n abstract get(key: string): V | undefined;\n abstract set(key: string, value: V): void;\n abstract delete(key: string): boolean;\n abstract has(key: string): boolean;\n abstract clear(): void;\n abstract entries(): IterableIterator<[string, V]>;\n abstract keys(): IterableIterator<string>;\n abstract values(): IterableIterator<V>;\n\n [Symbol.iterator](): IterableIterator<[string, V]> {\n return this.entries();\n }\n\n forEach(\n callback: (value: V, key: string, storage: BaseStorage<V>) => void,\n ): void {\n for (const [key, value] of this) {\n callback(value, key, this);\n }\n }\n}\n","import { BaseStorage } from \"./base-storage.js\";\n\nexport class BrowserLocalStorage<V> extends BaseStorage<V> {\n #namespace: string;\n #storage = window.localStorage;\n constructor(namespace: string) {\n super();\n this.#namespace = namespace;\n }\n\n #readMap(): Map<string, V> {\n const raw = this.#storage.getItem(this.#namespace);\n\n if (!raw) {\n return new Map();\n }\n\n return new Map(JSON.parse(raw) as [string, V][]);\n }\n\n #writeMap(map: Map<string, V>): void {\n this.#storage.setItem(\n this.#namespace,\n JSON.stringify(Array.from(map.entries())),\n );\n }\n\n get(key: string): V | undefined {\n return this.#readMap().get(key);\n }\n\n set(key: string, value: V): void {\n const map = this.#readMap();\n map.set(key, value);\n this.#writeMap(map);\n }\n\n delete(key: string): boolean {\n const map = this.#readMap();\n const deleted = map.delete(key);\n if (deleted) {\n this.#writeMap(map);\n }\n return deleted;\n }\n\n has(key: string): boolean {\n return this.#readMap().has(key);\n }\n\n clear(): void {\n this.#storage.removeItem(this.#namespace);\n }\n\n entries(): IterableIterator<[string, V]> {\n return this.#readMap().entries();\n }\n\n keys(): IterableIterator<string> {\n return this.#readMap().keys();\n }\n\n values(): IterableIterator<V> {\n return this.#readMap().values();\n }\n\n [Symbol.iterator](): IterableIterator<[string, V]> {\n return this.#readMap().entries();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AASA,eAAsB,aACpB,UACA,iBACA;AACA,KAAI,CAAC,SACH,OAAM,IAAI,MAAM,uBAAuB;AAEzC,KAAI,CAAC,gBACH,OAAM,IAAI,MAAM,sBAAsB;CAExC,MAAM,UAAU,MAAM,QAAQ,gBAA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C1C;;CAGH,IAAI,KAA4B;AAC9B,SAAO,MAAA,SAAe,CAAC,IAAI,IAAI;;CAGjC,IAAI,KAAa,OAAgB;EAC/B,MAAM,MAAM,MAAA,SAAe;AAC3B,MAAI,IAAI,KAAK,MAAM;AACnB,QAAA,SAAe,IAAI;;CAGrB,OAAO,KAAsB;EAC3B,MAAM,MAAM,MAAA,SAAe;EAC3B,MAAM,UAAU,IAAI,OAAO,IAAI;AAC/B,MAAI,QACF,OAAA,SAAe,IAAI;AAErB,SAAO;;CAGT,IAAI,KAAsB;AACxB,SAAO,MAAA,SAAe,CAAC,IAAI,IAAI;;CAGjC,QAAc;AACZ,QAAA,QAAc,WAAW,MAAA,UAAgB;;CAG3C,UAAyC;AACvC,SAAO,MAAA,SAAe,CAAC,SAAS;;CAGlC,OAAiC;AAC/B,SAAO,MAAA,SAAe,CAAC,MAAM;;CAG/B,SAA8B;AAC5B,SAAO,MAAA,SAAe,CAAC,QAAQ;;CAGjC,CAAC,OAAO,YAA2C;AACjD,SAAO,MAAA,SAAe,CAAC,SAAS"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["baseAddFolder","baseDeleteNode","copyNode","baseCopyNode","driveCollectionId","DocumentChangeType","truncateAddress","logoutUtil","copyNode","driveCollectionId","GqlRequestChannel","REACTOR_SCHEMA","styles","defaultLogout","#namespace","#storage","#readMap","#writeMap"],"sources":["../src/actions/queue.ts","../src/actions/sign.ts","../src/actions/dispatch.ts","../src/errors.ts","../src/utils/documents.ts","../src/utils/user.ts","../src/actions/document.ts","../src/actions/drive.ts","../src/global/core.ts","../src/analytics/context.tsx","../src/analytics/hooks/analytics-query.ts","../src/hooks/dispatch.ts","../src/document-cache.ts","../src/hooks/make-ph-event-functions.ts","../src/hooks/document-cache.ts","../src/hooks/document-by-id.ts","../src/analytics/hooks/timeline-items.ts","../src/analytics/hooks/document-timeline.ts","../src/constants.ts","../src/document-model.ts","../src/graphql/gen/schema.ts","../src/graphql/batch-queries.ts","../src/graphql/client.ts","../src/hooks/loading.ts","../src/hooks/renown.ts","../src/renown/constants.ts","../src/renown/utils.ts","../src/renown/use-renown-auth.ts","../src/hooks/config/editor.ts","../src/hooks/config/connect.ts","../src/hooks/features.ts","../src/hooks/package-discovery.ts","../src/hooks/drives.ts","../src/hooks/modals.ts","../src/hooks/reactor.ts","../src/hooks/revision-history.ts","../src/utils/url.ts","../src/hooks/selected-drive.ts","../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/selected-timeline-item.ts","../src/hooks/timeline-revision.ts","../src/hooks/toast.ts","../src/hooks/vetra-packages.ts","../src/hooks/add-ph-event-handlers.ts","../src/hooks/document-model-modules.ts","../src/hooks/allowed-document-model-modules.ts","../src/hooks/selected-folder.ts","../src/hooks/child-nodes.ts","../src/hooks/config/set-config-by-key.ts","../src/hooks/config/utils.ts","../src/hooks/config/set-config-by-object.ts","../src/hooks/config/use-value-by-key.ts","../src/hooks/connection-state.ts","../src/hooks/document-of-type.ts","../src/hooks/document-operations.ts","../src/hooks/supported-document-types.ts","../src/hooks/document-types.ts","../src/hooks/drive-by-id.ts","../src/hooks/editor-modules.ts","../src/hooks/folder-by-id.ts","../src/hooks/items-in-selected-folder.ts","../src/hooks/node-actions.ts","../src/hooks/node-by-id.ts","../src/hooks/node-path.ts","../src/hooks/parent-folder.ts","../src/hooks/selected-document.ts","../src/hooks/subgraph-modules.ts","../src/hooks/use-feature-flags.ts","../src/utils/drives.ts","../src/utils/validate-document.ts","../src/utils/export-document.ts","../src/utils/get-revision-from-date.ts","../src/utils/switchboard.ts","../src/hooks/use-get-switchboard-link.ts","../src/hooks/use-on-drop-file.ts","../src/hooks/user-permissions.ts","../src/pglite/drop.ts","../src/reactor.ts","../src/registry/fetchers.ts","../src/registry/client.ts","../src/pglite/usePGlite.ts","../src/relational/hooks/useRelationalDb.ts","../src/relational/hooks/useRelationalQuery.ts","../src/relational/utils/createProcessorQuery.ts","../src/remote-controller/action-tracker.ts","../src/remote-controller/remote-client.ts","../src/remote-controller/utils.ts","../src/remote-controller/remote-controller.ts","../src/renown/components/icons.tsx","../src/renown/components/slot.tsx","../src/renown/components/RenownLoginButton.tsx","../src/renown/components/RenownUserButton.tsx","../src/renown/components/RenownAuthButton.tsx","../src/renown/use-renown-init.ts","../src/renown/renown-init.tsx","../src/storage/base-storage.ts","../src/storage/local-storage.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 { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport {\n buildSignedAction,\n type ActionSigner,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\n\nexport async function signAction(action: Action, document: PHDocument) {\n const reactor = window.ph?.reactorClient;\n if (!reactor) return action;\n\n const documentModelModule = await reactor.getDocumentModelModule(\n document.header.documentType,\n );\n const reducer = documentModelModule.reducer;\n const renown = window.ph?.renown;\n if (!renown?.user) return action;\n if (!action.context?.signer) return action;\n\n const actionSigner = action.context.signer;\n const unsafeSignedAction = await buildSignedAction(\n action,\n reducer,\n document,\n actionSigner,\n renown.crypto.sign,\n );\n\n // TODO: this is super dangerous and is caused by the `buildSignedAction` function returning an `Operation` instead of an `Action`\n return unsafeSignedAction as unknown as Action;\n}\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\nasync function 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 const signedAction = await signAction(action, document);\n const signedActionWithContext = addActionContext(signedAction);\n return signedActionWithContext;\n}\n\nexport async 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 = await Promise.all(\n actions.map((action) => 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 = await 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","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 DocumentNotFoundError extends Error {\n constructor(documentId: string) {\n super(`Document with id ${documentId} not found`);\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","export function isDocumentTypeSupported(\n documentType: string,\n supportedDocuments: string[] | null | undefined,\n): boolean {\n if (!supportedDocuments?.length) {\n return true;\n }\n\n return supportedDocuments.some((pattern) => {\n // Path wildcard: \"powerhouse/*\"\n if (pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -2);\n return documentType.startsWith(prefix + \"/\");\n }\n\n // Prefix wildcard: \"power*\"\n if (pattern.endsWith(\"*\") && !pattern.endsWith(\"/*\")) {\n const prefix = pattern.slice(0, -1);\n return documentType.startsWith(prefix);\n }\n\n // Exact match\n return pattern === documentType;\n });\n}\n","export function getUserPermissions() {\n const user = window.ph?.renown?.user;\n const allowList = window.ph?.allowList;\n if (!allowList) {\n return {\n isAllowedToCreateDocuments: true,\n isAllowedToEditDocuments: true,\n };\n }\n return {\n isAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n isAllowedToEditDocuments: allowList.includes(user?.address ?? \"\"),\n };\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport type {\n ConflictResolution,\n DocumentTypeIcon,\n FileUploadProgressCallback,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n addFolder as baseAddFolder,\n copyNode as baseCopyNode,\n deleteNode as baseDeleteNode,\n updateFile as baseUpdateFile,\n generateNodesCopy,\n handleTargetNameCollisions,\n isFileNode,\n isFolderNode,\n updateNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelModule,\n DocumentOperations,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n baseLoadFromInput,\n baseSaveToFileHandle,\n createPresignedHeader,\n createZip,\n documentModelDocumentType,\n generateId,\n replayDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { logger } from \"document-model\";\nimport {\n DocumentModelNotFoundError,\n UnsupportedDocumentTypeError,\n} from \"../errors.js\";\nimport { isDocumentTypeSupported } from \"../utils/documents.js\";\nimport { getUserPermissions } from \"../utils/user.js\";\nimport { queueActions, queueOperations, uploadOperations } from \"./queue.js\";\n\nasync function isDocumentInLocation(\n document: PHDocument,\n driveId: string,\n parentFolder?: string,\n): Promise<{\n isDuplicate: boolean;\n duplicateType?: \"id\" | \"name\";\n nodeId?: string;\n}> {\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n return { isDuplicate: false };\n }\n\n // Get the drive and check its nodes\n let drive;\n try {\n drive = await reactorClient.get<DocumentDriveDocument>(driveId);\n } catch {\n return { isDuplicate: false };\n }\n\n // Case 1: Check for duplicate by ID\n const nodeById = drive.state.global.nodes.find(\n (node: { id: string }) => node.id === document.header.id,\n );\n\n if (nodeById && nodeById.parentFolder === (parentFolder ?? null)) {\n return {\n isDuplicate: true,\n duplicateType: \"id\",\n nodeId: nodeById.id,\n };\n }\n\n // Case 2: Check for duplicate by name + type in same parent folder\n const nodeByNameAndType = drive.state.global.nodes.find(\n (node: Node) =>\n isFileNode(node) &&\n node.name === document.header.name &&\n node.documentType === document.header.documentType &&\n node.parentFolder === (parentFolder ?? null),\n );\n\n if (nodeByNameAndType) {\n return {\n isDuplicate: true,\n duplicateType: \"name\",\n nodeId: nodeByNameAndType.id,\n };\n }\n\n return { isDuplicate: false };\n}\n\nfunction getDocumentTypeIcon(\n document: PHDocument,\n): DocumentTypeIcon | undefined {\n const documentType = document.header.documentType;\n\n switch (documentType) {\n case \"powerhouse/document-model\":\n return \"document-model\";\n case \"powerhouse/app\":\n return \"app\";\n case \"powerhouse/document-editor\":\n return \"editor\";\n case \"powerhouse/subgraph\":\n return \"subgraph\";\n case \"powerhouse/package\":\n return \"package\";\n case \"powerhouse/processor\": {\n // Check the processor type from global state (safely)\n const globalState = (document.state as { global?: { type?: string } })\n .global;\n const processorType = globalState?.type;\n\n if (processorType === \"analytics\") return \"analytics-processor\";\n if (processorType === \"relational\") return \"relational-processor\";\n if (processorType === \"codegen\") return \"codegen-processor\";\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\nexport function downloadFile(document: PHDocument, fileName: string) {\n const zip = createZip(document);\n zip\n .generateAsync({ type: \"blob\" })\n .then((blob) => {\n const link = window.document.createElement(\"a\");\n link.style.display = \"none\";\n link.href = URL.createObjectURL(blob);\n link.download = fileName;\n\n window.document.body.appendChild(link);\n link.click();\n\n window.document.body.removeChild(link);\n })\n .catch(logger.error);\n}\n\nasync function getDocumentExtension(document: PHDocument): Promise<string> {\n const documentType = document.header.documentType;\n\n // DocumentModel definitions always use \"phdm\"\n if (documentType === documentModelDocumentType) {\n return \"phdm\";\n }\n\n let rawExtension: string | undefined;\n\n const reactorClient = window.ph?.reactorClient;\n if (reactorClient) {\n const { results: documentModelModules } =\n await reactorClient.getDocumentModelModules();\n const module = documentModelModules.find(\n (m: DocumentModelModule) => m.documentModel.global.id === documentType,\n );\n rawExtension = module?.utils.fileExtension;\n }\n\n // Clean the extension (remove leading/trailing dots) and fallback to \"phdm\"\n const cleanExtension = (rawExtension ?? \"phdm\").replace(/^\\.+|\\.+$/g, \"\");\n return cleanExtension || \"phdm\";\n}\n\nconst BASE_STATE_KEYS = new Set([\"auth\", \"document\"]);\n\n/**\n * Fetches all operations for a document using cursor-based pagination.\n * The reactor client handles multi-scope cursors transparently via\n * composite cursors, so all scopes are fetched in a single paginated stream.\n */\nexport async function fetchDocumentOperations(\n reactorClient: IReactorClient,\n document: PHDocument,\n pageSize = 100,\n): Promise<DocumentOperations> {\n const scopes = Object.keys(document.state).filter(\n (k) => !BASE_STATE_KEYS.has(k),\n );\n const operations: DocumentOperations = {};\n for (const scope of scopes) {\n operations[scope] = [];\n }\n\n let cursor = \"\";\n\n do {\n const page = await reactorClient.getOperations(\n document.header.id,\n { scopes },\n undefined,\n { cursor, limit: pageSize },\n );\n\n for (const op of page.results) {\n const scope = op.action.scope ?? \"global\";\n if (operations[scope]) {\n operations[scope].push(op);\n }\n }\n\n cursor = page.nextCursor ?? \"\";\n } while (cursor);\n\n return operations;\n}\n\nexport async function exportFile(document: PHDocument, suggestedName?: string) {\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Fetch operations page-by-page (document from reactor has operations: {})\n const operations = await fetchDocumentOperations(reactorClient, document);\n const documentWithOps = { ...document, operations };\n\n // Get the extension from the document model module\n const extension = await getDocumentExtension(documentWithOps);\n\n const name = `${suggestedName || documentWithOps.header.name || \"Untitled\"}.${extension}.phd`;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!window.showSaveFilePicker) {\n return downloadFile(documentWithOps, name);\n }\n try {\n const fileHandle = await window.showSaveFilePicker({\n suggestedName: name,\n });\n\n await baseSaveToFileHandle(documentWithOps, fileHandle);\n return fileHandle;\n } catch (e) {\n // ignores error if user cancelled the file picker\n if (!(e instanceof DOMException && e.name === \"AbortError\")) {\n throw e;\n }\n }\n}\n\nexport async function loadFile(path: string | File) {\n const baseDocument = await baseLoadFromInput(\n path,\n (state: PHDocument) => state,\n { checkHashes: true },\n );\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n const { results: documentModelModules } =\n await reactorClient.getDocumentModelModules();\n const documentModelModule = documentModelModules.find(\n (module) =>\n module.documentModel.global.id === baseDocument.header.documentType,\n );\n if (!documentModelModule) {\n throw new DocumentModelNotFoundError(baseDocument.header.documentType);\n }\n return documentModelModule.utils.loadFromInput(path);\n}\n\nexport async function addDocument(\n driveId: string,\n name: string,\n documentType: string,\n parentFolder?: string,\n document?: PHDocument,\n id?: string,\n preferredEditor?: string,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // get the module\n const documentModelModule =\n await reactorClient.getDocumentModelModule(documentType);\n\n // create - use passed document's state if available\n const newDocument = document ?? documentModelModule.utils.createDocument();\n newDocument.header.name = name;\n if (preferredEditor) {\n newDocument.header.meta = {\n ...newDocument.header.meta,\n preferredEditor,\n };\n }\n\n // Create document using ReactorClient\n let newDoc: PHDocument;\n try {\n newDoc = await reactorClient.createDocumentInDrive(\n driveId,\n newDocument,\n parentFolder,\n );\n } catch (e) {\n logger.error(\"Error adding document\", e);\n throw new Error(\"There was an error adding document\");\n }\n\n // Return a file node structure for compatibility\n return {\n id: newDoc.header.id,\n name: newDoc.header.name,\n documentType,\n parentFolder: parentFolder ?? null,\n kind: \"file\" as const,\n };\n}\n\nexport async function addFile(\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n) {\n logger.verbose(\n `addFile(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`,\n );\n\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create files\");\n }\n\n const document = await loadFile(file);\n\n let duplicateId = false;\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n try {\n await reactorClient.get(document.header.id);\n duplicateId = true;\n } catch {\n // document id not found\n }\n\n const documentId = duplicateId ? generateId() : document.header.id;\n const header = createPresignedHeader(\n documentId,\n document.header.documentType,\n );\n header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n header.meta = document.header.meta;\n header.name = name || document.header.name;\n\n // copy the document at it's initial state\n const initialDocument = {\n ...document,\n header,\n state: document.initialState,\n operations: Object.keys(document.operations).reduce((acc, key) => {\n acc[key] = [];\n return acc;\n }, {} as DocumentOperations),\n };\n\n await addDocument(\n driveId,\n name || document.header.name,\n document.header.documentType,\n parentFolder,\n initialDocument,\n documentId,\n document.header.meta?.preferredEditor,\n );\n\n // then add all the operations in chunks\n await uploadOperations(documentId, document.operations, queueOperations);\n}\n\nexport async function addFileWithProgress(\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n onProgress?: FileUploadProgressCallback,\n documentTypes?: string[],\n resolveConflict?: ConflictResolution,\n) {\n logger.verbose(\n `addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`,\n );\n const reactor = window.ph?.reactorClient;\n if (!reactor) {\n return;\n }\n\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create files\");\n }\n\n // Loading stage (0-10%)\n try {\n onProgress?.({ stage: \"loading\", progress: 0 });\n let document: PHDocument;\n try {\n document = await loadFile(file);\n } catch (loadError) {\n // Only attempt discovery if the failure is specifically a missing\n // document model module, not for other errors like corrupt files.\n const discoveryService = window.ph?.packageDiscoveryService;\n if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {\n // Trigger discovery and retry without blocking the drop handler\n void retryAfterDiscovery(\n discoveryService,\n loadError.documentType,\n file,\n driveId,\n name,\n parentFolder,\n onProgress,\n documentTypes,\n resolveConflict,\n );\n return;\n }\n throw loadError;\n }\n\n // Check for duplicate in same location\n const duplicateCheck = await isDocumentInLocation(\n document,\n driveId,\n parentFolder,\n );\n\n if (duplicateCheck.isDuplicate && !resolveConflict) {\n // Report conflict and return early\n onProgress?.({\n stage: \"conflict\",\n progress: 0,\n duplicateType: duplicateCheck.duplicateType,\n });\n return undefined;\n }\n\n // Handle replace resolution by deleting the existing document\n if (\n duplicateCheck.isDuplicate &&\n resolveConflict === \"replace\" &&\n duplicateCheck.nodeId\n ) {\n await deleteNode(driveId, duplicateCheck.nodeId);\n }\n // For \"duplicate\" resolution, we continue normally which creates a new document\n // with a different ID (the default behavior)\n\n // Send documentType info immediately after loading\n const documentType = getDocumentTypeIcon(document);\n if (documentType) {\n onProgress?.({ stage: \"loading\", progress: 10, documentType });\n } else {\n onProgress?.({ stage: \"loading\", progress: 10 });\n }\n\n if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {\n onProgress?.({\n stage: \"unsupported-document-type\",\n progress: 100,\n error: `Document type ${document.header.documentType} is not supported`,\n });\n throw new UnsupportedDocumentTypeError(document.header.documentType);\n }\n\n // ensure we have the module + can load it (throws if not found)\n await reactor.getDocumentModelModule(document.header.documentType);\n\n // Initializing stage (10-20%)\n onProgress?.({ stage: \"initializing\", progress: 10 });\n\n let duplicateId = false;\n try {\n await reactor.get(document.header.id);\n duplicateId = true;\n } catch {\n // document id not found\n }\n\n const documentId = duplicateId ? generateId() : document.header.id;\n const header = createPresignedHeader(\n documentId,\n document.header.documentType,\n );\n header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n header.meta = document.header.meta;\n header.name = name || document.header.name;\n\n // copy the document at it's initial state\n const initialDocument = {\n ...document,\n header,\n state: document.initialState,\n operations: Object.keys(document.operations).reduce((acc, key) => {\n acc[key] = [];\n return acc;\n }, {} as DocumentOperations),\n };\n\n const fileNode = await addDocument(\n driveId,\n name || document.header.name,\n document.header.documentType,\n parentFolder,\n initialDocument,\n documentId,\n document.header.meta?.preferredEditor,\n );\n\n if (!fileNode) {\n throw new Error(\"There was an error adding file\");\n }\n\n onProgress?.({ stage: \"initializing\", progress: 20 });\n\n const doc = await reactor.get(documentId);\n console.log(\"Document created, starting upload of operations\");\n // Uploading stage (20-100%)\n await uploadOperations(documentId, document.operations, queueOperations, {\n onProgress: (uploadProgress) => {\n if (\n uploadProgress.totalOperations &&\n uploadProgress.uploadedOperations !== undefined\n ) {\n const uploadPercent =\n uploadProgress.totalOperations > 0\n ? uploadProgress.uploadedOperations /\n uploadProgress.totalOperations\n : 0;\n const overallProgress = 20 + Math.round(uploadPercent * 80);\n onProgress?.({\n stage: \"uploading\",\n progress: overallProgress,\n totalOperations: uploadProgress.totalOperations,\n uploadedOperations: uploadProgress.uploadedOperations,\n });\n }\n },\n });\n\n onProgress?.({ stage: \"complete\", progress: 100, fileNode });\n\n return fileNode;\n } catch (error) {\n // Don't override unsupported-document-type status\n if (!UnsupportedDocumentTypeError.isError(error)) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n onProgress?.({\n stage: \"failed\",\n progress: 100,\n error: errorMessage,\n });\n }\n throw error;\n }\n}\n\nasync function retryAfterDiscovery(\n discoveryService: NonNullable<typeof window.ph>[\"packageDiscoveryService\"],\n documentType: string,\n file: string | File,\n driveId: string,\n name?: string,\n parentFolder?: string,\n onProgress?: FileUploadProgressCallback,\n documentTypes?: string[],\n resolveConflict?: ConflictResolution,\n): Promise<void> {\n if (!discoveryService) return;\n try {\n await discoveryService.load(documentType);\n } catch {\n onProgress?.({\n stage: \"unsupported-document-type\",\n progress: 100,\n error: `Document type ${documentType} is not supported`,\n });\n return;\n }\n await addFileWithProgress(\n file,\n driveId,\n name,\n parentFolder,\n onProgress,\n documentTypes,\n resolveConflict,\n );\n}\n\nexport async function updateFile(\n driveId: string,\n nodeId: string,\n documentType?: string,\n name?: string,\n parentFolder?: string,\n) {\n const reactor = window.ph?.reactorClient;\n if (!reactor) {\n return;\n }\n const { isAllowedToCreateDocuments } = getUserPermissions();\n\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to update files\");\n }\n const drive = await reactor.get<DocumentDriveDocument>(driveId);\n const unsafeCastAsDrive = (await queueActions(\n drive,\n baseUpdateFile({\n id: nodeId,\n name: name ?? undefined,\n parentFolder,\n documentType,\n }),\n )) as DocumentDriveDocument;\n\n const node = unsafeCastAsDrive.state.global.nodes.find(\n (node) => node.id === nodeId,\n );\n if (!node || !isFileNode(node)) {\n throw new Error(\"There was an error updating document\");\n }\n return node;\n}\n\nexport async function addFolder(\n driveId: string,\n name: string,\n parentFolder?: string,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create folders\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Get the drive document and add folder action\n const drive = await reactorClient.get<DocumentDriveDocument>(driveId);\n const folderId = generateId();\n const updatedDrive = await reactorClient.execute<DocumentDriveDocument>(\n driveId,\n \"main\",\n [\n baseAddFolder({\n id: folderId,\n name,\n parentFolder,\n }),\n ],\n );\n\n const node = updatedDrive.state.global.nodes.find(\n (node) => node.id === folderId,\n );\n if (!node || !isFolderNode(node)) {\n throw new Error(\"There was an error adding folder\");\n }\n return node;\n}\n\nexport async function deleteNode(driveId: string, nodeId: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to delete documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // delete the node in the drive document\n await reactorClient.execute(driveId, \"main\", [\n baseDeleteNode({ id: nodeId }),\n ]);\n\n // now delete the document\n await reactorClient.deleteDocument(nodeId);\n}\n\nexport async function renameNode(\n driveId: string,\n nodeId: string,\n name: string,\n): Promise<Node | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Rename the node in the drive document using updateNode action\n const drive = await reactorClient.execute<DocumentDriveDocument>(\n driveId,\n \"main\",\n [updateNode({ id: nodeId, name })],\n );\n\n const node = drive.state.global.nodes.find((n) => n.id === nodeId);\n if (!node) {\n throw new Error(\"There was an error renaming node\");\n }\n return node;\n}\n\nexport async function renameDriveNode(\n driveId: string,\n nodeId: string,\n name: string,\n): Promise<Node | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n await reactorClient.execute(driveId, \"main\", [\n updateNode({ id: nodeId, name }),\n ]);\n\n const drive = await reactorClient.get<DocumentDriveDocument>(driveId);\n return drive.state.global.nodes.find((n: Node) => n.id === nodeId);\n}\n\nexport async function moveNode(\n driveId: string,\n src: Node,\n target: Node | undefined,\n) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to move documents\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n // Get current parent folder from source node\n const sourceParent = src.parentFolder ?? driveId;\n const targetParent = target?.id ?? driveId;\n\n return await reactorClient.moveChildren(sourceParent, targetParent, [src.id]);\n}\n\nasync function _duplicateDocument(\n reactor: IReactorClient,\n document: PHDocument,\n newId = generateId(),\n) {\n const documentModule = await reactor.getDocumentModelModule(\n document.header.documentType,\n );\n\n return replayDocument(\n document.initialState,\n document.operations,\n documentModule.reducer,\n createPresignedHeader(newId, document.header.documentType),\n );\n}\n\nexport async function copyNode(\n driveId: string,\n src: Node,\n target: Node | undefined,\n) {\n const reactor = window.ph?.reactorClient;\n if (!reactor) {\n return;\n }\n const { isAllowedToCreateDocuments } = getUserPermissions();\n\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to copy documents\");\n }\n\n const drive = await reactor.get<DocumentDriveDocument>(driveId);\n\n const copyNodesInput = generateNodesCopy(\n {\n srcId: src.id,\n targetParentFolder: target?.id,\n targetName: src.name,\n },\n () => generateId(),\n drive.state.global.nodes,\n );\n\n // Pre-calculate collision-resolved names for all nodes to be copied\n const resolvedNamesMap = new Map<string, string>();\n for (const copyNodeInput of copyNodesInput) {\n const node = drive.state.global.nodes.find(\n (n) => n.id === copyNodeInput.srcId,\n );\n if (node) {\n const resolvedName = handleTargetNameCollisions({\n nodes: drive.state.global.nodes,\n srcName: copyNodeInput.targetName || node.name,\n targetParentFolder: copyNodeInput.targetParentFolder || null,\n });\n resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);\n }\n }\n\n const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {\n const node = drive.state.global.nodes.find(\n (node) => node.id === copyNodeInput.srcId,\n );\n return node !== undefined && isFileNode(node);\n });\n\n for (const fileNodeToCopy of fileNodesToCopy) {\n try {\n const document = await reactor.get(fileNodeToCopy.srcId);\n\n const duplicatedDocument = await _duplicateDocument(\n reactor,\n document,\n fileNodeToCopy.targetId,\n );\n\n // Set the header name to match the collision-resolved node name\n const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);\n if (resolvedName) {\n duplicatedDocument.header.name = resolvedName;\n }\n\n await reactor.createDocumentInDrive(\n driveId,\n duplicatedDocument,\n target?.id,\n );\n } catch (e) {\n logger.error(\n `Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`,\n );\n }\n }\n\n const copyActions = copyNodesInput.map((copyNodeInput) =>\n baseCopyNode(copyNodeInput),\n );\n return await queueActions(drive, copyActions);\n}\n","import { driveCollectionId } from \"@powerhousedao/reactor\";\nimport {\n driveCreateDocument,\n setAvailableOffline,\n setSharingType,\n type DocumentDriveDocument,\n type DriveInput,\n type SharingType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { getUserPermissions } from \"../utils/user.js\";\n\nexport async function addDrive(input: DriveInput, preferredEditor?: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to create drives\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const driveDoc = driveCreateDocument({\n global: {\n name: input.global.name || \"\",\n icon: input.global.icon ?? null,\n nodes: [],\n },\n });\n\n if (preferredEditor) {\n driveDoc.header.meta = { preferredEditor };\n }\n\n return await reactorClient.create<DocumentDriveDocument>(driveDoc);\n}\n\nexport async function addRemoteDrive(url: string, driveId?: string) {\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n\n const sync =\n window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n if (!sync) {\n throw new Error(\"Sync not initialized\");\n }\n\n // Fetch drive info from the REST endpoint to get both id and graphqlEndpoint\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to resolve drive info from ${url}`);\n }\n const driveInfo = (await response.json()) as {\n id: string;\n graphqlEndpoint: string;\n };\n\n const resolvedDriveId = driveId ?? driveInfo.id;\n const collectionId = driveCollectionId(\"main\", resolvedDriveId);\n\n const existingRemote = sync\n .list()\n .find((remote) => remote.collectionId === collectionId);\n if (existingRemote) {\n return resolvedDriveId;\n }\n\n const remoteName = crypto.randomUUID();\n\n await sync.add(remoteName, collectionId, {\n type: \"gql\",\n parameters: {\n url: driveInfo.graphqlEndpoint,\n },\n });\n\n return resolvedDriveId;\n}\n\nexport async function deleteDrive(driveId: string) {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to delete drives\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n await reactorClient.deleteDocument(driveId);\n}\n\nexport async function renameDrive(\n driveId: string,\n name: string,\n): Promise<PHDocument | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to rename drives\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n return await reactorClient.rename(driveId, name);\n}\n\nexport async function setDriveAvailableOffline(\n driveId: string,\n availableOffline: boolean,\n): Promise<PHDocument | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to change drive availability\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n return await reactorClient.execute(driveId, \"main\", [\n setAvailableOffline({ availableOffline }),\n ]);\n}\n\nexport async function setDriveSharingType(\n driveId: string,\n sharingType: SharingType,\n): Promise<PHDocument | undefined> {\n const { isAllowedToCreateDocuments } = getUserPermissions();\n if (!isAllowedToCreateDocuments) {\n throw new Error(\"User is not allowed to change drive sharing type\");\n }\n\n const reactorClient = window.ph?.reactorClient;\n if (!reactorClient) {\n throw new Error(\"ReactorClient not initialized\");\n }\n return await reactorClient.execute(driveId, \"main\", [\n setSharingType({ type: sharingType }),\n ]);\n}\n","import type { PowerhouseGlobal } from \"./types.js\";\n\nexport function getGlobal<K extends keyof PowerhouseGlobal>(\n namespace: K,\n): PowerhouseGlobal[K] | undefined {\n if (typeof window === \"undefined\") return undefined;\n return window.powerhouse?.[namespace];\n}\n\nexport function setGlobal<K extends keyof PowerhouseGlobal>(\n namespace: K,\n value: PowerhouseGlobal[K],\n): void {\n if (typeof window === \"undefined\") return;\n window.powerhouse = window.powerhouse || {};\n window.powerhouse[namespace] = value;\n}\n\nexport function clearGlobal(namespace: keyof PowerhouseGlobal): void {\n if (typeof window === \"undefined\") return;\n\n if (window.powerhouse?.[namespace]) {\n delete window.powerhouse[namespace];\n if (Object.keys(window.powerhouse).length === 0) {\n delete window.powerhouse;\n }\n }\n}\n","import type { BrowserAnalyticsStoreOptions } from \"@powerhousedao/analytics-engine-browser\";\nimport { BrowserAnalyticsStore } from \"@powerhousedao/analytics-engine-browser\";\nimport type { IAnalyticsStore } from \"@powerhousedao/analytics-engine-core\";\nimport { AnalyticsQueryEngine } from \"@powerhousedao/analytics-engine-core\";\nimport {\n QueryClient,\n QueryClientProvider,\n useMutation,\n useQuery,\n useQueryClient,\n useSuspenseQuery,\n} from \"@tanstack/react-query\";\nimport { childLogger } from \"document-model\";\nimport type { PropsWithChildren } from \"react\";\nimport { useEffect } from \"react\";\nimport { getGlobal } from \"../global/core.js\";\n\nconst logger = childLogger([\"reactor-browser\", \"analytics\", \"provider\"]);\n\nconst defaultQueryClient = new QueryClient();\n\ntype CreateStoreOptions = BrowserAnalyticsStoreOptions;\n\nexport const analyticsOptionsKey = [\"analytics\", \"options\"] as const;\nexport const analyticsStoreKey = [\"analytics\", \"store\"] as const;\nexport const analyticsEngineKey = [\"analytics\", \"store\"] as const;\n\nexport async function createAnalyticsStore(options: CreateStoreOptions) {\n const store = new BrowserAnalyticsStore(options);\n await store.init();\n\n const engine = new AnalyticsQueryEngine(store);\n return {\n store,\n engine,\n options,\n };\n}\n\nexport async function getAnalyticsStore(): Promise<IAnalyticsStore | null> {\n const globalAnalytics = await getGlobal(\"analytics\");\n\n return globalAnalytics?.store ?? null;\n}\n\nexport function useAnalyticsStoreOptions() {\n return useQuery<CreateStoreOptions | undefined>({\n queryKey: analyticsOptionsKey,\n }).data;\n}\n\nexport function useCreateAnalyticsStore(options?: CreateStoreOptions) {\n const queryClient = useQueryClient();\n useEffect(() => {\n queryClient.setQueryDefaults(analyticsOptionsKey, {\n queryFn: () => options,\n staleTime: Infinity,\n gcTime: Infinity,\n });\n }, [queryClient, options]);\n\n return useMutation({\n mutationFn: async () => {\n const store = getAnalyticsStore();\n queryClient.setQueryDefaults(analyticsStoreKey, {\n queryFn: () => store,\n staleTime: Infinity,\n gcTime: Infinity,\n });\n return store;\n },\n });\n}\n\nexport function useAnalyticsStoreQuery(options?: CreateStoreOptions) {\n return useSuspenseQuery({\n queryKey: [analyticsStoreKey, options],\n queryFn: () => getAnalyticsStore(),\n retry: true,\n });\n}\n\nexport function useAnalyticsStore(options?: CreateStoreOptions) {\n const store = useAnalyticsStoreQuery(options);\n return store.data;\n}\n\nexport function useAnalyticsStoreAsync(options?: CreateStoreOptions) {\n return useQuery({\n queryKey: [analyticsStoreKey, options],\n queryFn: () => getAnalyticsStore(),\n retry: true,\n throwOnError: false,\n });\n}\n\ninterface BaseAnalyticsProviderProps extends PropsWithChildren {\n /**\n * Custom QueryClient instance\n * @default undefined\n */\n queryClient?: QueryClient;\n}\n\ntype CreateAnalyticsStoreProps =\n | {\n options?: CreateStoreOptions;\n }\n | {\n databaseName?: string;\n };\n\ntype AnalyticsProviderProps = BaseAnalyticsProviderProps &\n CreateAnalyticsStoreProps;\n\nfunction CreateAnalyticsStore() {\n const { mutate } = useCreateAnalyticsStore();\n\n useEffect(() => {\n mutate();\n }, []);\n\n return null;\n}\n\nexport function AnalyticsProvider({\n children,\n queryClient = defaultQueryClient,\n ...props\n}: AnalyticsProviderProps) {\n return (\n <QueryClientProvider client={queryClient}>\n <CreateAnalyticsStore />\n {children}\n </QueryClientProvider>\n );\n}\n\nexport function useAnalyticsEngine(): AnalyticsQueryEngine | undefined {\n return useSuspenseQuery({\n queryKey: analyticsEngineKey,\n queryFn: async () => {\n const globalAnalytics = getGlobal(\"analytics\");\n if (!globalAnalytics) {\n throw new Error(\"No analytics store available\");\n }\n return (await globalAnalytics).engine;\n },\n retry: false,\n }).data;\n}\n\nexport function useAnalyticsEngineAsync() {\n return useQuery({\n queryKey: analyticsEngineKey,\n queryFn: async () => {\n const globalAnalytics = getGlobal(\"analytics\");\n if (!globalAnalytics) {\n throw new Error(\"No analytics store available\");\n }\n return (await globalAnalytics).engine;\n },\n retry: false,\n });\n}\n","import type {\n AnalyticsQuery,\n AnalyticsQueryEngine,\n AnalyticsSeries,\n AnalyticsSeriesInput,\n AnalyticsSeriesQuery,\n GroupedPeriodResults,\n IAnalyticsStore,\n} from \"@powerhousedao/analytics-engine-core\";\nimport { AnalyticsPath } from \"@powerhousedao/analytics-engine-core\";\nimport type {\n UseMutationOptions,\n UseQueryOptions,\n UseQueryResult,\n} from \"@tanstack/react-query\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect } from \"react\";\nimport {\n getAnalyticsStore,\n useAnalyticsEngineAsync,\n useAnalyticsStoreAsync,\n useAnalyticsStoreOptions,\n} from \"../context.js\";\n\nfunction useAnalyticsQueryWrapper<TQueryFnData = unknown, TData = TQueryFnData>(\n options: Omit<UseQueryOptions<TQueryFnData, Error, TData>, \"queryFn\"> & {\n queryFn: (analytics: {\n store: IAnalyticsStore;\n engine: AnalyticsQueryEngine;\n }) => Promise<TQueryFnData> | TQueryFnData;\n },\n) {\n const { queryFn, ...queryOptions } = options;\n const { data: store } = useAnalyticsStoreAsync();\n const { data: engine } = useAnalyticsEngineAsync();\n const enabled =\n \"enabled\" in queryOptions ? queryOptions.enabled : !!store && !!engine;\n\n return useQuery({\n ...queryOptions,\n enabled,\n queryFn: async () => {\n if (!store || !engine) {\n throw new Error(\n \"No analytics store available. Use within an AnalyticsProvider.\",\n );\n }\n return await queryFn({ store, engine });\n },\n });\n}\n\nfunction useAnalyticsMutationWrapper<TVariables, TData>(\n options: Omit<UseMutationOptions<TData, Error, TVariables>, \"mutationFn\"> & {\n mutationFn: (\n variables: TVariables,\n context: {\n store: IAnalyticsStore;\n },\n ) => Promise<TData> | TData;\n },\n) {\n const { mutationFn, ...mutationOptions } = options;\n const storeOptions = useAnalyticsStoreOptions();\n\n return useMutation({\n ...mutationOptions,\n mutationFn: async (value: TVariables) => {\n let store: IAnalyticsStore | null = null;\n try {\n store = await getAnalyticsStore();\n } catch (e) {\n console.error(e);\n }\n\n if (!store) {\n throw new Error(\n \"No analytics store available. Use within an AnalyticsProvider.\",\n );\n }\n return await mutationFn(value, { store });\n },\n });\n}\n\nexport type UseAnalyticsQueryOptions<TData = GroupedPeriodResults> = Omit<\n UseQueryOptions<GroupedPeriodResults, Error, TData>,\n \"queryKey\" | \"queryFn\"\n> & {\n sources?: AnalyticsPath[];\n};\n\nexport type UseAnalyticsQueryResult<TData = GroupedPeriodResults> =\n UseQueryResult<TData>;\n\nconst DEBOUNCE_INTERVAL = 200;\n\nexport function useAnalyticsQuery<TData = GroupedPeriodResults>(\n query: AnalyticsQuery,\n options?: UseAnalyticsQueryOptions<TData>,\n): UseAnalyticsQueryResult<TData> {\n const { data: store } = useAnalyticsStoreAsync();\n const queryClient = useQueryClient();\n const sources = options?.sources ?? [];\n\n const result = useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"query\", query],\n queryFn: ({ engine }) => engine.execute(query),\n ...options,\n });\n\n useEffect(() => {\n if (!sources.length || !store) {\n return;\n }\n\n const subscriptions = new Array<() => void>();\n // Debounce invalidateQueries so it's not called too frequently\n let invalidateTimeout: ReturnType<typeof setTimeout> | null = null;\n const debouncedInvalidate = () => {\n if (invalidateTimeout) clearTimeout(invalidateTimeout);\n invalidateTimeout = setTimeout(() => {\n queryClient\n .invalidateQueries({\n queryKey: [\"analytics\", \"query\", query],\n })\n .catch((e) => {\n console.error(e);\n });\n }, DEBOUNCE_INTERVAL);\n };\n\n sources.forEach((path) => {\n const unsub = store.subscribeToSource(path, debouncedInvalidate);\n subscriptions.push(unsub);\n });\n\n // Unsubscribes from store when component unmounts or dependencies change\n return () => {\n subscriptions.forEach((unsub) => unsub());\n };\n }, [query, store, sources]);\n\n return result;\n}\n\nexport type UseAnalyticsSeriesOptions = Omit<\n UseQueryOptions<AnalyticsSeries[], Error, AnalyticsSeries[]>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useAnalyticsSeries(\n query: AnalyticsSeriesQuery,\n options?: UseAnalyticsSeriesOptions,\n) {\n return useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"series\", query],\n queryFn: ({ store }) => store.getMatchingSeries(query),\n ...options,\n });\n}\n\nexport type UseAddSeriesValueOptions = Omit<\n UseMutationOptions<void, Error, AnalyticsSeriesInput>,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useAddSeriesValue(options?: UseAddSeriesValueOptions) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"addSeries\"],\n mutationFn: async (value, { store }) => {\n return await store.addSeriesValue(value);\n },\n ...options,\n });\n}\n\nexport type UseClearSeriesBySourceOptions = Omit<\n UseMutationOptions<\n number,\n Error,\n { source: AnalyticsPath; cleanUpDimensions?: boolean }\n >,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useClearSeriesBySource(\n options?: UseClearSeriesBySourceOptions,\n) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"clearSeries\"],\n mutationFn: async ({ source, cleanUpDimensions }, { store }) => {\n return store.clearSeriesBySource(source, cleanUpDimensions);\n },\n ...options,\n });\n}\n\nexport type UseClearEmptyAnalyticsDimensionsOptions = Omit<\n UseMutationOptions<number>,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useClearEmptyAnalyticsDimensions(\n options?: UseClearEmptyAnalyticsDimensionsOptions,\n) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"clearEmptyDimensions\"],\n mutationFn: async (_, { store }) => {\n return store.clearEmptyAnalyticsDimensions();\n },\n ...options,\n });\n}\n\nexport type UseAddSeriesValuesOptions = Omit<\n UseMutationOptions<void, Error, AnalyticsSeriesInput[]>,\n \"mutationKey\" | \"mutationFn\"\n>;\n\nexport function useAddSeriesValues(options?: UseAddSeriesValuesOptions) {\n return useAnalyticsMutationWrapper({\n mutationKey: [\"analytics\", \"addSeriesValues\"],\n mutationFn: async (values, { store }) => {\n return store.addSeriesValues(values);\n },\n ...options,\n });\n}\n\nexport type UseGetDimensionsOptions<TData> = Omit<\n UseQueryOptions<any, Error, TData>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useGetDimensions<TData = any>(\n options?: UseGetDimensionsOptions<TData>,\n) {\n return useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"dimensions\"],\n queryFn: ({ store }) => store.getDimensions(),\n ...options,\n });\n}\n\nexport type UseMatchingSeriesOptions = Omit<\n UseQueryOptions<AnalyticsSeries[], Error, AnalyticsSeries[]>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useMatchingSeries(\n query: AnalyticsSeriesQuery,\n options?: UseMatchingSeriesOptions,\n) {\n const result = useAnalyticsQueryWrapper({\n queryKey: [\"analytics\", \"matchingSeries\", query],\n queryFn: ({ store }) => store.getMatchingSeries(query),\n ...options,\n });\n\n return result;\n}\n\nexport type UseQuerySourcesOptions = Omit<\n UseQueryOptions<AnalyticsPath[] | undefined>,\n \"queryKey\" | \"queryFn\"\n>;\n\nexport function useQuerySources(\n query: AnalyticsSeriesQuery,\n options?: UseQuerySourcesOptions,\n) {\n const { data: matchingSeries } = useMatchingSeries(query);\n\n return useQuery({\n queryKey: [\"analytics\", \"sources\", query],\n queryFn: () => {\n if (!matchingSeries?.length) {\n return [];\n }\n const uniqueSources = [\n ...new Set(matchingSeries.map((s) => s.source.toString())),\n ];\n return uniqueSources.map((source) => AnalyticsPath.fromString(source));\n },\n enabled: !!matchingSeries,\n ...options,\n });\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 logger.error,\n );\n }\n return [document, dispatch] as const;\n}\n","import {\n DocumentChangeType,\n type DocumentChangeEvent,\n type IReactorClient,\n} from \"@powerhousedao/reactor\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport type {\n FulfilledPromise,\n IDocumentCache,\n PromiseState,\n PromiseWithState,\n RejectedPromise,\n} from \"./types/documents.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 * Document cache implementation that uses the new ReactorClient API.\n *\n * This cache subscribes to document change events via IReactorClient.subscribe()\n * and automatically updates the cache when documents are created, updated, or deleted.\n */\nexport class DocumentCache implements IDocumentCache {\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 private unsubscribe: (() => void) | null = null;\n\n constructor(private client: IReactorClient) {\n this.unsubscribe = client.subscribe({}, (event: DocumentChangeEvent) => {\n this.handleDocumentChange(event);\n });\n }\n\n private handleDocumentChange(event: DocumentChangeEvent): void {\n if (event.type === DocumentChangeType.Deleted) {\n const documentId = event.context?.childId;\n if (documentId) {\n this.handleDocumentDeleted(documentId);\n }\n } else if (event.type === DocumentChangeType.Updated) {\n for (const doc of event.documents) {\n this.handleDocumentUpdated(doc.header.id).catch(console.warn);\n }\n }\n }\n\n private handleDocumentDeleted(documentId: string): void {\n const listeners = this.listeners.get(documentId);\n this.documents.delete(documentId);\n this.invalidateBatchesContaining(documentId);\n if (listeners) {\n listeners.forEach((listener) => listener());\n }\n this.listeners.delete(documentId);\n }\n\n private async handleDocumentUpdated(documentId: string): Promise<void> {\n if (this.documents.has(documentId)) {\n await this.get(documentId, true);\n const listeners = this.listeners.get(documentId);\n if (listeners) {\n listeners.forEach((listener) => listener());\n }\n }\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) {\n if (currentData.status === \"pending\") {\n return currentData;\n }\n if (!refetch) {\n return currentData;\n }\n }\n\n const documentPromise = this.client.get(id);\n this.documents.set(id, addPromiseState(documentPromise));\n return documentPromise;\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 = Promise.all(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 allFulfilled = states.every((s) => s.status === \"fulfilled\");\n\n if (allFulfilled) {\n const values = states.map(\n (s) => (s as { status: \"fulfilled\"; value: PHDocument }).value,\n );\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 = Promise.all(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 /**\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 }\n}\n","import type {\n PHGlobal,\n PHGlobalKey,\n SetEvent,\n} from \"@powerhousedao/reactor-browser\";\nimport { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\n\n// guard condition for server side rendering\nconst isServer = typeof window === \"undefined\";\n\nexport function makePHEventFunctions<TKey extends PHGlobalKey>(key: TKey) {\n const setEventName = `ph:set${capitalCase(key)}` as const;\n const updateEventName = `ph:${key}Updated` as const;\n\n function setValue(value: PHGlobal[TKey] | undefined) {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(setEventName, {\n detail: { [key]: value },\n });\n window.dispatchEvent(event);\n }\n\n function dispatchUpdatedEvent() {\n if (isServer) {\n return;\n }\n const event = new CustomEvent(updateEventName);\n window.dispatchEvent(event);\n }\n\n function handleSetValueEvent(event: SetEvent<TKey>) {\n if (isServer) {\n return;\n }\n const value = event.detail[key];\n if (!window.ph) {\n window.ph = {};\n }\n window.ph[key] = value;\n dispatchUpdatedEvent();\n }\n\n function addEventHandler() {\n if (isServer) {\n return;\n }\n window.addEventListener(setEventName, handleSetValueEvent as EventListener);\n }\n\n function subscribeToValue(onStoreChange: () => void) {\n if (isServer) return () => {};\n window.addEventListener(updateEventName, onStoreChange);\n return () => {\n window.removeEventListener(updateEventName, onStoreChange);\n };\n }\n\n function getSnapshot() {\n if (isServer) {\n return undefined;\n }\n if (!window.ph) {\n console.warn(\n `ph global store is not initialized. Did you call set${capitalCase(key)}?`,\n );\n return undefined;\n }\n return window.ph[key];\n }\n\n function getServerSnapshot() {\n return undefined;\n }\n\n function useValue() {\n return useSyncExternalStore(\n subscribeToValue,\n getSnapshot,\n getServerSnapshot,\n );\n }\n\n return {\n useValue,\n setValue,\n addEventHandler,\n };\n}\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { use, useCallback, useSyncExternalStore } from \"react\";\nimport { readPromiseState } from \"../document-cache.js\";\nimport type { IDocumentCache } 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 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 */\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 } as const;\n }\n\n const promise = documentCache.get(id);\n const state = getDocumentQueryState(promise);\n\n return { ...state, reload: () => documentCache.get(id, true) } 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","import type { GroupedPeriodResults } from \"@powerhousedao/analytics-engine-core\";\nimport {\n AnalyticsGranularity,\n AnalyticsPath,\n} from \"@powerhousedao/analytics-engine-core\";\nimport { DateTime } from \"luxon\";\nimport type { UseAnalyticsQueryResult } from \"./analytics-query.js\";\nimport { useAnalyticsQuery } from \"./analytics-query.js\";\n\nconst getBarSize = (value: number) => {\n if (value <= 0) return 0;\n if (value > 0 && value <= 50) return 1;\n if (value > 50 && value <= 100) return 2;\n if (value > 100 && value <= 250) return 3;\n return 4;\n};\n\n// Define types for our timeline items\ntype BarItem = {\n id: string;\n type: \"bar\";\n addSize: 0 | 1 | 2 | 3 | 4;\n delSize: 0 | 1 | 2 | 3 | 4;\n additions: number;\n deletions: number;\n timestampUtcMs: string;\n startDate: Date;\n endDate: Date;\n revision?: number;\n};\n\ntype DividerItem = {\n id: string;\n type: \"divider\";\n revision?: number;\n startDate?: Date;\n endDate?: Date;\n};\n\ntype TimelineItem = BarItem | DividerItem;\n\nfunction addItemsDividers(items: BarItem[]): TimelineItem[] {\n if (!items.length) return [];\n\n const result: TimelineItem[] = [];\n items.forEach((item, index) => {\n result.push(item);\n\n // Check if there's a next item and if they're not in consecutive hours\n if (index < items.length - 1) {\n const currentDate = new Date(item.startDate);\n const nextDate = new Date(items[index + 1].startDate);\n\n const currentHour = currentDate.getHours();\n const nextHour = nextDate.getHours();\n\n // Get day parts (without time) for comparison\n const currentDay = currentDate.toDateString();\n const nextDay = nextDate.toDateString();\n\n // If different days or non-consecutive hours on the same day\n if (\n currentDay !== nextDay ||\n (currentDay === nextDay && Math.abs(nextHour - currentHour) > 1)\n ) {\n result.push({\n id: `divider-${item.id}-${items[index + 1].id}`,\n type: \"divider\" as const,\n revision: 0,\n });\n }\n }\n });\n\n return result;\n}\n\nfunction metricsToItems(metrics: GroupedPeriodResults): TimelineItem[] {\n if (!metrics) return [];\n\n const items = metrics\n .sort((a, b) => {\n const aDate = new Date(a.start as unknown as Date);\n const bDate = new Date(b.start as unknown as Date);\n return aDate.getTime() - bDate.getTime();\n })\n .filter((result) => {\n return result.rows.every((row) => row.value > 0);\n })\n .map((result) => {\n const { additions, deletions } = result.rows.reduce(\n (acc, row) => {\n if (\n (row.dimensions.changes.path as unknown as string) ===\n \"ph/diff/changes/add\"\n ) {\n acc.additions += row.value;\n } else if (\n (row.dimensions.changes.path as unknown as string) ===\n \"ph/diff/changes/remove\"\n ) {\n acc.deletions += row.value;\n }\n return acc;\n },\n { additions: 0, deletions: 0 },\n );\n\n const startDate = new Date(result.start as unknown as Date);\n\n return {\n id: startDate.toISOString(),\n type: \"bar\" as const,\n addSize: getBarSize(additions),\n delSize: getBarSize(deletions),\n additions,\n deletions,\n timestampUtcMs: startDate.toISOString(),\n startDate: startDate,\n endDate: new Date(result.end as unknown as Date),\n revision: 0,\n } as const;\n });\n\n return addItemsDividers(items);\n}\n\nexport type UseTimelineItemsResult = UseAnalyticsQueryResult<TimelineItem[]>;\n\nexport const useTimelineItems = (\n documentId?: string,\n startTimestamp?: string,\n driveId?: string,\n): UseTimelineItemsResult => {\n const start = startTimestamp\n ? DateTime.fromISO(startTimestamp)\n : DateTime.now().startOf(\"day\");\n\n return useAnalyticsQuery<TimelineItem[]>(\n {\n start,\n end: DateTime.now().endOf(\"day\"),\n granularity: AnalyticsGranularity.Hourly,\n metrics: [\"Count\"],\n select: {\n changes: [AnalyticsPath.fromString(`ph/diff/changes`)],\n document: [AnalyticsPath.fromString(`ph/diff/document/${documentId}`)],\n },\n lod: {\n changes: 4,\n },\n },\n {\n sources: [AnalyticsPath.fromString(`ph/diff/${driveId}/${documentId}`)],\n select: metricsToItems,\n },\n );\n};\n","import { useDocumentById } from \"../../hooks/document-by-id.js\";\nimport { useTimelineItems } from \"./timeline-items.js\";\n\nexport function useDocumentTimeline(documentId?: string) {\n const [document] = useDocumentById(documentId);\n\n const id = document?.header.id;\n const createdAt = document?.header.createdAtUtcIso;\n const timelineItems = useTimelineItems(id, createdAt);\n\n return timelineItems.data || [];\n}\n","export const DEFAULT_DRIVE_EDITOR_ID = \"powerhouse/generic-drive-explorer\";\nexport const COMMON_PACKAGE_ID = \"powerhouse/common\";\n","import type {\n DocumentModelModule,\n DocumentModelPHState,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"document-model\";\n\nexport const baseDocumentModelsMap: Record<\n string,\n DocumentModelModule<DocumentModelPHState>\n> = {\n DocumentModel:\n documentModelDocumentModelModule as DocumentModelModule<DocumentModelPHState>,\n};\n\nexport const baseDocumentModels = Object.values(baseDocumentModelsMap);\n","import type { GraphQLClient, RequestOptions } from \"graphql-request\";\nimport { gql } from \"graphql-tag\";\nexport type Maybe<T> = T | null | undefined;\nexport type InputMaybe<T> = T | null | undefined;\nexport type Exact<T extends { [key: string]: unknown }> = {\n [K in keyof T]: T[K];\n};\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & {\n [SubKey in K]?: Maybe<T[SubKey]>;\n};\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {\n [SubKey in K]: Maybe<T[SubKey]>;\n};\nexport type MakeEmpty<\n T extends { [key: string]: unknown },\n K extends keyof T,\n> = { [_ in K]?: never };\nexport type Incremental<T> =\n | T\n | {\n [P in keyof T]?: P extends \" $fragmentName\" | \"__typename\" ? T[P] : never;\n };\ntype GraphQLClientRequestHeaders = RequestOptions[\"requestHeaders\"];\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n ID: { input: string; output: string };\n String: { input: string; output: string };\n Boolean: { input: boolean; output: boolean };\n Int: { input: number; output: number };\n Float: { input: number; output: number };\n DateTime: { input: string | Date; output: string | Date };\n JSONObject: { input: NonNullable<unknown>; output: NonNullable<unknown> };\n};\n\nexport type Action = {\n readonly attachments?: Maybe<ReadonlyArray<Attachment>>;\n readonly context?: Maybe<ActionContext>;\n readonly id: Scalars[\"String\"][\"output\"];\n readonly input: Scalars[\"JSONObject\"][\"output\"];\n readonly scope: Scalars[\"String\"][\"output\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"output\"];\n readonly type: Scalars[\"String\"][\"output\"];\n};\n\nexport type ActionContext = {\n readonly signer?: Maybe<ReactorSigner>;\n};\n\nexport type ActionContextInput = {\n readonly signer?: InputMaybe<ReactorSignerInput>;\n};\n\nexport type ActionInput = {\n readonly attachments?: InputMaybe<ReadonlyArray<AttachmentInput>>;\n readonly context?: InputMaybe<ActionContextInput>;\n readonly id: Scalars[\"String\"][\"input\"];\n readonly input: Scalars[\"JSONObject\"][\"input\"];\n readonly scope: Scalars[\"String\"][\"input\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"input\"];\n readonly type: Scalars[\"String\"][\"input\"];\n};\n\nexport type Attachment = {\n readonly data: Scalars[\"String\"][\"output\"];\n readonly extension?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly fileName?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hash: Scalars[\"String\"][\"output\"];\n readonly mimeType: Scalars[\"String\"][\"output\"];\n};\n\nexport type AttachmentInput = {\n readonly data: Scalars[\"String\"][\"input\"];\n readonly extension?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly fileName?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly hash: Scalars[\"String\"][\"input\"];\n readonly mimeType: Scalars[\"String\"][\"input\"];\n};\n\nexport type ChannelMeta = {\n readonly id: Scalars[\"String\"][\"output\"];\n};\n\nexport type ChannelMetaInput = {\n readonly id: Scalars[\"String\"][\"input\"];\n};\n\nexport type DeadLetterInfo = {\n readonly branch: Scalars[\"String\"][\"output\"];\n readonly documentId: Scalars[\"String\"][\"output\"];\n readonly error: Scalars[\"String\"][\"output\"];\n readonly jobId: Scalars[\"String\"][\"output\"];\n readonly operationCount: Scalars[\"Int\"][\"output\"];\n readonly scopes: ReadonlyArray<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type DocumentChangeContext = {\n readonly childId?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly parentId?: Maybe<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type DocumentChangeEvent = {\n readonly context?: Maybe<DocumentChangeContext>;\n readonly documents: ReadonlyArray<PhDocument>;\n readonly type: DocumentChangeType;\n};\n\nexport enum DocumentChangeType {\n ChildAdded = \"CHILD_ADDED\",\n ChildRemoved = \"CHILD_REMOVED\",\n Created = \"CREATED\",\n Deleted = \"DELETED\",\n ParentAdded = \"PARENT_ADDED\",\n ParentRemoved = \"PARENT_REMOVED\",\n Updated = \"UPDATED\",\n}\n\nexport type DocumentModelGlobalState = {\n readonly id: Scalars[\"String\"][\"output\"];\n readonly name: Scalars[\"String\"][\"output\"];\n readonly namespace?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly specification: Scalars[\"JSONObject\"][\"output\"];\n readonly version?: Maybe<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type DocumentModelResultPage = {\n readonly cursor?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hasNextPage: Scalars[\"Boolean\"][\"output\"];\n readonly hasPreviousPage: Scalars[\"Boolean\"][\"output\"];\n readonly items: ReadonlyArray<DocumentModelGlobalState>;\n readonly totalCount: Scalars[\"Int\"][\"output\"];\n};\n\nexport type DocumentOperationsFilterInput = {\n readonly actionTypes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly scopes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly sinceRevision?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n readonly timestampFrom?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly timestampTo?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type DocumentWithChildren = {\n readonly childIds: ReadonlyArray<Scalars[\"String\"][\"output\"]>;\n readonly document: PhDocument;\n};\n\nexport type JobChangeEvent = {\n readonly error?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly jobId: Scalars[\"String\"][\"output\"];\n readonly result: Scalars[\"JSONObject\"][\"output\"];\n readonly status: Scalars[\"String\"][\"output\"];\n};\n\nexport type JobInfo = {\n readonly completedAt?: Maybe<Scalars[\"DateTime\"][\"output\"]>;\n readonly createdAt: Scalars[\"DateTime\"][\"output\"];\n readonly error?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly id: Scalars[\"String\"][\"output\"];\n readonly result: Scalars[\"JSONObject\"][\"output\"];\n readonly status: Scalars[\"String\"][\"output\"];\n};\n\nexport type MoveChildrenResult = {\n readonly source: PhDocument;\n readonly target: PhDocument;\n};\n\nexport type Mutation = {\n readonly addChildren: PhDocument;\n readonly createDocument: PhDocument;\n readonly createEmptyDocument: PhDocument;\n readonly deleteDocument: Scalars[\"Boolean\"][\"output\"];\n readonly deleteDocuments: Scalars[\"Boolean\"][\"output\"];\n readonly moveChildren: MoveChildrenResult;\n readonly mutateDocument: PhDocument;\n readonly mutateDocumentAsync: Scalars[\"String\"][\"output\"];\n readonly pushSyncEnvelopes: Scalars[\"Boolean\"][\"output\"];\n readonly removeChildren: PhDocument;\n readonly renameDocument: PhDocument;\n readonly touchChannel: Scalars[\"Boolean\"][\"output\"];\n};\n\nexport type MutationAddChildrenArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n parentIdentifier: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationCreateDocumentArgs = {\n document: Scalars[\"JSONObject\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type MutationCreateEmptyDocumentArgs = {\n documentType: Scalars[\"String\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type MutationDeleteDocumentArgs = {\n identifier: Scalars[\"String\"][\"input\"];\n propagate?: InputMaybe<PropagationMode>;\n};\n\nexport type MutationDeleteDocumentsArgs = {\n identifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n propagate?: InputMaybe<PropagationMode>;\n};\n\nexport type MutationMoveChildrenArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n sourceParentIdentifier: Scalars[\"String\"][\"input\"];\n targetParentIdentifier: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationMutateDocumentArgs = {\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n documentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type MutationMutateDocumentAsyncArgs = {\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n documentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type MutationPushSyncEnvelopesArgs = {\n envelopes: ReadonlyArray<SyncEnvelopeInput>;\n};\n\nexport type MutationRemoveChildrenArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n parentIdentifier: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationRenameDocumentArgs = {\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n documentIdentifier: Scalars[\"String\"][\"input\"];\n name: Scalars[\"String\"][\"input\"];\n};\n\nexport type MutationTouchChannelArgs = {\n input: TouchChannelInput;\n};\n\nexport type OperationContext = {\n readonly branch: Scalars[\"String\"][\"output\"];\n readonly documentId: Scalars[\"String\"][\"output\"];\n readonly documentType: Scalars[\"String\"][\"output\"];\n readonly ordinal: Scalars[\"Int\"][\"output\"];\n readonly scope: Scalars[\"String\"][\"output\"];\n};\n\nexport type OperationContextInput = {\n readonly branch: Scalars[\"String\"][\"input\"];\n readonly documentId: Scalars[\"String\"][\"input\"];\n readonly documentType: Scalars[\"String\"][\"input\"];\n readonly ordinal: Scalars[\"Int\"][\"input\"];\n readonly scope: Scalars[\"String\"][\"input\"];\n};\n\nexport type OperationInput = {\n readonly action: ActionInput;\n readonly error?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly hash: Scalars[\"String\"][\"input\"];\n readonly id?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly index: Scalars[\"Int\"][\"input\"];\n readonly skip: Scalars[\"Int\"][\"input\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"input\"];\n};\n\nexport type OperationWithContext = {\n readonly context: OperationContext;\n readonly operation: ReactorOperation;\n};\n\nexport type OperationWithContextInput = {\n readonly context: OperationContextInput;\n readonly operation: OperationInput;\n};\n\nexport type OperationsFilterInput = {\n readonly actionTypes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly documentId: Scalars[\"String\"][\"input\"];\n readonly scopes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly sinceRevision?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n readonly timestampFrom?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly timestampTo?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type PhDocument = {\n readonly createdAtUtcIso: Scalars[\"DateTime\"][\"output\"];\n readonly documentType: Scalars[\"String\"][\"output\"];\n readonly id: Scalars[\"String\"][\"output\"];\n readonly lastModifiedAtUtcIso: Scalars[\"DateTime\"][\"output\"];\n readonly name: Scalars[\"String\"][\"output\"];\n readonly operations?: Maybe<ReactorOperationResultPage>;\n readonly revisionsList: ReadonlyArray<Revision>;\n readonly slug?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly state: Scalars[\"JSONObject\"][\"output\"];\n};\n\nexport type PhDocumentOperationsArgs = {\n filter?: InputMaybe<DocumentOperationsFilterInput>;\n paging?: InputMaybe<PagingInput>;\n};\n\nexport type PhDocumentResultPage = {\n readonly cursor?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hasNextPage: Scalars[\"Boolean\"][\"output\"];\n readonly hasPreviousPage: Scalars[\"Boolean\"][\"output\"];\n readonly items: ReadonlyArray<PhDocument>;\n readonly totalCount: Scalars[\"Int\"][\"output\"];\n};\n\nexport type PagingInput = {\n readonly cursor?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly limit?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n readonly offset?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n};\n\nexport type PollSyncEnvelopesResult = {\n readonly ackOrdinal: Scalars[\"Int\"][\"output\"];\n readonly deadLetters: ReadonlyArray<DeadLetterInfo>;\n readonly envelopes: ReadonlyArray<SyncEnvelope>;\n};\n\nexport enum PropagationMode {\n Cascade = \"CASCADE\",\n Orphan = \"ORPHAN\",\n}\n\nexport type Query = {\n readonly document?: Maybe<DocumentWithChildren>;\n readonly documentChildren: PhDocumentResultPage;\n readonly documentModels: DocumentModelResultPage;\n readonly documentOperations: ReactorOperationResultPage;\n readonly documentParents: PhDocumentResultPage;\n readonly findDocuments: PhDocumentResultPage;\n readonly jobStatus?: Maybe<JobInfo>;\n readonly pollSyncEnvelopes: PollSyncEnvelopesResult;\n};\n\nexport type QueryDocumentArgs = {\n identifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryDocumentChildrenArgs = {\n paging?: InputMaybe<PagingInput>;\n parentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryDocumentModelsArgs = {\n namespace?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n paging?: InputMaybe<PagingInput>;\n};\n\nexport type QueryDocumentOperationsArgs = {\n filter: OperationsFilterInput;\n paging?: InputMaybe<PagingInput>;\n};\n\nexport type QueryDocumentParentsArgs = {\n childIdentifier: Scalars[\"String\"][\"input\"];\n paging?: InputMaybe<PagingInput>;\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryFindDocumentsArgs = {\n paging?: InputMaybe<PagingInput>;\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type QueryJobStatusArgs = {\n jobId: Scalars[\"String\"][\"input\"];\n};\n\nexport type QueryPollSyncEnvelopesArgs = {\n channelId: Scalars[\"String\"][\"input\"];\n outboxAck: Scalars[\"Int\"][\"input\"];\n outboxLatest: Scalars[\"Int\"][\"input\"];\n};\n\nexport type ReactorOperation = {\n readonly action: Action;\n readonly error?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hash: Scalars[\"String\"][\"output\"];\n readonly id?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly index: Scalars[\"Int\"][\"output\"];\n readonly skip: Scalars[\"Int\"][\"output\"];\n readonly timestampUtcMs: Scalars[\"String\"][\"output\"];\n};\n\nexport type ReactorOperationResultPage = {\n readonly cursor?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly hasNextPage: Scalars[\"Boolean\"][\"output\"];\n readonly hasPreviousPage: Scalars[\"Boolean\"][\"output\"];\n readonly items: ReadonlyArray<ReactorOperation>;\n readonly totalCount: Scalars[\"Int\"][\"output\"];\n};\n\nexport type ReactorSigner = {\n readonly app?: Maybe<ReactorSignerApp>;\n readonly signatures: ReadonlyArray<Scalars[\"String\"][\"output\"]>;\n readonly user?: Maybe<ReactorSignerUser>;\n};\n\nexport type ReactorSignerApp = {\n readonly key: Scalars[\"String\"][\"output\"];\n readonly name: Scalars[\"String\"][\"output\"];\n};\n\nexport type ReactorSignerAppInput = {\n readonly key: Scalars[\"String\"][\"input\"];\n readonly name: Scalars[\"String\"][\"input\"];\n};\n\nexport type ReactorSignerInput = {\n readonly app?: InputMaybe<ReactorSignerAppInput>;\n readonly signatures: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n readonly user?: InputMaybe<ReactorSignerUserInput>;\n};\n\nexport type ReactorSignerUser = {\n readonly address: Scalars[\"String\"][\"output\"];\n readonly chainId: Scalars[\"Int\"][\"output\"];\n readonly networkId: Scalars[\"String\"][\"output\"];\n};\n\nexport type ReactorSignerUserInput = {\n readonly address: Scalars[\"String\"][\"input\"];\n readonly chainId: Scalars[\"Int\"][\"input\"];\n readonly networkId: Scalars[\"String\"][\"input\"];\n};\n\nexport type RemoteCursor = {\n readonly cursorOrdinal: Scalars[\"Int\"][\"output\"];\n readonly lastSyncedAtUtcMs?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly remoteName: Scalars[\"String\"][\"output\"];\n};\n\nexport type RemoteCursorInput = {\n readonly cursorOrdinal: Scalars[\"Int\"][\"input\"];\n readonly lastSyncedAtUtcMs?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly remoteName: Scalars[\"String\"][\"input\"];\n};\n\nexport type RemoteFilterInput = {\n readonly branch: Scalars[\"String\"][\"input\"];\n readonly documentId: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n readonly scope: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type Revision = {\n readonly revision: Scalars[\"Int\"][\"output\"];\n readonly scope: Scalars[\"String\"][\"output\"];\n};\n\nexport type SearchFilterInput = {\n readonly identifiers?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly parentId?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly type?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n};\n\nexport type Subscription = {\n readonly documentChanges: DocumentChangeEvent;\n readonly jobChanges: JobChangeEvent;\n};\n\nexport type SubscriptionDocumentChangesArgs = {\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n};\n\nexport type SubscriptionJobChangesArgs = {\n jobId: Scalars[\"String\"][\"input\"];\n};\n\nexport type SyncEnvelope = {\n readonly channelMeta: ChannelMeta;\n readonly cursor?: Maybe<RemoteCursor>;\n readonly dependsOn?: Maybe<ReadonlyArray<Scalars[\"String\"][\"output\"]>>;\n readonly key?: Maybe<Scalars[\"String\"][\"output\"]>;\n readonly operations?: Maybe<ReadonlyArray<OperationWithContext>>;\n readonly type: SyncEnvelopeType;\n};\n\nexport type SyncEnvelopeInput = {\n readonly channelMeta: ChannelMetaInput;\n readonly cursor?: InputMaybe<RemoteCursorInput>;\n readonly dependsOn?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n readonly key?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly operations?: InputMaybe<ReadonlyArray<OperationWithContextInput>>;\n readonly type: SyncEnvelopeType;\n};\n\nexport enum SyncEnvelopeType {\n Ack = \"ACK\",\n Operations = \"OPERATIONS\",\n}\n\nexport type TouchChannelInput = {\n readonly collectionId: Scalars[\"String\"][\"input\"];\n readonly filter: RemoteFilterInput;\n readonly id: Scalars[\"String\"][\"input\"];\n readonly name: Scalars[\"String\"][\"input\"];\n readonly sinceTimestampUtcMs: Scalars[\"String\"][\"input\"];\n};\n\nexport type ViewFilterInput = {\n readonly branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n readonly scopes?: InputMaybe<ReadonlyArray<Scalars[\"String\"][\"input\"]>>;\n};\n\nexport type PhDocumentFieldsFragment = {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n};\n\nexport type GetDocumentModelsQueryVariables = Exact<{\n namespace?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentModelsQuery = {\n readonly documentModels: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly name: string;\n readonly namespace?: string | null | undefined;\n readonly version?: string | null | undefined;\n readonly specification: NonNullable<unknown>;\n }>;\n };\n};\n\nexport type GetDocumentQueryVariables = Exact<{\n identifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type GetDocumentQuery = {\n readonly document?:\n | {\n readonly childIds: ReadonlyArray<string>;\n readonly document: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n }\n | null\n | undefined;\n};\n\nexport type GetDocumentWithOperationsQueryVariables = Exact<{\n identifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n operationsFilter?: InputMaybe<DocumentOperationsFilterInput>;\n operationsPaging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentWithOperationsQuery = {\n readonly document?:\n | {\n readonly childIds: ReadonlyArray<string>;\n readonly document: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly operations?:\n | {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly index: number;\n readonly timestampUtcMs: string;\n readonly hash: string;\n readonly skip: number;\n readonly error?: string | null | undefined;\n readonly id?: string | null | undefined;\n readonly action: {\n readonly id: string;\n readonly type: string;\n readonly timestampUtcMs: string;\n readonly input: NonNullable<unknown>;\n readonly scope: string;\n readonly attachments?:\n | ReadonlyArray<{\n readonly data: string;\n readonly mimeType: string;\n readonly hash: string;\n readonly extension?: string | null | undefined;\n readonly fileName?: string | null | undefined;\n }>\n | null\n | undefined;\n readonly context?:\n | {\n readonly signer?:\n | {\n readonly signatures: ReadonlyArray<string>;\n readonly user?:\n | {\n readonly address: string;\n readonly networkId: string;\n readonly chainId: number;\n }\n | null\n | undefined;\n readonly app?:\n | {\n readonly name: string;\n readonly key: string;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n };\n }>;\n }\n | null\n | undefined;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n }\n | null\n | undefined;\n};\n\nexport type GetDocumentChildrenQueryVariables = Exact<{\n parentIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentChildrenQuery = {\n readonly documentChildren: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n };\n};\n\nexport type GetDocumentParentsQueryVariables = Exact<{\n childIdentifier: Scalars[\"String\"][\"input\"];\n view?: InputMaybe<ViewFilterInput>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentParentsQuery = {\n readonly documentParents: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n };\n};\n\nexport type FindDocumentsQueryVariables = Exact<{\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type FindDocumentsQuery = {\n readonly findDocuments: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n };\n};\n\nexport type GetDocumentOperationsQueryVariables = Exact<{\n filter: OperationsFilterInput;\n paging?: InputMaybe<PagingInput>;\n}>;\n\nexport type GetDocumentOperationsQuery = {\n readonly documentOperations: {\n readonly totalCount: number;\n readonly hasNextPage: boolean;\n readonly hasPreviousPage: boolean;\n readonly cursor?: string | null | undefined;\n readonly items: ReadonlyArray<{\n readonly index: number;\n readonly timestampUtcMs: string;\n readonly hash: string;\n readonly skip: number;\n readonly error?: string | null | undefined;\n readonly id?: string | null | undefined;\n readonly action: {\n readonly id: string;\n readonly type: string;\n readonly timestampUtcMs: string;\n readonly input: NonNullable<unknown>;\n readonly scope: string;\n readonly attachments?:\n | ReadonlyArray<{\n readonly data: string;\n readonly mimeType: string;\n readonly hash: string;\n readonly extension?: string | null | undefined;\n readonly fileName?: string | null | undefined;\n }>\n | null\n | undefined;\n readonly context?:\n | {\n readonly signer?:\n | {\n readonly signatures: ReadonlyArray<string>;\n readonly user?:\n | {\n readonly address: string;\n readonly networkId: string;\n readonly chainId: number;\n }\n | null\n | undefined;\n readonly app?:\n | { readonly name: string; readonly key: string }\n | null\n | undefined;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n };\n }>;\n };\n};\n\nexport type GetJobStatusQueryVariables = Exact<{\n jobId: Scalars[\"String\"][\"input\"];\n}>;\n\nexport type GetJobStatusQuery = {\n readonly jobStatus?:\n | {\n readonly id: string;\n readonly status: string;\n readonly result: NonNullable<unknown>;\n readonly error?: string | null | undefined;\n readonly createdAt: string | Date;\n readonly completedAt?: string | Date | null | undefined;\n }\n | null\n | undefined;\n};\n\nexport type CreateDocumentMutationVariables = Exact<{\n document: Scalars[\"JSONObject\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type CreateDocumentMutation = {\n readonly createDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type CreateEmptyDocumentMutationVariables = Exact<{\n documentType: Scalars[\"String\"][\"input\"];\n parentIdentifier?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type CreateEmptyDocumentMutation = {\n readonly createEmptyDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type MutateDocumentMutationVariables = Exact<{\n documentIdentifier: Scalars[\"String\"][\"input\"];\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type MutateDocumentMutation = {\n readonly mutateDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type MutateDocumentAsyncMutationVariables = Exact<{\n documentIdentifier: Scalars[\"String\"][\"input\"];\n actions: ReadonlyArray<Scalars[\"JSONObject\"][\"input\"]>;\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type MutateDocumentAsyncMutation = {\n readonly mutateDocumentAsync: string;\n};\n\nexport type RenameDocumentMutationVariables = Exact<{\n documentIdentifier: Scalars[\"String\"][\"input\"];\n name: Scalars[\"String\"][\"input\"];\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type RenameDocumentMutation = {\n readonly renameDocument: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type AddChildrenMutationVariables = Exact<{\n parentIdentifier: Scalars[\"String\"][\"input\"];\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type AddChildrenMutation = {\n readonly addChildren: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type RemoveChildrenMutationVariables = Exact<{\n parentIdentifier: Scalars[\"String\"][\"input\"];\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type RemoveChildrenMutation = {\n readonly removeChildren: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n};\n\nexport type MoveChildrenMutationVariables = Exact<{\n sourceParentIdentifier: Scalars[\"String\"][\"input\"];\n targetParentIdentifier: Scalars[\"String\"][\"input\"];\n documentIdentifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n branch?: InputMaybe<Scalars[\"String\"][\"input\"]>;\n}>;\n\nexport type MoveChildrenMutation = {\n readonly moveChildren: {\n readonly source: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n readonly target: {\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n };\n };\n};\n\nexport type DeleteDocumentMutationVariables = Exact<{\n identifier: Scalars[\"String\"][\"input\"];\n propagate?: InputMaybe<PropagationMode>;\n}>;\n\nexport type DeleteDocumentMutation = { readonly deleteDocument: boolean };\n\nexport type DeleteDocumentsMutationVariables = Exact<{\n identifiers: ReadonlyArray<Scalars[\"String\"][\"input\"]>;\n propagate?: InputMaybe<PropagationMode>;\n}>;\n\nexport type DeleteDocumentsMutation = { readonly deleteDocuments: boolean };\n\nexport type DocumentChangesSubscriptionVariables = Exact<{\n search: SearchFilterInput;\n view?: InputMaybe<ViewFilterInput>;\n}>;\n\nexport type DocumentChangesSubscription = {\n readonly documentChanges: {\n readonly type: DocumentChangeType;\n readonly documents: ReadonlyArray<{\n readonly id: string;\n readonly slug?: string | null | undefined;\n readonly name: string;\n readonly documentType: string;\n readonly state: NonNullable<unknown>;\n readonly createdAtUtcIso: string | Date;\n readonly lastModifiedAtUtcIso: string | Date;\n readonly revisionsList: ReadonlyArray<{\n readonly scope: string;\n readonly revision: number;\n }>;\n }>;\n readonly context?:\n | {\n readonly parentId?: string | null | undefined;\n readonly childId?: string | null | undefined;\n }\n | null\n | undefined;\n };\n};\n\nexport type JobChangesSubscriptionVariables = Exact<{\n jobId: Scalars[\"String\"][\"input\"];\n}>;\n\nexport type JobChangesSubscription = {\n readonly jobChanges: {\n readonly jobId: string;\n readonly status: string;\n readonly result: NonNullable<unknown>;\n readonly error?: string | null | undefined;\n };\n};\n\nexport type PollSyncEnvelopesQueryVariables = Exact<{\n channelId: Scalars[\"String\"][\"input\"];\n outboxAck: Scalars[\"Int\"][\"input\"];\n outboxLatest: Scalars[\"Int\"][\"input\"];\n}>;\n\nexport type PollSyncEnvelopesQuery = {\n readonly pollSyncEnvelopes: {\n readonly ackOrdinal: number;\n readonly envelopes: ReadonlyArray<{\n readonly type: SyncEnvelopeType;\n readonly key?: string | null | undefined;\n readonly dependsOn?: ReadonlyArray<string> | null | undefined;\n readonly channelMeta: { readonly id: string };\n readonly operations?:\n | ReadonlyArray<{\n readonly operation: {\n readonly index: number;\n readonly timestampUtcMs: string;\n readonly hash: string;\n readonly skip: number;\n readonly error?: string | null | undefined;\n readonly id?: string | null | undefined;\n readonly action: {\n readonly id: string;\n readonly type: string;\n readonly timestampUtcMs: string;\n readonly input: NonNullable<unknown>;\n readonly scope: string;\n readonly attachments?:\n | ReadonlyArray<{\n readonly data: string;\n readonly mimeType: string;\n readonly hash: string;\n readonly extension?: string | null | undefined;\n readonly fileName?: string | null | undefined;\n }>\n | null\n | undefined;\n readonly context?:\n | {\n readonly signer?:\n | {\n readonly signatures: ReadonlyArray<string>;\n readonly user?:\n | {\n readonly address: string;\n readonly networkId: string;\n readonly chainId: number;\n }\n | null\n | undefined;\n readonly app?:\n | { readonly name: string; readonly key: string }\n | null\n | undefined;\n }\n | null\n | undefined;\n }\n | null\n | undefined;\n };\n };\n readonly context: {\n readonly documentId: string;\n readonly documentType: string;\n readonly scope: string;\n readonly branch: string;\n };\n }>\n | null\n | undefined;\n readonly cursor?:\n | {\n readonly remoteName: string;\n readonly cursorOrdinal: number;\n readonly lastSyncedAtUtcMs?: string | null | undefined;\n }\n | null\n | undefined;\n }>;\n readonly deadLetters: ReadonlyArray<{\n readonly documentId: string;\n readonly error: string;\n }>;\n };\n};\n\nexport type TouchChannelMutationVariables = Exact<{\n input: TouchChannelInput;\n}>;\n\nexport type TouchChannelMutation = { readonly touchChannel: boolean };\n\nexport type PushSyncEnvelopesMutationVariables = Exact<{\n envelopes: ReadonlyArray<SyncEnvelopeInput>;\n}>;\n\nexport type PushSyncEnvelopesMutation = { readonly pushSyncEnvelopes: boolean };\n\nexport const PhDocumentFieldsFragmentDoc = gql`\n fragment PHDocumentFields on PHDocument {\n id\n slug\n name\n documentType\n state\n revisionsList {\n scope\n revision\n }\n createdAtUtcIso\n lastModifiedAtUtcIso\n }\n`;\nexport const GetDocumentModelsDocument = gql`\n query GetDocumentModels($namespace: String, $paging: PagingInput) {\n documentModels(namespace: $namespace, paging: $paging) {\n items {\n id\n name\n namespace\n version\n specification\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n`;\nexport const GetDocumentDocument = gql`\n query GetDocument($identifier: String!, $view: ViewFilterInput) {\n document(identifier: $identifier, view: $view) {\n document {\n ...PHDocumentFields\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentWithOperationsDocument = gql`\n query GetDocumentWithOperations(\n $identifier: String!\n $view: ViewFilterInput\n $operationsFilter: DocumentOperationsFilterInput\n $operationsPaging: PagingInput\n ) {\n document(identifier: $identifier, view: $view) {\n document {\n ...PHDocumentFields\n operations(filter: $operationsFilter, paging: $operationsPaging) {\n items {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n attachments {\n data\n mimeType\n hash\n extension\n fileName\n }\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n childIds\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentChildrenDocument = gql`\n query GetDocumentChildren(\n $parentIdentifier: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentChildren(\n parentIdentifier: $parentIdentifier\n view: $view\n paging: $paging\n ) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentParentsDocument = gql`\n query GetDocumentParents(\n $childIdentifier: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentParents(\n childIdentifier: $childIdentifier\n view: $view\n paging: $paging\n ) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const FindDocumentsDocument = gql`\n query FindDocuments(\n $search: SearchFilterInput!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n findDocuments(search: $search, view: $view, paging: $paging) {\n items {\n ...PHDocumentFields\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const GetDocumentOperationsDocument = gql`\n query GetDocumentOperations(\n $filter: OperationsFilterInput!\n $paging: PagingInput\n ) {\n documentOperations(filter: $filter, paging: $paging) {\n items {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n attachments {\n data\n mimeType\n hash\n extension\n fileName\n }\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n totalCount\n hasNextPage\n hasPreviousPage\n cursor\n }\n }\n`;\nexport const GetJobStatusDocument = gql`\n query GetJobStatus($jobId: String!) {\n jobStatus(jobId: $jobId) {\n id\n status\n result\n error\n createdAt\n completedAt\n }\n }\n`;\nexport const CreateDocumentDocument = gql`\n mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {\n createDocument(document: $document, parentIdentifier: $parentIdentifier) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const CreateEmptyDocumentDocument = gql`\n mutation CreateEmptyDocument(\n $documentType: String!\n $parentIdentifier: String\n ) {\n createEmptyDocument(\n documentType: $documentType\n parentIdentifier: $parentIdentifier\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const MutateDocumentDocument = gql`\n mutation MutateDocument(\n $documentIdentifier: String!\n $actions: [JSONObject!]!\n $view: ViewFilterInput\n ) {\n mutateDocument(\n documentIdentifier: $documentIdentifier\n actions: $actions\n view: $view\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const MutateDocumentAsyncDocument = gql`\n mutation MutateDocumentAsync(\n $documentIdentifier: String!\n $actions: [JSONObject!]!\n $view: ViewFilterInput\n ) {\n mutateDocumentAsync(\n documentIdentifier: $documentIdentifier\n actions: $actions\n view: $view\n )\n }\n`;\nexport const RenameDocumentDocument = gql`\n mutation RenameDocument(\n $documentIdentifier: String!\n $name: String!\n $branch: String\n ) {\n renameDocument(\n documentIdentifier: $documentIdentifier\n name: $name\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const AddChildrenDocument = gql`\n mutation AddChildren(\n $parentIdentifier: String!\n $documentIdentifiers: [String!]!\n $branch: String\n ) {\n addChildren(\n parentIdentifier: $parentIdentifier\n documentIdentifiers: $documentIdentifiers\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const RemoveChildrenDocument = gql`\n mutation RemoveChildren(\n $parentIdentifier: String!\n $documentIdentifiers: [String!]!\n $branch: String\n ) {\n removeChildren(\n parentIdentifier: $parentIdentifier\n documentIdentifiers: $documentIdentifiers\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const MoveChildrenDocument = gql`\n mutation MoveChildren(\n $sourceParentIdentifier: String!\n $targetParentIdentifier: String!\n $documentIdentifiers: [String!]!\n $branch: String\n ) {\n moveChildren(\n sourceParentIdentifier: $sourceParentIdentifier\n targetParentIdentifier: $targetParentIdentifier\n documentIdentifiers: $documentIdentifiers\n branch: $branch\n ) {\n source {\n ...PHDocumentFields\n }\n target {\n ...PHDocumentFields\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const DeleteDocumentDocument = gql`\n mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {\n deleteDocument(identifier: $identifier, propagate: $propagate)\n }\n`;\nexport const DeleteDocumentsDocument = gql`\n mutation DeleteDocuments(\n $identifiers: [String!]!\n $propagate: PropagationMode\n ) {\n deleteDocuments(identifiers: $identifiers, propagate: $propagate)\n }\n`;\nexport const DocumentChangesDocument = gql`\n subscription DocumentChanges(\n $search: SearchFilterInput!\n $view: ViewFilterInput\n ) {\n documentChanges(search: $search, view: $view) {\n type\n documents {\n ...PHDocumentFields\n }\n context {\n parentId\n childId\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nexport const JobChangesDocument = gql`\n subscription JobChanges($jobId: String!) {\n jobChanges(jobId: $jobId) {\n jobId\n status\n result\n error\n }\n }\n`;\nexport const PollSyncEnvelopesDocument = gql`\n query PollSyncEnvelopes(\n $channelId: String!\n $outboxAck: Int!\n $outboxLatest: Int!\n ) {\n pollSyncEnvelopes(\n channelId: $channelId\n outboxAck: $outboxAck\n outboxLatest: $outboxLatest\n ) {\n envelopes {\n type\n channelMeta {\n id\n }\n operations {\n operation {\n index\n timestampUtcMs\n hash\n skip\n error\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\n attachments {\n data\n mimeType\n hash\n extension\n fileName\n }\n context {\n signer {\n user {\n address\n networkId\n chainId\n }\n app {\n name\n key\n }\n signatures\n }\n }\n }\n }\n context {\n documentId\n documentType\n scope\n branch\n }\n }\n cursor {\n remoteName\n cursorOrdinal\n lastSyncedAtUtcMs\n }\n key\n dependsOn\n }\n ackOrdinal\n deadLetters {\n documentId\n error\n }\n }\n }\n`;\nexport const TouchChannelDocument = gql`\n mutation TouchChannel($input: TouchChannelInput!) {\n touchChannel(input: $input)\n }\n`;\nexport const PushSyncEnvelopesDocument = gql`\n mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {\n pushSyncEnvelopes(envelopes: $envelopes)\n }\n`;\n\nexport type SdkFunctionWrapper = <T>(\n action: (requestHeaders?: Record<string, string>) => Promise<T>,\n operationName: string,\n operationType?: string,\n variables?: any,\n) => Promise<T>;\n\nconst defaultWrapper: SdkFunctionWrapper = (\n action,\n _operationName,\n _operationType,\n _variables,\n) => action();\n\nexport function getSdk(\n client: GraphQLClient,\n withWrapper: SdkFunctionWrapper = defaultWrapper,\n) {\n return {\n GetDocumentModels(\n variables?: GetDocumentModelsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentModelsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentModelsQuery>({\n document: GetDocumentModelsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentModels\",\n \"query\",\n variables,\n );\n },\n GetDocument(\n variables: GetDocumentQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentQuery>({\n document: GetDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocument\",\n \"query\",\n variables,\n );\n },\n GetDocumentWithOperations(\n variables: GetDocumentWithOperationsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentWithOperationsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentWithOperationsQuery>({\n document: GetDocumentWithOperationsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentWithOperations\",\n \"query\",\n variables,\n );\n },\n GetDocumentChildren(\n variables: GetDocumentChildrenQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentChildrenQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentChildrenQuery>({\n document: GetDocumentChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentChildren\",\n \"query\",\n variables,\n );\n },\n GetDocumentParents(\n variables: GetDocumentParentsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentParentsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentParentsQuery>({\n document: GetDocumentParentsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentParents\",\n \"query\",\n variables,\n );\n },\n FindDocuments(\n variables: FindDocumentsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<FindDocumentsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<FindDocumentsQuery>({\n document: FindDocumentsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"FindDocuments\",\n \"query\",\n variables,\n );\n },\n GetDocumentOperations(\n variables: GetDocumentOperationsQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetDocumentOperationsQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetDocumentOperationsQuery>({\n document: GetDocumentOperationsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetDocumentOperations\",\n \"query\",\n variables,\n );\n },\n GetJobStatus(\n variables: GetJobStatusQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<GetJobStatusQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<GetJobStatusQuery>({\n document: GetJobStatusDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"GetJobStatus\",\n \"query\",\n variables,\n );\n },\n CreateDocument(\n variables: CreateDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<CreateDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<CreateDocumentMutation>({\n document: CreateDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"CreateDocument\",\n \"mutation\",\n variables,\n );\n },\n CreateEmptyDocument(\n variables: CreateEmptyDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<CreateEmptyDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<CreateEmptyDocumentMutation>({\n document: CreateEmptyDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"CreateEmptyDocument\",\n \"mutation\",\n variables,\n );\n },\n MutateDocument(\n variables: MutateDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<MutateDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<MutateDocumentMutation>({\n document: MutateDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"MutateDocument\",\n \"mutation\",\n variables,\n );\n },\n MutateDocumentAsync(\n variables: MutateDocumentAsyncMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<MutateDocumentAsyncMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<MutateDocumentAsyncMutation>({\n document: MutateDocumentAsyncDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"MutateDocumentAsync\",\n \"mutation\",\n variables,\n );\n },\n RenameDocument(\n variables: RenameDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<RenameDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<RenameDocumentMutation>({\n document: RenameDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"RenameDocument\",\n \"mutation\",\n variables,\n );\n },\n AddChildren(\n variables: AddChildrenMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<AddChildrenMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<AddChildrenMutation>({\n document: AddChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"AddChildren\",\n \"mutation\",\n variables,\n );\n },\n RemoveChildren(\n variables: RemoveChildrenMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<RemoveChildrenMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<RemoveChildrenMutation>({\n document: RemoveChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"RemoveChildren\",\n \"mutation\",\n variables,\n );\n },\n MoveChildren(\n variables: MoveChildrenMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<MoveChildrenMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<MoveChildrenMutation>({\n document: MoveChildrenDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"MoveChildren\",\n \"mutation\",\n variables,\n );\n },\n DeleteDocument(\n variables: DeleteDocumentMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<DeleteDocumentMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<DeleteDocumentMutation>({\n document: DeleteDocumentDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"DeleteDocument\",\n \"mutation\",\n variables,\n );\n },\n DeleteDocuments(\n variables: DeleteDocumentsMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<DeleteDocumentsMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<DeleteDocumentsMutation>({\n document: DeleteDocumentsDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"DeleteDocuments\",\n \"mutation\",\n variables,\n );\n },\n DocumentChanges(\n variables: DocumentChangesSubscriptionVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<DocumentChangesSubscription> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<DocumentChangesSubscription>({\n document: DocumentChangesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"DocumentChanges\",\n \"subscription\",\n variables,\n );\n },\n JobChanges(\n variables: JobChangesSubscriptionVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<JobChangesSubscription> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<JobChangesSubscription>({\n document: JobChangesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"JobChanges\",\n \"subscription\",\n variables,\n );\n },\n PollSyncEnvelopes(\n variables: PollSyncEnvelopesQueryVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<PollSyncEnvelopesQuery> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<PollSyncEnvelopesQuery>({\n document: PollSyncEnvelopesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"PollSyncEnvelopes\",\n \"query\",\n variables,\n );\n },\n TouchChannel(\n variables: TouchChannelMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<TouchChannelMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<TouchChannelMutation>({\n document: TouchChannelDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"TouchChannel\",\n \"mutation\",\n variables,\n );\n },\n PushSyncEnvelopes(\n variables: PushSyncEnvelopesMutationVariables,\n requestHeaders?: GraphQLClientRequestHeaders,\n signal?: RequestInit[\"signal\"],\n ): Promise<PushSyncEnvelopesMutation> {\n return withWrapper(\n (wrappedRequestHeaders) =>\n client.request<PushSyncEnvelopesMutation>({\n document: PushSyncEnvelopesDocument,\n variables,\n requestHeaders: { ...requestHeaders, ...wrappedRequestHeaders },\n signal,\n }),\n \"PushSyncEnvelopes\",\n \"mutation\",\n variables,\n );\n },\n };\n}\nexport type Sdk = ReturnType<typeof getSdk>;\n","import {\n GetDocumentDocument,\n GetDocumentOperationsDocument,\n type OperationsFilterInput,\n type PagingInput,\n type ViewFilterInput,\n} from \"./gen/schema.js\";\n\n/** Get the source string from a GraphQL document (string or DocumentNode). */\nfunction getDocumentSource(doc: unknown): string {\n return typeof doc === \"string\"\n ? doc\n : ((doc as { loc?: { source: { body: string } } }).loc?.source.body ?? \"\");\n}\n\n/**\n * Extract the inner selection set of a named field from a GraphQL document source.\n * Returns the `{ ... }` block including braces.\n */\nfunction extractSelectionSet(\n doc: unknown,\n fieldName: string,\n fallback: string,\n): string {\n const source = getDocumentSource(doc);\n\n const regex = new RegExp(\n `${fieldName}\\\\([^)]*\\\\)\\\\s*(\\\\{[\\\\s\\\\S]*\\\\})\\\\s*\\\\}`,\n );\n return regex.exec(source)?.[1] ?? fallback;\n}\n\n/**\n * Extract the query body and any fragment definitions from a GraphQL document.\n * Returns { body, fragments } where body is the content inside the query `{ ... }`\n * and fragments are any trailing fragment definitions.\n */\nfunction extractQueryParts(\n doc: unknown,\n fallbackBody: string,\n): { body: string; fragments: string } {\n const source = getDocumentSource(doc);\n\n // Match the query body: everything between the first `{` and its closing `}`\n // before any fragment definitions\n const queryMatch = /^[^{]*\\{([\\s\\S]*?)\\}\\s*(fragment[\\s\\S]*)?$/.exec(source);\n const body = queryMatch?.[1]?.trim() ?? fallbackBody;\n const fragments = queryMatch?.[2]?.trim() ?? \"\";\n\n return { body, fragments };\n}\n\nconst operationsSelectionSet = extractSelectionSet(\n GetDocumentOperationsDocument,\n \"documentOperations\",\n \"{ items { index } }\",\n);\n\nconst documentParts = extractQueryParts(\n GetDocumentDocument,\n \"document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }\",\n);\n\n/**\n * Build a single GraphQL query that fetches documentOperations for\n * multiple filters using aliases. Each filter gets its own alias\n * (`scope_0`, `scope_1`, …) so all scopes are fetched in one HTTP request.\n */\nexport function buildBatchOperationsQuery(\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined | null)[],\n) {\n const varDefs = filters\n .flatMap((_, i) => [\n `$filter_${i}: OperationsFilterInput!`,\n `$paging_${i}: PagingInput`,\n ])\n .join(\", \");\n\n const fields = filters\n .map(\n (_, i) =>\n `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`,\n )\n .join(\"\\n \");\n\n const query = `query BatchGetDocumentOperations(${varDefs}) {\n ${fields}\n }`;\n\n const variables: Record<string, unknown> = {};\n for (let i = 0; i < filters.length; i++) {\n variables[`filter_${i}`] = filters[i];\n variables[`paging_${i}`] = pagings[i] ?? null;\n }\n\n return { query, variables };\n}\n\n/**\n * Build a single GraphQL query that fetches a document AND\n * documentOperations for multiple filters, all in one HTTP request.\n */\nexport function buildBatchDocumentWithOperationsQuery(\n identifier: string,\n view: ViewFilterInput | undefined,\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined)[],\n) {\n const docVarDefs = \"$identifier: String!, $view: ViewFilterInput\";\n const opsVarDefs = filters\n .flatMap((_, i) => [\n `$filter_${i}: OperationsFilterInput!`,\n `$paging_${i}: PagingInput`,\n ])\n .join(\", \");\n\n const opsFields = filters\n .map(\n (_, i) =>\n `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`,\n )\n .join(\"\\n \");\n\n const query = `query BatchGetDocumentWithOperations(${docVarDefs}, ${opsVarDefs}) {\n ${documentParts.body}\n ${opsFields}\n }\n ${documentParts.fragments}`;\n\n const variables: Record<string, unknown> = {\n identifier,\n view: view ?? null,\n };\n for (let i = 0; i < filters.length; i++) {\n variables[`filter_${i}`] = filters[i];\n variables[`paging_${i}`] = pagings[i] ?? null;\n }\n\n return { query, variables };\n}\n","import { GraphQLClient } from \"graphql-request\";\nimport {\n buildBatchDocumentWithOperationsQuery,\n buildBatchOperationsQuery,\n} from \"./batch-queries.js\";\nimport {\n getSdk,\n type GetDocumentOperationsQuery,\n type GetDocumentQuery,\n type OperationsFilterInput,\n type PagingInput,\n type SdkFunctionWrapper,\n type ViewFilterInput,\n} from \"./gen/schema.js\";\nimport type { ReactorGraphQLClient } from \"./types.js\";\n\nexport type { ReactorGraphQLClient } from \"./types.js\";\n\ntype DocumentOperationsPage = GetDocumentOperationsQuery[\"documentOperations\"];\n\ntype DocumentResult = NonNullable<GetDocumentQuery[\"document\"]>;\n\n/**\n * Creates a GraphQL client for the Reactor Subgraph API.\n * @param urlOrGQLClient The URL of the GraphQL API or a GraphQL client instance.\n * @param middleware An optional middleware function to wrap the GraphQL client calls.\n * @returns A GraphQL client for the Reactor Subgraph API.\n */\nexport function createClient(\n urlOrGQLClient: string | GraphQLClient,\n middleware?: SdkFunctionWrapper,\n): ReactorGraphQLClient {\n const client =\n typeof urlOrGQLClient === \"string\"\n ? new GraphQLClient(urlOrGQLClient)\n : urlOrGQLClient;\n return {\n ...getSdk(client, middleware),\n\n /**\n * Fetch documentOperations for multiple filters in a single HTTP request\n * using GraphQL aliases. Each filter has its own paging parameters.\n * Returns one result page per filter, in order.\n */\n async BatchGetDocumentOperations(\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined | null)[],\n ): Promise<DocumentOperationsPage[]> {\n const { query, variables } = buildBatchOperationsQuery(filters, pagings);\n const data = await client.request<Record<string, DocumentOperationsPage>>(\n query,\n variables,\n );\n return filters.map((_, i) => data[`scope_${i}`]);\n },\n\n /**\n * Fetch a document AND documentOperations for multiple filters\n * in a single HTTP request. Combines GetDocument + BatchGetDocumentOperations.\n */\n async BatchGetDocumentWithOperations(\n identifier: string,\n view: ViewFilterInput | undefined,\n filters: OperationsFilterInput[],\n pagings: (PagingInput | undefined)[],\n ): Promise<{\n document: DocumentResult | null;\n operations: DocumentOperationsPage[];\n }> {\n const { query, variables } = buildBatchDocumentWithOperationsQuery(\n identifier,\n view,\n filters,\n pagings,\n );\n const data = await client.request<\n Record<string, unknown> & { document?: DocumentResult }\n >(query, variables);\n return {\n document: data.document ?? null,\n operations: filters.map(\n (_, i) => data[`scope_${i}`] as DocumentOperationsPage,\n ),\n };\n },\n };\n}\n","import type { LOADING } from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nexport const {\n useValue: useLoading,\n setValue: setLoading,\n addEventHandler: addLoadingEventHandler,\n} = makePHEventFunctions(\"loading\");\n\nexport const loading: LOADING = null;\n","import type { IRenown, LoginStatus, User } from \"@renown/sdk\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport type { LOADING } from \"../types/global.js\";\nimport { loading } from \"./loading.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst renownEventFunctions = makePHEventFunctions(\"renown\");\n\n/** Adds an event handler for the renown instance */\nexport const addRenownEventHandler: () => void =\n renownEventFunctions.addEventHandler;\n\n/** Returns the renown instance */\nexport const useRenown: () => IRenown | LOADING | undefined =\n renownEventFunctions.useValue;\n\n/** Sets the renown instance */\nexport const setRenown: (value: IRenown | LOADING | undefined) => void =\n renownEventFunctions.setValue;\n\n/** Returns the DID from the renown instance */\nexport function useDid() {\n const renown = useRenown();\n return renown?.did;\n}\n\n/** Returns the current user from the renown instance, subscribing to user events */\nexport function useUser(): User | undefined {\n const renown = useRenown();\n const [user, setUser] = useState<User | undefined>(renown?.user);\n\n useEffect(() => {\n setUser(renown?.user);\n if (!renown) return;\n return renown.on(\"user\", setUser);\n }, [renown]);\n\n return user;\n}\n\n/** Returns the login status, subscribing to renown status events */\nexport function useLoginStatus(): LoginStatus | \"loading\" | undefined {\n const renown = useRenown();\n return useSyncExternalStore(\n (cb) => {\n if (!renown) {\n return () => {};\n }\n return renown.on(\"status\", cb);\n },\n () => (renown === loading ? \"loading\" : renown?.status),\n () => undefined,\n );\n}\n","export const RENOWN_URL = \"https://www.renown.id\";\nexport const RENOWN_NETWORK_ID = \"eip155\";\nexport const RENOWN_CHAIN_ID = \"1\";\n\nexport const DOMAIN_TYPE = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nexport const VERIFIABLE_CREDENTIAL_EIP712_TYPE = [\n { name: \"@context\", type: \"string[]\" },\n { name: \"type\", type: \"string[]\" },\n { name: \"id\", type: \"string\" },\n { name: \"issuer\", type: \"Issuer\" },\n { name: \"credentialSubject\", type: \"CredentialSubject\" },\n { name: \"credentialSchema\", type: \"CredentialSchema\" },\n { name: \"issuanceDate\", type: \"string\" },\n { name: \"expirationDate\", type: \"string\" },\n] as const;\n\nexport const CREDENTIAL_SCHEMA_EIP712_TYPE = [\n { name: \"id\", type: \"string\" },\n { name: \"type\", type: \"string\" },\n] as const;\n\nexport const CREDENTIAL_SUBJECT_TYPE = [\n { name: \"app\", type: \"string\" },\n { name: \"id\", type: \"string\" },\n { name: \"name\", type: \"string\" },\n] as const;\n\nexport const ISSUER_TYPE = [\n { name: \"id\", type: \"string\" },\n { name: \"ethereumAddress\", type: \"string\" },\n] as const;\n\nexport const CREDENTIAL_TYPES = {\n EIP712Domain: DOMAIN_TYPE,\n VerifiableCredential: VERIFIABLE_CREDENTIAL_EIP712_TYPE,\n CredentialSchema: CREDENTIAL_SCHEMA_EIP712_TYPE,\n CredentialSubject: CREDENTIAL_SUBJECT_TYPE,\n Issuer: ISSUER_TYPE,\n} as const;\n","import type { IRenown, User } from \"@renown/sdk\";\nimport { logger } from \"document-model\";\nimport { RENOWN_CHAIN_ID, RENOWN_NETWORK_ID, RENOWN_URL } from \"./constants.js\";\n\nexport function openRenown(documentId?: string) {\n const renown = window.ph?.renown;\n let renownUrl = renown?.baseUrl;\n if (!renownUrl) {\n logger.warn(\"Renown instance not found, falling back to: \", RENOWN_URL);\n renownUrl = RENOWN_URL;\n }\n\n if (documentId) {\n window.open(`${renownUrl}/profile/${documentId}`, \"_blank\")?.focus();\n return;\n }\n\n const url = new URL(renownUrl);\n url.searchParams.set(\"app\", renown?.did ?? \"\");\n url.searchParams.set(\"connect\", renown?.did ?? \"\");\n url.searchParams.set(\"network\", RENOWN_NETWORK_ID);\n url.searchParams.set(\"chain\", RENOWN_CHAIN_ID);\n\n const returnUrl = new URL(window.location.pathname, window.location.origin);\n url.searchParams.set(\"returnUrl\", returnUrl.toJSON());\n window.open(url, \"_self\")?.focus();\n}\n\n/**\n * Reads the `?user=` DID from the URL if present.\n * Returns the DID and cleans up the URL parameter.\n */\nfunction consumeDidFromUrl(): string | undefined {\n if (typeof window === \"undefined\") return;\n\n const urlParams = new URLSearchParams(window.location.search);\n const userParam = urlParams.get(\"user\");\n if (!userParam) return;\n\n const userDid = decodeURIComponent(userParam);\n\n // Clean up the URL parameter\n const cleanUrl = new URL(window.location.href);\n cleanUrl.searchParams.delete(\"user\");\n window.history.replaceState({}, \"\", cleanUrl.toString());\n\n return userDid;\n}\n\n/**\n * Log in the user. Resolves the user DID from (in order):\n * 1. Explicit `userDid` argument\n * 2. `?user=` URL parameter (from Renown portal redirect)\n * 3. Previously stored session in the Renown instance\n */\nexport async function login(\n userDid: string | undefined,\n renown: IRenown | undefined,\n): Promise<User | undefined> {\n if (!renown) {\n return;\n }\n\n const did = userDid ?? consumeDidFromUrl();\n\n try {\n const user = renown.user;\n\n if (user?.did && (user.did === did || !did)) {\n return user;\n }\n\n if (!did) {\n return;\n }\n\n return await renown.login(did);\n } catch (error) {\n logger.error(\n error instanceof Error ? error.message : JSON.stringify(error),\n );\n }\n}\n\nexport async function logout() {\n const renown = window.ph?.renown;\n await renown?.logout();\n\n // Clear the user parameter from URL to prevent auto-login on refresh\n const url = new URL(window.location.href);\n if (url.searchParams.has(\"user\")) {\n url.searchParams.delete(\"user\");\n window.history.replaceState(null, \"\", url.toString());\n }\n}\n","import type { LoginStatus, User } from \"@renown/sdk\";\nimport { useCallback } from \"react\";\nimport { useLoginStatus, useUser } from \"../hooks/renown.js\";\nimport { logout as logoutUtil, openRenown } from \"./utils.js\";\n\nexport type RenownAuthStatus = LoginStatus | \"loading\";\n\nexport interface RenownAuth {\n status: RenownAuthStatus | undefined;\n user: User | undefined;\n address: string | undefined;\n ensName: string | undefined;\n avatarUrl: string | undefined;\n profileId: string | undefined;\n displayName: string | undefined;\n displayAddress: string | undefined;\n login: () => void;\n logout: () => Promise<void>;\n openProfile: () => void;\n}\n\nfunction truncateAddress(address: string): string {\n if (address.length <= 13) return address;\n return `${address.slice(0, 7)}...${address.slice(-5)}`;\n}\n\nfunction toRenownAuthStatus(\n loginStatus: LoginStatus | \"loading\" | undefined,\n user: User | undefined,\n): RenownAuthStatus | undefined {\n if (loginStatus === \"authorized\") {\n return user ? \"authorized\" : \"checking\";\n }\n return loginStatus;\n}\n\nexport function useRenownAuth(): RenownAuth {\n const user = useUser();\n const loginStatus = useLoginStatus();\n\n // syncs user with login status\n const status = toRenownAuthStatus(loginStatus, user);\n\n const address = user?.address;\n const ensName = user?.ens?.name;\n const avatarUrl = user?.profile?.userImage ?? user?.ens?.avatarUrl;\n const profileId = user?.profile?.documentId;\n\n const displayName = ensName ?? user?.profile?.username ?? undefined;\n const displayAddress = address ? truncateAddress(address) : undefined;\n\n const login = useCallback(() => {\n openRenown();\n }, []);\n\n const logout = useCallback(async () => {\n await logoutUtil();\n }, []);\n\n const openProfile = useCallback(() => {\n if (profileId) {\n openRenown(profileId);\n }\n }, [profileId]);\n\n return {\n status,\n user,\n address,\n ensName,\n avatarUrl,\n profileId,\n displayName,\n displayAddress,\n login,\n logout,\n openProfile,\n };\n}\n","import type {\n PHAppConfigHooks,\n PHAppConfigSetters,\n PHDocumentEditorConfigHooks,\n PHDocumentEditorConfigSetters,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"../make-ph-event-functions.js\";\n\nexport const isExternalControlsEnabledEventFunctions = makePHEventFunctions(\n \"isExternalControlsEnabled\",\n);\n\n/** Sets whether external controls are enabled for a given editor. */\nexport const setIsExternalControlsEnabled =\n isExternalControlsEnabledEventFunctions.setValue;\n\n/** Gets whether external controls are enabled for a given editor. */\nexport const useIsExternalControlsEnabled =\n isExternalControlsEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the external controls enabled state changes. */\nexport const addIsExternalControlsEnabledEventHandler =\n isExternalControlsEnabledEventFunctions.addEventHandler;\n\nconst isDragAndDropEnabledEventFunctions = makePHEventFunctions(\n \"isDragAndDropEnabled\",\n);\n\n/** Sets whether drag and drop is enabled for a given app. */\nexport const setIsDragAndDropEnabled =\n isDragAndDropEnabledEventFunctions.setValue;\n\n/** Gets whether drag and drop is enabled for a given app. */\nexport const useIsDragAndDropEnabled =\n isDragAndDropEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the drag and drop enabled state changes. */\nexport const addIsDragAndDropEnabledEventHandler =\n isDragAndDropEnabledEventFunctions.addEventHandler;\n\nconst allowedDocumentTypesEventFunctions = makePHEventFunctions(\n \"allowedDocumentTypes\",\n);\n\n/** Sets the allowed document types for a given app. */\nexport const setAllowedDocumentTypes =\n allowedDocumentTypesEventFunctions.setValue;\n\n/** Defines the document types a drive supports.\n *\n * Defaults to all of the document types registered in the reactor.\n */\nexport function useAllowedDocumentTypes() {\n const definedAllowedDocumentTypes =\n allowedDocumentTypesEventFunctions.useValue();\n return definedAllowedDocumentTypes;\n}\n\n/** Adds an event handler for when the allowed document types for a given app changes. */\nexport const addAllowedDocumentTypesEventHandler =\n allowedDocumentTypesEventFunctions.addEventHandler;\n\nexport const phAppConfigSetters: PHAppConfigSetters = {\n allowedDocumentTypes: setAllowedDocumentTypes,\n isDragAndDropEnabled: setIsDragAndDropEnabled,\n};\n\nexport const phDocumentEditorConfigSetters: PHDocumentEditorConfigSetters = {\n isExternalControlsEnabled: setIsExternalControlsEnabled,\n};\n\nexport const phAppConfigHooks: PHAppConfigHooks = {\n allowedDocumentTypes: useAllowedDocumentTypes,\n isDragAndDropEnabled: useIsDragAndDropEnabled,\n};\n\nexport const phDocumentEditorConfigHooks: PHDocumentEditorConfigHooks = {\n isExternalControlsEnabled: useIsExternalControlsEnabled,\n};\n","import type {\n PHAppConfigKey,\n PHDocumentEditorConfigKey,\n PHGlobalConfigHooks,\n PHGlobalConfigHooksForKey,\n PHGlobalConfigKey,\n PHGlobalConfigSetters,\n PHGlobalConfigSettersForKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { makePHEventFunctions } from \"../make-ph-event-functions.js\";\nimport {\n phAppConfigHooks,\n phAppConfigSetters,\n phDocumentEditorConfigHooks,\n phDocumentEditorConfigSetters,\n} from \"./editor.js\";\n\nexport const {\n useValue: useRouterBasename,\n setValue: setRouterBasename,\n addEventHandler: addRouterBasenameEventHandler,\n} = makePHEventFunctions(\"routerBasename\");\n\nexport const {\n useValue: useVersion,\n setValue: setVersion,\n addEventHandler: addVersionEventHandler,\n} = makePHEventFunctions(\"version\");\n\nexport const {\n useValue: useRequiresHardRefresh,\n setValue: setRequiresHardRefresh,\n addEventHandler: addRequiresHardRefreshEventHandler,\n} = makePHEventFunctions(\"requiresHardRefresh\");\n\nexport const {\n useValue: useWarnOutdatedApp,\n setValue: setWarnOutdatedApp,\n addEventHandler: addWarnOutdatedAppEventHandler,\n} = makePHEventFunctions(\"warnOutdatedApp\");\n\nexport const {\n useValue: useStudioMode,\n setValue: setStudioMode,\n addEventHandler: addStudioModeEventHandler,\n} = makePHEventFunctions(\"studioMode\");\n\nexport const {\n useValue: useBasePath,\n setValue: setBasePath,\n addEventHandler: addBasePathEventHandler,\n} = makePHEventFunctions(\"basePath\");\n\nexport const {\n useValue: useVersionCheckInterval,\n setValue: setVersionCheckInterval,\n addEventHandler: addVersionCheckIntervalEventHandler,\n} = makePHEventFunctions(\"versionCheckInterval\");\n\nexport const {\n useValue: useCliVersion,\n setValue: setCliVersion,\n addEventHandler: addCliVersionEventHandler,\n} = makePHEventFunctions(\"cliVersion\");\n\nexport const {\n useValue: useFileUploadOperationsChunkSize,\n setValue: setFileUploadOperationsChunkSize,\n addEventHandler: addFileUploadOperationsChunkSizeEventHandler,\n} = makePHEventFunctions(\"fileUploadOperationsChunkSize\");\n\nexport const {\n useValue: useIsDocumentModelSelectionSettingsEnabled,\n setValue: setIsDocumentModelSelectionSettingsEnabled,\n addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler,\n} = makePHEventFunctions(\"isDocumentModelSelectionSettingsEnabled\");\n\nexport const {\n useValue: useGaTrackingId,\n setValue: setGaTrackingId,\n addEventHandler: addGaTrackingIdEventHandler,\n} = makePHEventFunctions(\"gaTrackingId\");\n\nexport const {\n useValue: useDefaultDrivesUrl,\n setValue: setDefaultDrivesUrl,\n addEventHandler: addDefaultDrivesUrlEventHandler,\n} = makePHEventFunctions(\"defaultDrivesUrl\");\n\nexport const {\n useValue: useDrivesPreserveStrategy,\n setValue: setDrivesPreserveStrategy,\n addEventHandler: addDrivesPreserveStrategyEventHandler,\n} = makePHEventFunctions(\"drivesPreserveStrategy\");\n\nexport const {\n useValue: useIsLocalDrivesEnabled,\n setValue: setIsLocalDrivesEnabled,\n addEventHandler: addIsLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsAddDriveEnabled,\n setValue: setIsAddDriveEnabled,\n addEventHandler: addIsAddDriveEnabledEventHandler,\n} = makePHEventFunctions(\"isAddDriveEnabled\");\n\nexport const {\n useValue: useIsPublicDrivesEnabled,\n setValue: setIsPublicDrivesEnabled,\n addEventHandler: addIsPublicDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isPublicDrivesEnabled\");\n\nexport const {\n useValue: useIsAddPublicDrivesEnabled,\n setValue: setIsAddPublicDrivesEnabled,\n addEventHandler: addIsAddPublicDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isAddPublicDrivesEnabled\");\n\nexport const {\n useValue: useIsDeletePublicDrivesEnabled,\n setValue: setIsDeletePublicDrivesEnabled,\n addEventHandler: addIsDeletePublicDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isDeletePublicDrivesEnabled\");\n\nexport const {\n useValue: useIsCloudDrivesEnabled,\n setValue: setIsCloudDrivesEnabled,\n addEventHandler: addIsCloudDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isCloudDrivesEnabled\");\n\nexport const {\n useValue: useIsAddCloudDrivesEnabled,\n setValue: setIsAddCloudDrivesEnabled,\n addEventHandler: addIsAddCloudDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isAddCloudDrivesEnabled\");\n\nexport const {\n useValue: useIsDeleteCloudDrivesEnabled,\n setValue: setIsDeleteCloudDrivesEnabled,\n addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isDeleteCloudDrivesEnabled\");\n\nexport const {\n useValue: useLocalDrivesEnabled,\n setValue: setLocalDrivesEnabled,\n addEventHandler: addLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsAddLocalDrivesEnabled,\n setValue: setIsAddLocalDrivesEnabled,\n addEventHandler: addIsAddLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isAddLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsDeleteLocalDrivesEnabled,\n setValue: setIsDeleteLocalDrivesEnabled,\n addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler,\n} = makePHEventFunctions(\"isDeleteLocalDrivesEnabled\");\n\nexport const {\n useValue: useIsEditorDebugModeEnabled,\n setValue: setIsEditorDebugModeEnabled,\n addEventHandler: addIsEditorDebugModeEnabledEventHandler,\n} = makePHEventFunctions(\"isEditorDebugModeEnabled\");\n\nexport const {\n useValue: useIsEditorReadModeEnabled,\n setValue: setIsEditorReadModeEnabled,\n addEventHandler: addIsEditorReadModeEnabledEventHandler,\n} = makePHEventFunctions(\"isEditorReadModeEnabled\");\n\nexport const {\n useValue: useIsAnalyticsDatabaseWorkerEnabled,\n setValue: setIsAnalyticsDatabaseWorkerEnabled,\n addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n} = makePHEventFunctions(\"isAnalyticsDatabaseWorkerEnabled\");\n\nexport const {\n useValue: useIsDiffAnalyticsEnabled,\n setValue: setIsDiffAnalyticsEnabled,\n addEventHandler: addIsDiffAnalyticsEnabledEventHandler,\n} = makePHEventFunctions(\"isDiffAnalyticsEnabled\");\n\nexport const {\n useValue: useIsDriveAnalyticsEnabled,\n setValue: setIsDriveAnalyticsEnabled,\n addEventHandler: addIsDriveAnalyticsEnabledEventHandler,\n} = makePHEventFunctions(\"isDriveAnalyticsEnabled\");\n\nexport const {\n useValue: useRenownUrl,\n setValue: setRenownUrl,\n addEventHandler: addRenownUrlEventHandler,\n} = makePHEventFunctions(\"renownUrl\");\n\nexport const {\n useValue: useRenownNetworkId,\n setValue: setRenownNetworkId,\n addEventHandler: addRenownNetworkIdEventHandler,\n} = makePHEventFunctions(\"renownNetworkId\");\n\nexport const {\n useValue: useRenownChainId,\n setValue: setRenownChainId,\n addEventHandler: addRenownChainIdEventHandler,\n} = makePHEventFunctions(\"renownChainId\");\n\nexport const {\n useValue: useSentryRelease,\n setValue: setSentryRelease,\n addEventHandler: addSentryReleaseEventHandler,\n} = makePHEventFunctions(\"sentryRelease\");\n\nexport const {\n useValue: useSentryDsn,\n setValue: setSentryDsn,\n addEventHandler: addSentryDsnEventHandler,\n} = makePHEventFunctions(\"sentryDsn\");\n\nexport const {\n useValue: useSentryEnv,\n setValue: setSentryEnv,\n addEventHandler: addSentryEnvEventHandler,\n} = makePHEventFunctions(\"sentryEnv\");\n\nexport const {\n useValue: useIsSentryTracingEnabled,\n setValue: setIsSentryTracingEnabled,\n addEventHandler: addIsSentryTracingEnabledEventHandler,\n} = makePHEventFunctions(\"isSentryTracingEnabled\");\n\nexport const {\n useValue: useIsExternalProcessorsEnabled,\n setValue: setIsExternalProcessorsEnabled,\n addEventHandler: addIsExternalProcessorsEnabledEventHandler,\n} = makePHEventFunctions(\"isExternalProcessorsEnabled\");\n\nexport const {\n useValue: useIsExternalPackagesEnabled,\n setValue: setIsExternalPackagesEnabled,\n addEventHandler: addIsExternalPackagesEnabledEventHandler,\n} = makePHEventFunctions(\"isExternalPackagesEnabled\");\n\nconst enabledEditorsEventFunctions = makePHEventFunctions(\"enabledEditors\");\n\n/** Sets the enabled editors for Connect. */\nexport const setEnabledEditors = enabledEditorsEventFunctions.setValue;\n\n/** Gets the enabled editors for Connect. */\nexport const useEnabledEditors = enabledEditorsEventFunctions.useValue;\n\n/** Adds an event handler for when the enabled editors for Connect changes. */\nexport const addEnabledEditorsEventHandler =\n enabledEditorsEventFunctions.addEventHandler;\n\nconst disabledEditorsEventFunctions = makePHEventFunctions(\"disabledEditors\");\n\n/** Sets the disabled editors for Connect. */\nexport const setDisabledEditors = disabledEditorsEventFunctions.setValue;\n\n/** Gets the disabled editors for Connect. */\nexport const useDisabledEditors = disabledEditorsEventFunctions.useValue;\n\n/** Adds an event handler for when the disabled editors for Connect changes. */\nexport const addDisabledEditorsEventHandler =\n disabledEditorsEventFunctions.addEventHandler;\n\nconst isRelationalProcessorsEnabled = makePHEventFunctions(\n \"isRelationalProcessorsEnabled\",\n);\n\n/** Sets the isRelationalProcessorsEnabled for Connect. */\nexport const setIsRelationalProcessorsEnabled =\n isRelationalProcessorsEnabled.setValue;\n\n/** Gets the isRelationalProcessorsEnabled for Connect. */\nexport const useIsRelationalProcessorsEnabled =\n isRelationalProcessorsEnabled.useValue;\n\n/** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */\nexport const addIsRelationalProcessorsEnabledEventHandler =\n isRelationalProcessorsEnabled.addEventHandler;\n\nconst isExternalRelationalProcessorsEnabled = makePHEventFunctions(\n \"isExternalRelationalProcessorsEnabled\",\n);\n\n/** Sets the isExternalRelationalProcessorsEnabled for Connect. */\nexport const setIsExternalRelationalProcessorsEnabled =\n isExternalRelationalProcessorsEnabled.setValue;\n\n/** Gets the isExternalRelationalProcessorsEnabled for Connect. */\nexport const useIsExternalRelationalProcessorsEnabled =\n isExternalRelationalProcessorsEnabled.useValue;\n\n/** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */\nexport const addIsExternalRelationalProcessorsEnabledEventHandler =\n isExternalRelationalProcessorsEnabled.addEventHandler;\n\nconst isAnalyticsEnabledEventFunctions =\n makePHEventFunctions(\"isAnalyticsEnabled\");\n\n/** Sets the isAnalyticsEnabled for Connect. */\nexport const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;\n\n/** Gets the isAnalyticsEnabled for Connect. */\nexport const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;\n\n/** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */\nexport const addIsAnalyticsEnabledEventHandler =\n isAnalyticsEnabledEventFunctions.addEventHandler;\n\nconst isAnalyticsExternalProcessorsEnabled = makePHEventFunctions(\n \"isAnalyticsExternalProcessorsEnabled\",\n);\n\n/** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */\nexport const setIsAnalyticsExternalProcessorsEnabled =\n isAnalyticsExternalProcessorsEnabled.setValue;\n\n/** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */\nexport const useIsAnalyticsExternalProcessorsEnabled =\n isAnalyticsExternalProcessorsEnabled.useValue;\n\n/** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */\nexport const addIsAnalyticsExternalProcessorsEnabledEventHandler =\n isAnalyticsExternalProcessorsEnabled.addEventHandler;\n\nconst analyticsDatabaseNameEventFunctions = makePHEventFunctions(\n \"analyticsDatabaseName\",\n);\n\n/** Sets the analytics database name for Connect. */\nexport const setAnalyticsDatabaseName =\n analyticsDatabaseNameEventFunctions.setValue;\n\n/** Gets the analytics database name for Connect. */\nexport const useAnalyticsDatabaseName =\n analyticsDatabaseNameEventFunctions.useValue;\n\n/** Adds an event handler for when the analytics database name for Connect changes. */\nexport const addAnalyticsDatabaseNameEventHandler =\n analyticsDatabaseNameEventFunctions.addEventHandler;\n\nconst logLevelEventFunctions = makePHEventFunctions(\"logLevel\");\n\n/** Sets the log level for Connect. */\nexport const setLogLevel = logLevelEventFunctions.setValue;\n\n/** Gets the log level for Connect. */\nexport const useLogLevel = logLevelEventFunctions.useValue;\n\n/** Adds an event handler for when the log level for Connect changes. */\nexport const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;\n\nconst allowListEventFunctions = makePHEventFunctions(\"allowList\");\n\n/** Sets the allow list for Connect. */\nexport const setAllowList = allowListEventFunctions.setValue;\n\n/** Gets the allow list for Connect. */\nexport const useAllowList = allowListEventFunctions.useValue;\n\n/** Adds an event handler for when the allow list for Connect changes. */\nexport const addAllowListEventHandler = allowListEventFunctions.addEventHandler;\n\ntype NonUserConfigKey = Exclude<\n PHGlobalConfigKey,\n PHAppConfigKey | PHDocumentEditorConfigKey\n>;\ntype NonUserConfigSetters = PHGlobalConfigSettersForKey<NonUserConfigKey>;\ntype NonUserConfigHooks = PHGlobalConfigHooksForKey<NonUserConfigKey>;\n\nconst nonUserConfigSetters: NonUserConfigSetters = {\n routerBasename: setRouterBasename,\n version: setVersion,\n requiresHardRefresh: setRequiresHardRefresh,\n warnOutdatedApp: setWarnOutdatedApp,\n studioMode: setStudioMode,\n basePath: setBasePath,\n versionCheckInterval: setVersionCheckInterval,\n cliVersion: setCliVersion,\n fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,\n isDocumentModelSelectionSettingsEnabled:\n setIsDocumentModelSelectionSettingsEnabled,\n gaTrackingId: setGaTrackingId,\n defaultDrivesUrl: setDefaultDrivesUrl,\n drivesPreserveStrategy: setDrivesPreserveStrategy,\n isLocalDrivesEnabled: setIsLocalDrivesEnabled,\n isAddDriveEnabled: setIsAddDriveEnabled,\n isPublicDrivesEnabled: setIsPublicDrivesEnabled,\n isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,\n isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,\n isCloudDrivesEnabled: setIsCloudDrivesEnabled,\n isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,\n isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,\n isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,\n isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,\n isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,\n isEditorReadModeEnabled: setIsEditorReadModeEnabled,\n isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,\n isExternalRelationalProcessorsEnabled:\n setIsExternalRelationalProcessorsEnabled,\n isAnalyticsEnabled: setIsAnalyticsEnabled,\n analyticsDatabaseName: setAnalyticsDatabaseName,\n isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,\n isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,\n isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,\n isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,\n renownUrl: setRenownUrl,\n renownNetworkId: setRenownNetworkId,\n renownChainId: setRenownChainId,\n sentryRelease: setSentryRelease,\n sentryDsn: setSentryDsn,\n sentryEnv: setSentryEnv,\n isSentryTracingEnabled: setIsSentryTracingEnabled,\n isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,\n isExternalPackagesEnabled: setIsExternalPackagesEnabled,\n allowList: setAllowList,\n logLevel: setLogLevel,\n disabledEditors: setDisabledEditors,\n enabledEditors: setEnabledEditors,\n};\n\nexport const phGlobalConfigSetters: PHGlobalConfigSetters = {\n ...phAppConfigSetters,\n ...phDocumentEditorConfigSetters,\n ...nonUserConfigSetters,\n};\n\nconst nonUserConfigHooks: NonUserConfigHooks = {\n routerBasename: useRouterBasename,\n version: useVersion,\n requiresHardRefresh: useRequiresHardRefresh,\n warnOutdatedApp: useWarnOutdatedApp,\n studioMode: useStudioMode,\n basePath: useBasePath,\n versionCheckInterval: useVersionCheckInterval,\n cliVersion: useCliVersion,\n fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,\n isDocumentModelSelectionSettingsEnabled:\n useIsDocumentModelSelectionSettingsEnabled,\n gaTrackingId: useGaTrackingId,\n defaultDrivesUrl: useDefaultDrivesUrl,\n drivesPreserveStrategy: useDrivesPreserveStrategy,\n isAddDriveEnabled: useIsAddDriveEnabled,\n isPublicDrivesEnabled: useIsPublicDrivesEnabled,\n isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,\n isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,\n isCloudDrivesEnabled: useIsCloudDrivesEnabled,\n isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,\n isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,\n isLocalDrivesEnabled: useIsLocalDrivesEnabled,\n isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,\n isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,\n isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,\n isEditorReadModeEnabled: useIsEditorReadModeEnabled,\n isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,\n isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,\n isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,\n renownUrl: useRenownUrl,\n renownNetworkId: useRenownNetworkId,\n renownChainId: useRenownChainId,\n sentryRelease: useSentryRelease,\n sentryDsn: useSentryDsn,\n sentryEnv: useSentryEnv,\n isSentryTracingEnabled: useIsSentryTracingEnabled,\n isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,\n isExternalPackagesEnabled: useIsExternalPackagesEnabled,\n allowList: useAllowList,\n isAnalyticsEnabled: useIsAnalyticsEnabled,\n isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,\n isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,\n isExternalRelationalProcessorsEnabled:\n useIsExternalRelationalProcessorsEnabled,\n analyticsDatabaseName: useAnalyticsDatabaseName,\n logLevel: useLogLevel,\n disabledEditors: useDisabledEditors,\n enabledEditors: useEnabledEditors,\n};\n\nexport const phGlobalConfigHooks: PHGlobalConfigHooks = {\n ...phAppConfigHooks,\n ...phDocumentEditorConfigHooks,\n ...nonUserConfigHooks,\n};\n","import type {\n AddPHGlobalEventHandler,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"../types/global.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst featuresEventFunctions = makePHEventFunctions(\"features\");\n\nexport const useFeatures: UsePHGlobalValue<Map<string, boolean>> =\n featuresEventFunctions.useValue;\n\nexport const setFeatures: SetPHGlobalValue<Map<string, boolean>> =\n featuresEventFunctions.setValue;\n\nexport const addFeaturesEventHandler: AddPHGlobalEventHandler =\n featuresEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst packageDiscoveryFunctions = makePHEventFunctions(\n \"packageDiscoveryService\",\n);\n\nexport const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;\nexport const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;\nexport const addPackageDiscoveryServiceEventHandler =\n packageDiscoveryFunctions.addEventHandler;\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 { PHModal } from \"@powerhousedao/reactor-browser\";\nimport type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst modalEventFunctions = makePHEventFunctions(\"modal\");\n\n/** Returns the current modal */\nexport const usePHModal = modalEventFunctions.useValue;\n\n/** Sets the current modal */\nexport const setPHModal = modalEventFunctions.setValue;\n\n/** Adds an event handler for the modal */\nexport const addModalEventHandler = modalEventFunctions.addEventHandler;\n\n/** Shows a modal */\nexport function showPHModal(modal: PHModal) {\n setPHModal(modal);\n}\n\n/** Closes the current modal */\nexport function closePHModal() {\n setPHModal(undefined);\n}\n\n/** Shows the create document modal */\nexport function showCreateDocumentModal(documentType: string) {\n setPHModal({ type: \"createDocument\", documentType });\n}\n\n/** Shows the delete node modal */\nexport function showDeleteNodeModal(nodeOrId: Node | string) {\n const id = typeof nodeOrId === \"string\" ? nodeOrId : nodeOrId.id;\n setPHModal({ type: \"deleteItem\", id });\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport type {\n Database,\n IDocumentModelRegistry,\n IReactorClient,\n ISyncManager,\n} from \"@powerhousedao/reactor\";\nimport type {\n AddPHGlobalEventHandler,\n BrowserReactorClientModule,\n SetPHGlobalValue,\n UsePHGlobalValue,\n} from \"@powerhousedao/reactor-browser\";\nimport type { Kysely } from \"kysely\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst reactorClientModuleEventFunctions = makePHEventFunctions(\n \"reactorClientModule\",\n);\nconst reactorClientEventFunctions = makePHEventFunctions(\"reactorClient\");\n\n/** Returns the reactor client module */\nexport const useReactorClientModule: UsePHGlobalValue<BrowserReactorClientModule> =\n reactorClientModuleEventFunctions.useValue;\n\n/** Sets the reactor client module */\nexport const setReactorClientModule: SetPHGlobalValue<BrowserReactorClientModule> =\n reactorClientModuleEventFunctions.setValue;\n\n/** Adds an event handler for the reactor client module */\nexport const addReactorClientModuleEventHandler: AddPHGlobalEventHandler =\n reactorClientModuleEventFunctions.addEventHandler;\n\n/** Returns the reactor client */\nexport const useReactorClient: UsePHGlobalValue<IReactorClient> =\n reactorClientEventFunctions.useValue;\n\n/** Sets the reactor client */\nexport const setReactorClient: SetPHGlobalValue<IReactorClient> =\n reactorClientEventFunctions.setValue;\n\n/** Adds an event handler for the reactor client */\nexport const addReactorClientEventHandler: AddPHGlobalEventHandler =\n reactorClientEventFunctions.addEventHandler;\n\n// The following are derived from the reactor client module:\n\nexport const useSync = (): ISyncManager | undefined =>\n useReactorClientModule()?.reactorModule?.syncModule?.syncManager;\n\nexport const useSyncList = () => {\n const sync = useSync();\n return sync?.list() ?? [];\n};\n\nexport const useModelRegistry = (): IDocumentModelRegistry | undefined =>\n useReactorClientModule()?.reactorModule?.documentModelRegistry;\n\nexport const useDatabase = (): Kysely<Database> | undefined =>\n useReactorClientModule()?.reactorModule?.database;\n\nexport const usePGlite = (): PGlite | undefined => useReactorClientModule()?.pg;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst revisionHistoryEventFunctions = makePHEventFunctions(\n \"revisionHistoryVisible\",\n);\n\n/** Returns whether revision history is visible */\nexport const useRevisionHistoryVisible = revisionHistoryEventFunctions.useValue;\n\n/** Sets revision history visibility */\nexport const setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;\n\n/** Adds event handler for revision history visibility */\nexport const addRevisionHistoryVisibleEventHandler =\n revisionHistoryEventFunctions.addEventHandler;\n\n/** Shows the revision history */\nexport function showRevisionHistory() {\n setRevisionHistoryVisible(true);\n}\n\n/** Hides the revision history */\nexport function hideRevisionHistory() {\n setRevisionHistoryVisible(false);\n}\n","import type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport slug from \"slug\";\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/** Makes a URL component for a node. */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n const nodeName = node.name;\n if (!nodeName) return slug(node.id);\n return slug(`${nodeName}-${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\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n const nodeId = findUuid(nodeSlug);\n return nodeId;\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 const driveId = findUuid(driveSlug);\n return driveId;\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 { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport {\n createUrlWithPreservedParams,\n extractDriveIdFromPath,\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\";\n\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n\n/** Returns the selected drive id */\nexport const useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n\n/** Sets the selected drive id */\nconst 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 // Find the drive by slug to get its actual ID\n const drive = window.ph?.drives?.find((d) => d.header.slug === driveSlug);\n const driveId = drive?.header.id;\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\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 {\n createUrlWithPreservedParams,\n extractDriveSlugFromPath,\n extractNodeIdFromSlug,\n extractNodeSlugFromPath,\n makeNodeSlug,\n resolveUrlPathname,\n} from \"../utils/url.js\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\nconst setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\nexport const addSelectedNodeIdEventHandler =\n selectedNodeIdEventFunctions.addEventHandler;\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\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 const selectedNodeId = window.ph?.selectedNodeId;\n if (nodeSlug !== selectedNodeId) {\n setSelectedNode(nodeSlug);\n }\n });\n}\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedTimelineItemEventFunctions = makePHEventFunctions(\n \"selectedTimelineItem\",\n);\n\n/** Returns the selected timeline item */\nexport const useSelectedTimelineItem =\n selectedTimelineItemEventFunctions.useValue;\n\n/** Sets the selected timeline item */\nexport const setSelectedTimelineItem =\n selectedTimelineItemEventFunctions.setValue;\n\n/** Adds event handler for selected timeline item */\nexport const addSelectedTimelineItemEventHandler =\n selectedTimelineItemEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst selectedTimelineRevisionEventFunctions = makePHEventFunctions(\n \"selectedTimelineRevision\",\n);\n\n/** Returns the selected timeline revision. */\nexport const useSelectedTimelineRevision =\n selectedTimelineRevisionEventFunctions.useValue;\n\n/** Sets the selected timeline revision. */\nexport const setSelectedTimelineRevision =\n selectedTimelineRevisionEventFunctions.setValue;\n\n/** Adds an event handler for the selected timeline revision. */\nexport const addSelectedTimelineRevisionEventHandler =\n selectedTimelineRevisionEventFunctions.addEventHandler;\n","import { makePHEventFunctions } from \"./make-ph-event-functions.js\";\n\nconst toastEventFunctions = makePHEventFunctions(\"toast\");\n\n/** Returns the toast function */\nexport const usePHToast = toastEventFunctions.useValue;\n\n/** Sets the toast function */\nexport const setPHToast = toastEventFunctions.setValue;\n\n/** Adds an event handler for the toast */\nexport const addToastEventHandler = toastEventFunctions.addEventHandler;\n","import { DuplicateModuleError } from \"@powerhousedao/reactor\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { useSyncExternalStore } from \"react\";\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\n/** Returns all of the Vetra packages loaded by the Connect instance */\nexport const useVetraPackages = () => {\n const packageManager = useVetraPackageManager();\n\n return useSyncExternalStore(\n (cb) => (packageManager ? packageManager.subscribe(cb) : () => {}),\n () => packageManager?.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 packageManager.subscribe(({ packages }) => {\n updateReactorClientDocumentModels(packages);\n });\n}\n\nfunction updateReactorClientDocumentModels(packages: DocumentModelLib[]) {\n const documentModelModules = packages.flatMap((pkg) => pkg.documentModels);\n\n const registry =\n window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n if (!registry || documentModelModules.length === 0) return;\n\n for (const module of documentModelModules) {\n try {\n registry.registerModules(module);\n } catch (error) {\n if (DuplicateModuleError.isError(error)) {\n const documentType = module.documentModel.global.id;\n registry.unregisterModules(documentType);\n registry.registerModules(module);\n continue;\n }\n throw error;\n }\n }\n}\n","import type { PHGlobalEventHandlerAdders } from \"../types/global.js\";\nimport {\n addAllowListEventHandler,\n addAnalyticsDatabaseNameEventHandler,\n addBasePathEventHandler,\n addCliVersionEventHandler,\n addDefaultDrivesUrlEventHandler,\n addDisabledEditorsEventHandler,\n addDrivesPreserveStrategyEventHandler,\n addEnabledEditorsEventHandler,\n addFileUploadOperationsChunkSizeEventHandler,\n addGaTrackingIdEventHandler,\n addIsAddCloudDrivesEnabledEventHandler,\n addIsAddDriveEnabledEventHandler,\n addIsAddLocalDrivesEnabledEventHandler,\n addIsAddPublicDrivesEnabledEventHandler,\n addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n addIsAnalyticsEnabledEventHandler,\n addIsAnalyticsExternalProcessorsEnabledEventHandler,\n addIsCloudDrivesEnabledEventHandler,\n addIsDeleteCloudDrivesEnabledEventHandler,\n addIsDeleteLocalDrivesEnabledEventHandler,\n addIsDeletePublicDrivesEnabledEventHandler,\n addIsDiffAnalyticsEnabledEventHandler,\n addIsDocumentModelSelectionSettingsEnabledEventHandler,\n addIsDriveAnalyticsEnabledEventHandler,\n addIsEditorDebugModeEnabledEventHandler,\n addIsEditorReadModeEnabledEventHandler,\n addIsExternalPackagesEnabledEventHandler,\n addIsExternalProcessorsEnabledEventHandler,\n addIsExternalRelationalProcessorsEnabledEventHandler,\n addIsLocalDrivesEnabledEventHandler,\n addIsPublicDrivesEnabledEventHandler,\n addIsRelationalProcessorsEnabledEventHandler,\n addIsSentryTracingEnabledEventHandler,\n addLogLevelEventHandler,\n addRenownChainIdEventHandler,\n addRenownNetworkIdEventHandler,\n addRenownUrlEventHandler,\n addRequiresHardRefreshEventHandler,\n addRouterBasenameEventHandler,\n addSentryDsnEventHandler,\n addSentryEnvEventHandler,\n addSentryReleaseEventHandler,\n addStudioModeEventHandler,\n addVersionCheckIntervalEventHandler,\n addVersionEventHandler,\n addWarnOutdatedAppEventHandler,\n} from \"./config/connect.js\";\nimport { addFeaturesEventHandler } from \"./features.js\";\n\nimport {\n addAllowedDocumentTypesEventHandler,\n addIsDragAndDropEnabledEventHandler,\n addIsExternalControlsEnabledEventHandler,\n} from \"./config/editor.js\";\nimport { addDocumentCacheEventHandler } from \"./document-cache.js\";\nimport { addPackageDiscoveryServiceEventHandler } from \"./package-discovery.js\";\nimport { addDrivesEventHandler } from \"./drives.js\";\nimport { addLoadingEventHandler } from \"./loading.js\";\nimport { addModalEventHandler } from \"./modals.js\";\nimport {\n addReactorClientEventHandler,\n addReactorClientModuleEventHandler,\n} from \"./reactor.js\";\nimport { addRenownEventHandler } from \"./renown.js\";\nimport { addRevisionHistoryVisibleEventHandler } from \"./revision-history.js\";\nimport {\n addSelectedDriveIdEventHandler,\n addSetSelectedDriveOnPopStateEventHandler,\n} from \"./selected-drive.js\";\nimport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n addSetSelectedNodeOnPopStateEventHandler,\n} from \"./selected-node.js\";\nimport { addSelectedTimelineItemEventHandler } from \"./selected-timeline-item.js\";\nimport { addSelectedTimelineRevisionEventHandler } from \"./timeline-revision.js\";\nimport { addToastEventHandler } from \"./toast.js\";\nimport { addVetraPackageManagerEventHandler } from \"./vetra-packages.js\";\n\nconst phGlobalEventHandlerRegisterFunctions: PHGlobalEventHandlerAdders = {\n loading: addLoadingEventHandler,\n reactorClientModule: addReactorClientModuleEventHandler,\n reactorClient: addReactorClientEventHandler,\n features: addFeaturesEventHandler,\n modal: addModalEventHandler,\n renown: addRenownEventHandler,\n drives: addDrivesEventHandler,\n documentCache: addDocumentCacheEventHandler,\n selectedDriveId: () => {\n addSelectedDriveIdEventHandler();\n addSetSelectedDriveOnPopStateEventHandler();\n addResetSelectedNodeEventHandler();\n },\n selectedNodeId: () => {\n addSelectedNodeIdEventHandler();\n addSetSelectedNodeOnPopStateEventHandler();\n },\n vetraPackageManager: addVetraPackageManagerEventHandler,\n packageDiscoveryService: addPackageDiscoveryServiceEventHandler,\n selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,\n revisionHistoryVisible: addRevisionHistoryVisibleEventHandler,\n selectedTimelineItem: addSelectedTimelineItemEventHandler,\n routerBasename: addRouterBasenameEventHandler,\n version: addVersionEventHandler,\n logLevel: addLogLevelEventHandler,\n requiresHardRefresh: addRequiresHardRefreshEventHandler,\n warnOutdatedApp: addWarnOutdatedAppEventHandler,\n studioMode: addStudioModeEventHandler,\n basePath: addBasePathEventHandler,\n versionCheckInterval: addVersionCheckIntervalEventHandler,\n cliVersion: addCliVersionEventHandler,\n fileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,\n isDocumentModelSelectionSettingsEnabled:\n addIsDocumentModelSelectionSettingsEnabledEventHandler,\n gaTrackingId: addGaTrackingIdEventHandler,\n allowList: addAllowListEventHandler,\n defaultDrivesUrl: addDefaultDrivesUrlEventHandler,\n drivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,\n allowedDocumentTypes: addAllowedDocumentTypesEventHandler,\n enabledEditors: addEnabledEditorsEventHandler,\n disabledEditors: addDisabledEditorsEventHandler,\n isAddDriveEnabled: addIsAddDriveEnabledEventHandler,\n isLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,\n isPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,\n isAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,\n isDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,\n isCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,\n isAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,\n isDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,\n isAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,\n isDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,\n isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,\n isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,\n isEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,\n isEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,\n isRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,\n isExternalRelationalProcessorsEnabled:\n addIsExternalRelationalProcessorsEnabledEventHandler,\n isAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,\n isAnalyticsExternalProcessorsEnabled:\n addIsAnalyticsExternalProcessorsEnabledEventHandler,\n analyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,\n isAnalyticsDatabaseWorkerEnabled:\n addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n isDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,\n isDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,\n renownUrl: addRenownUrlEventHandler,\n renownNetworkId: addRenownNetworkIdEventHandler,\n renownChainId: addRenownChainIdEventHandler,\n sentryRelease: addSentryReleaseEventHandler,\n sentryDsn: addSentryDsnEventHandler,\n sentryEnv: addSentryEnvEventHandler,\n isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,\n isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,\n isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,\n toast: addToastEventHandler,\n};\nexport function addPHEventHandlers() {\n for (const fn of Object.values(phGlobalEventHandlerRegisterFunctions)) {\n fn();\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.flatMap((pkg) => pkg.documentModels);\n}\n\nexport function useDocumentModelModuleById(\n id: string | null | undefined,\n): DocumentModelModule | undefined {\n const documentModelModules = useDocumentModelModules();\n return documentModelModules?.find(\n (module) => module.documentModel.global.id === id,\n );\n}\n","import { useAllowedDocumentTypes } from \"./config/editor.js\";\nimport { useDocumentModelModules } from \"./document-model-modules.js\";\n\nexport function useAllowedDocumentModelModules() {\n const documentModelModules = useDocumentModelModules();\n const allowedDocumentTypes = useAllowedDocumentTypes();\n if (!allowedDocumentTypes?.length) return documentModelModules;\n return documentModelModules?.filter((module) =>\n allowedDocumentTypes.includes(module.documentModel.global.id),\n );\n}\n","import type { FolderNode } from \"@powerhousedao/shared/document-drive\";\nimport { isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected folder. */\nexport function useSelectedFolder(): FolderNode | undefined {\n const selectedNode = useSelectedNode();\n if (isFolderNodeKind(selectedNode)) return selectedNode;\n return undefined;\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { sortNodesByName } from \"../utils/nodes.js\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\n\n/** Returns the child nodes for the selected drive or folder. */\nexport function useNodesInSelectedDriveOrFolder(): Node[] {\n const nodes = useNodesInSelectedDrive();\n const selectedFolder = useSelectedFolder();\n const selectedFolderId = selectedFolder?.id;\n if (!nodes) return [];\n if (!selectedFolderId)\n return sortNodesByName(nodes.filter((n) => !n.parentFolder));\n return sortNodesByName(\n nodes.filter((n) => n.parentFolder === selectedFolderId),\n );\n}\n","import type {\n PHAppConfig,\n PHAppConfigKey,\n PHDocumentEditorConfig,\n PHDocumentEditorConfigKey,\n PHGlobalConfig,\n PHGlobalConfigKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { phGlobalConfigSetters } from \"./connect.js\";\nimport { phAppConfigSetters, phDocumentEditorConfigSetters } from \"./editor.js\";\n\nexport function setPHGlobalConfigByKey<TKey extends PHGlobalConfigKey>(\n key: TKey,\n value: PHGlobalConfig[TKey] | undefined,\n) {\n const setter = phGlobalConfigSetters[key];\n setter(value);\n}\n\nexport function setPHAppConfigByKey<TKey extends PHAppConfigKey>(\n key: TKey,\n value: PHAppConfig[TKey] | undefined,\n) {\n const setter = phAppConfigSetters[key];\n setter(value);\n}\n\nexport function setPHDocumentEditorConfigByKey<\n TKey extends PHDocumentEditorConfigKey,\n>(key: TKey, value: PHDocumentEditorConfig[TKey] | undefined) {\n const setter = phDocumentEditorConfigSetters[key];\n setter(value);\n}\n","import type {\n PHGlobalConfig,\n PHGlobalConfigKey,\n PHGlobalConfigSetters,\n} from \"@powerhousedao/reactor-browser\";\nimport { phGlobalConfigSetters } from \"./connect.js\";\n\nexport function callGlobalSetterForKey<TKey extends PHGlobalConfigKey>(\n key: TKey,\n value: PHGlobalConfig[TKey] | undefined,\n) {\n const setter = phGlobalConfigSetters[key] as PHGlobalConfigSetters[TKey];\n setter(value);\n}\n","import type {\n PHAppConfig,\n PHAppConfigKey,\n PHDocumentEditorConfig,\n PHDocumentEditorConfigKey,\n PHGlobalConfig,\n PHGlobalConfigKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useState } from \"react\";\nimport { callGlobalSetterForKey } from \"./utils.js\";\n\nexport function setDefaultPHGlobalConfig(config: PHGlobalConfig) {\n for (const key of Object.keys(config) as PHGlobalConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\nexport function useSetDefaultPHGlobalConfig(config: PHGlobalConfig) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setDefaultPHGlobalConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n\nexport function useResetPHGlobalConfig(defaultConfigForReset: PHGlobalConfig) {\n return function reset() {\n setPHGlobalConfig(defaultConfigForReset);\n };\n}\n\nexport function setPHGlobalConfig(config: Partial<PHGlobalConfig>) {\n for (const key of Object.keys(config) as PHGlobalConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\nexport function useSetPHGlobalConfig(config: Partial<PHGlobalConfig>) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setPHGlobalConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n\n/** Sets the global drive config.\n *\n * Pass in a partial object of the global drive config to set.\n */\nexport function setPHAppConfig(config: Partial<PHAppConfig>) {\n for (const key of Object.keys(config) as PHAppConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\n/** Sets the global document config.\n *\n * Pass in a partial object of the global document config to set.\n */\nexport function setPHDocumentEditorConfig(\n config: Partial<PHDocumentEditorConfig>,\n) {\n for (const key of Object.keys(config) as PHDocumentEditorConfigKey[]) {\n callGlobalSetterForKey(key, config[key]);\n }\n}\n\n/** Wrapper hook for setting the global app config.\n *\n * Automatically sets the global app config when the component mounts.\n *\n * Pass in a partial object of the global app config to set.\n */\nexport function useSetPHAppConfig(config: Partial<PHAppConfig>) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setPHAppConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n\n/** Wrapper hook for setting the global document editor config.\n *\n * Automatically sets the global document editor config when the component mounts.\n *\n * Pass in a partial object of the global document editor config to set.\n */\nexport function useSetPHDocumentEditorConfig(\n config: Partial<PHDocumentEditorConfig>,\n) {\n const [isInitialized, setIsInitialized] = useState(false);\n\n useEffect(() => {\n if (isInitialized) return;\n setPHDocumentEditorConfig(config);\n setIsInitialized(true);\n }, [config, isInitialized]);\n}\n","import type {\n PHAppConfigKey,\n PHDocumentEditorConfigKey,\n PHGlobalConfigKey,\n} from \"@powerhousedao/reactor-browser\";\nimport { phGlobalConfigHooks } from \"./connect.js\";\nimport { phAppConfigHooks, phDocumentEditorConfigHooks } from \"./editor.js\";\n\nexport function usePHGlobalConfigByKey<TKey extends PHGlobalConfigKey>(\n key: TKey,\n) {\n const useValueHook = phGlobalConfigHooks[key];\n return useValueHook();\n}\n\n/** Gets the value of an item in the global drive config for a given key.\n *\n * Strongly typed, inferred from type definition for the key.\n */\nexport function usePHAppConfigByKey<TKey extends PHAppConfigKey>(key: TKey) {\n const useValueHook = phAppConfigHooks[key];\n return useValueHook();\n}\n\n/** Gets the value of an item in the global document config for a given key.\n *\n * Strongly typed, inferred from type definition for the key.\n */\nexport function usePHDocumentEditorConfigByKey<\n TKey extends PHDocumentEditorConfigKey,\n>(key: TKey) {\n const useValueHook = phDocumentEditorConfigHooks[key];\n return useValueHook();\n}\n","import type { ConnectionStateSnapshot } from \"@powerhousedao/reactor\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useSync } from \"./reactor.js\";\n\n/**\n * Returns a map of remote name to connection state snapshot for all remotes.\n * Re-renders when any remote's connection state changes.\n */\nexport function useConnectionStates(): ReadonlyMap<\n string,\n ConnectionStateSnapshot\n> {\n const syncManager = useSync();\n const [states, setStates] = useState<\n ReadonlyMap<string, ConnectionStateSnapshot>\n >(() => buildSnapshot(syncManager));\n const unsubscribesRef = useRef<Array<() => void>>([]);\n\n useEffect(() => {\n if (!syncManager) return;\n\n function subscribe() {\n // Clean up previous subscriptions\n for (const unsub of unsubscribesRef.current) {\n unsub();\n }\n unsubscribesRef.current = [];\n\n const remotes = syncManager!.list();\n for (const remote of remotes) {\n const unsub = remote.channel.onConnectionStateChange(() => {\n setStates(buildSnapshot(syncManager));\n });\n unsubscribesRef.current.push(unsub);\n }\n\n // Set initial state\n setStates(buildSnapshot(syncManager));\n }\n\n subscribe();\n\n // Re-subscribe periodically to pick up added/removed remotes\n const interval = setInterval(subscribe, 5000);\n\n return () => {\n clearInterval(interval);\n for (const unsub of unsubscribesRef.current) {\n unsub();\n }\n unsubscribesRef.current = [];\n };\n }, [syncManager]);\n\n return states;\n}\n\n/**\n * Returns the connection state snapshot for a specific remote by name.\n */\nexport function useConnectionState(\n remoteName: string,\n): ConnectionStateSnapshot | undefined {\n const states = useConnectionStates();\n return states.get(remoteName);\n}\n\nfunction buildSnapshot(\n syncManager: ReturnType<typeof useSync>,\n): ReadonlyMap<string, ConnectionStateSnapshot> {\n const map = new Map<string, ConnectionStateSnapshot>();\n if (!syncManager) return map;\n for (const remote of syncManager.list()) {\n map.set(remote.name, remote.channel.getConnectionState());\n }\n return map;\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useReactorClient } from \"./reactor.js\";\n\ntype InternalState = {\n globalOperations: Operation[];\n localOperations: Operation[];\n isLoading: boolean;\n error: Error | undefined;\n};\n\ntype DocumentOperationsState = InternalState & {\n refetch: () => void;\n};\n\n/**\n * Hook to fetch document operations via the reactor client.\n * Operations are no longer auto-populated on documents and must be fetched explicitly.\n *\n * @param documentId - The document ID to fetch operations for\n * @returns Object containing globalOperations, localOperations, isLoading, and error\n */\nexport function useDocumentOperations(\n documentId: string | null | undefined,\n): DocumentOperationsState {\n const reactorClient = useReactorClient();\n const hasFetchedRef = useRef(false);\n const [state, setState] = useState<InternalState>(() => ({\n globalOperations: [],\n localOperations: [],\n isLoading: !!documentId,\n error: undefined,\n }));\n\n const fetchOperations = useCallback(\n async (retryCount = 0): Promise<void> => {\n const MAX_RETRIES = 5;\n const RETRY_DELAY_MS = 500;\n\n if (!documentId || !reactorClient) {\n setState({\n globalOperations: [],\n localOperations: [],\n isLoading: false,\n error: undefined,\n });\n return;\n }\n\n setState((prev) => ({ ...prev, isLoading: true, error: undefined }));\n\n let globalOps: Operation[] = [];\n let localOps: Operation[] = [];\n let fetchError: Error | undefined;\n\n try {\n const globalResult = await reactorClient.getOperations(documentId, {\n scopes: [\"global\"],\n });\n globalOps = globalResult.results;\n } catch (err) {\n fetchError = err instanceof Error ? err : new Error(String(err));\n }\n\n if (!fetchError) {\n try {\n const localResult = await reactorClient.getOperations(documentId, {\n scopes: [\"local\"],\n });\n localOps = localResult.results;\n } catch (err) {\n fetchError = err instanceof Error ? err : new Error(String(err));\n }\n }\n\n // If no operations found and we haven't exhausted retries, wait and try again\n // This handles eventual consistency where operations may not be immediately available\n if (\n !fetchError &&\n globalOps.length === 0 &&\n localOps.length === 0 &&\n retryCount < MAX_RETRIES\n ) {\n await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));\n return fetchOperations(retryCount + 1);\n }\n\n setState({\n globalOperations: globalOps,\n localOperations: localOps,\n isLoading: false,\n error: fetchError,\n });\n hasFetchedRef.current = true;\n },\n [documentId, reactorClient],\n );\n\n useEffect(() => {\n if (documentId && reactorClient) {\n void fetchOperations();\n } else if (!documentId) {\n setState({\n globalOperations: [],\n localOperations: [],\n isLoading: false,\n error: undefined,\n });\n hasFetchedRef.current = false;\n }\n }, [documentId, reactorClient, fetchOperations]);\n\n // Wrap fetchOperations to hide the internal retry parameter\n const refetch = useCallback(() => {\n void fetchOperations(0);\n }, [fetchOperations]);\n\n return { ...state, refetch };\n}\n","import { useDocumentModelModules } from \"./document-model-modules.js\";\n\n/** Returns the supported document types for the reactor (derived from the document model modules) */\nexport function useSupportedDocumentTypesInReactor() {\n const documentModelModules = useDocumentModelModules();\n return documentModelModules?.map((module) => module.documentModel.global.id);\n}\n","import { useAllowedDocumentTypes } from \"./config/editor.js\";\nimport { useSupportedDocumentTypesInReactor } from \"./supported-document-types.js\";\n\n/** Returns the document types a app supports.\n *\n * If present, uses the `allowedDocumentTypes` config value.\n * Otherwise, uses the supported document types from the reactor.\n */\nexport function useDocumentTypes() {\n const allowedDocumentTypes = useAllowedDocumentTypes();\n const supportedDocumentTypes = useSupportedDocumentTypesInReactor();\n return allowedDocumentTypes ?? supportedDocumentTypes;\n}\n","import type {\n DocumentDriveAction,\n DocumentDriveDocument,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentDispatch } from \"../types/documents.js\";\nimport { useDispatch } from \"./dispatch.js\";\nimport { useDrives } from \"./drives.js\";\n\nexport function useDriveById(\n driveId: string | undefined | null,\n): [DocumentDriveDocument, DocumentDispatch<DocumentDriveAction>] {\n const drives = useDrives();\n const foundDrive = drives?.find((drive) => drive.header.id === driveId);\n const [drive, dispatch] = useDispatch(foundDrive);\n if (!foundDrive) {\n throw new Error(`Drive with id ${driveId} not found`);\n }\n return [drive, dispatch] as [\n DocumentDriveDocument,\n DocumentDispatch<DocumentDriveAction>,\n ];\n}\n","import type { EditorModule } from \"document-model\";\nimport { DEFAULT_DRIVE_EDITOR_ID } from \"../constants.js\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useEditorModules(): EditorModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.editors)\n .filter(\n (module) => !module.documentTypes.includes(\"powerhouse/document-drive\"),\n );\n}\n\nexport function useAppModules(): EditorModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages\n .flatMap((pkg) => pkg.editors)\n .filter((module) =>\n module.documentTypes.includes(\"powerhouse/document-drive\"),\n );\n}\n\nexport function useFallbackEditorModule(\n documentType: string | null | undefined,\n): EditorModule | undefined {\n const editorModules = useEditorModules();\n if (!documentType) return undefined;\n if (editorModules?.length === 0) return undefined;\n\n const modulesForType = editorModules?.filter((module) =>\n module.documentTypes.includes(documentType),\n );\n return modulesForType?.[0];\n}\n\nexport function useAppModuleById(\n id: string | null | undefined,\n): EditorModule | undefined {\n const appModules = useAppModules();\n return appModules?.find((module) => module.config.id === id);\n}\n\nexport function useDefaultAppModule(): EditorModule | undefined {\n const defaultAppModule = useAppModuleById(DEFAULT_DRIVE_EDITOR_ID);\n return defaultAppModule;\n}\n\nexport function useEditorModuleById(\n id: string | null | undefined,\n): EditorModule | undefined {\n const editorModules = useEditorModules();\n return editorModules?.find((module) => module.config.id === id);\n}\n\nexport function useEditorModulesForDocumentType(\n documentType: string | null | undefined,\n) {\n const editorModules = useEditorModules();\n if (!documentType) return undefined;\n\n const modulesForType = editorModules?.filter((module) =>\n module.documentTypes.includes(documentType),\n );\n return modulesForType;\n}\n","import type { FolderNode } from \"@powerhousedao/shared/document-drive\";\nimport { useFolderNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\n\nexport function useFolderById(\n id: string | null | undefined,\n): FolderNode | undefined {\n const folders = useFolderNodesInSelectedDrive();\n return folders?.find((n) => n.id === id);\n}\n","import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport {\n useDocumentsInSelectedDrive,\n useNodesInSelectedDrive,\n} from \"./items-in-selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\n\n/** Returns the nodes in the selected folder. */\nexport function useNodesInSelectedFolder(): Node[] | undefined {\n const selectedFolder = useSelectedFolder();\n const nodes = useNodesInSelectedDrive();\n if (!selectedFolder || !nodes) return undefined;\n\n return nodes.filter((n) => n.parentFolder === selectedFolder.id);\n}\n\n/** Returns the file nodes in the selected folder. */\nexport function useFileNodesInSelectedFolder(): FileNode[] | undefined {\n const nodes = useNodesInSelectedFolder();\n if (!nodes) return undefined;\n return nodes.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected folder. */\nexport function useFolderNodesInSelectedFolder(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedFolder();\n if (!nodes) return undefined;\n return nodes.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected folder. */\nexport function useDocumentsInSelectedFolder(): PHDocument[] | undefined {\n const documents = useDocumentsInSelectedDrive();\n const fileNodes = useFileNodesInSelectedFolder();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return documents?.filter((d) => fileNodeIds?.includes(d.header.id));\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport {\n addFile,\n addFolder,\n copyNode,\n moveNode,\n renameDriveNode,\n renameNode,\n} from \"../actions/document.js\";\nimport { useDrives } from \"./drives.js\";\nimport { useFolderById } from \"./folder-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\nimport { setSelectedNode, useSelectedNode } from \"./selected-node.js\";\n\nfunction resolveNode(driveId: string, node: Node | undefined) {\n return node?.id !== driveId ? node : undefined;\n}\n\nexport function useNodeActions() {\n const [selectedDrive] = useSelectedDriveSafe();\n const selectedFolder = useSelectedFolder();\n const selectedNode = useSelectedNode();\n const selectedParentFolder = useFolderById(selectedNode?.parentFolder);\n const selectedDriveId = selectedDrive?.header.id;\n const drives = useDrives();\n\n async function onAddFile(file: File, parent: Node | undefined) {\n if (!selectedDriveId) return;\n\n const fileName = file.name.replace(/\\..+/gim, \"\");\n\n return addFile(\n file,\n selectedDriveId,\n fileName,\n resolveNode(selectedDriveId, parent)?.id,\n );\n }\n\n async function onAddFolder(name: string, parent: Node | undefined) {\n if (!selectedDriveId) return;\n\n return addFolder(\n selectedDriveId,\n name,\n resolveNode(selectedDriveId, parent)?.id,\n );\n }\n\n async function onRenameNode(\n newName: string,\n node: Node,\n ): Promise<Node | undefined> {\n if (!selectedDriveId) return;\n\n const resolvedNode = resolveNode(selectedDriveId, node);\n if (!resolvedNode) {\n console.error(`Node ${node.id} not found`);\n return;\n }\n\n return await renameNode(selectedDriveId, node.id, newName);\n }\n\n async function onCopyNode(src: Node, target: Node | undefined) {\n if (!selectedDriveId) return;\n const resolvedSrc = resolveNode(selectedDriveId, src);\n if (!resolvedSrc) {\n console.error(`Node ${src.id} not found`);\n return;\n }\n const resolvedTarget = resolveNode(selectedDriveId, target);\n\n await copyNode(selectedDriveId, resolvedSrc, resolvedTarget);\n }\n\n async function onMoveNode(src: Node, target: Node | undefined) {\n if (!selectedDriveId) return;\n\n const resolvedSrc = resolveNode(selectedDriveId, src);\n if (!resolvedSrc) {\n console.error(`Node ${src.id} not found`);\n return;\n }\n const resolvedTarget = resolveNode(selectedDriveId, target);\n\n // if node is already on target then ignore move\n if (\n (!resolvedTarget?.id && !src.parentFolder) ||\n resolvedTarget?.id === src.parentFolder\n ) {\n return;\n }\n await moveNode(selectedDriveId, resolvedSrc, resolvedTarget);\n }\n\n async function onDuplicateNode(src: Node) {\n if (!selectedDriveId) return;\n\n const resolvedSrc = resolveNode(selectedDriveId, src);\n if (!resolvedSrc) {\n console.error(`Node ${src.id} not found`);\n return;\n }\n\n const target = resolveNode(\n selectedDriveId,\n selectedFolder ?? selectedParentFolder,\n );\n await copyNode(selectedDriveId, resolvedSrc, target);\n }\n async function onAddAndSelectNewFolder(name: string) {\n if (!name) return;\n if (!selectedDriveId) return;\n\n const resolvedTarget = resolveNode(\n selectedDriveId,\n selectedFolder ?? selectedParentFolder,\n );\n if (!resolvedTarget) return;\n\n const newFolder = await onAddFolder(name, resolvedTarget);\n\n if (newFolder) {\n setSelectedNode(newFolder);\n }\n }\n\n async function onRenameDriveNodes(\n newName: string,\n nodeId: string,\n ): Promise<void> {\n if (!drives) return;\n\n // Find all drives that contain this node\n const drivesWithNode = drives.filter((drive) =>\n drive.state.global.nodes.some((n) => n.id === nodeId),\n );\n\n // Update node name in all parent drives\n await Promise.all(\n drivesWithNode.map((drive) =>\n renameDriveNode(drive.header.id, nodeId, newName),\n ),\n );\n }\n\n return {\n onAddFile,\n onAddFolder,\n onRenameNode,\n onCopyNode,\n onMoveNode,\n onDuplicateNode,\n onAddAndSelectNewFolder,\n onRenameDriveNodes,\n };\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\n\n/** Returns a node in the selected drive by id. */\nexport function useNodeById(id: string | null | undefined): Node | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === id);\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the path to a node in the selected drive */\nexport function useNodePathById(id: string | null | undefined) {\n const nodes = useNodesInSelectedDrive();\n if (!nodes) return [];\n\n const path: Node[] = [];\n let current = nodes.find((n) => n.id === id);\n\n while (current) {\n path.push(current);\n if (!current.parentFolder) break;\n current = nodes.find((n) => n.id === current?.parentFolder);\n }\n\n return path.reverse();\n}\n\n/** Returns the path to the currently selected node in the selected drive. */\nexport function useSelectedNodePath() {\n const selectedNode = useSelectedNode();\n return useNodePathById(selectedNode?.id);\n}\n","import type { FolderNode } from \"@powerhousedao/shared/document-drive\";\nimport { useFolderById } from \"./folder-by-id.js\";\nimport { useNodeById } from \"./node-by-id.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\nexport function useNodeParentFolderById(\n id: string | null | undefined,\n): FolderNode | undefined {\n const node = useNodeById(id);\n const parentFolder = useFolderById(node?.parentFolder);\n return parentFolder;\n}\n\nexport function useParentFolderForSelectedNode() {\n const node = useSelectedNode();\n return useNodeParentFolderById(node?.id);\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { NoSelectedDocumentError } from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id */\nexport function useSelectedDocumentId(): string | undefined {\n const selectedNode = useSelectedNode();\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const selectedDocumentId = useSelectedDocumentId();\n const [document, dispatch] = useDocumentById(selectedDocumentId);\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const selectedDocumentId = useSelectedDocumentId();\n return useDocumentById(selectedDocumentId);\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const documentId = useSelectedDocumentId();\n\n if (!documentType) {\n return [];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return useDocumentOfType<TDocument, TAction>(documentId, documentType);\n}\n","import type { SubgraphModule } from \"@powerhousedao/shared/document-model\";\nimport { useVetraPackages } from \"./vetra-packages.js\";\n\nexport function useSubgraphModules(): SubgraphModule[] | undefined {\n const vetraPackages = useVetraPackages();\n return vetraPackages.flatMap((pkg) => pkg.subgraphs || []);\n}\n","import { useFeatures } from \"./features.js\";\n\nconst FEATURE_INSPECTOR_ENABLED = \"FEATURE_INSPECTOR_ENABLED\";\nconst FEATURE_INSPECTOR_ENABLED_DEFAULT = false;\n\n/**\n * Synchronous helper to check if inspector is enabled.\n */\nexport function isInspectorEnabledSync(): boolean {\n return (\n window.ph?.features?.get(FEATURE_INSPECTOR_ENABLED) ??\n FEATURE_INSPECTOR_ENABLED_DEFAULT\n );\n}\n\n/**\n * React hook to check if inspector is enabled.\n */\nexport function useInspectorEnabled(): boolean {\n const features = useFeatures();\n return (\n features?.get(FEATURE_INSPECTOR_ENABLED) ??\n FEATURE_INSPECTOR_ENABLED_DEFAULT\n );\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { SyncStatus } from \"@powerhousedao/reactor\";\nimport type {\n DocumentDriveDocument,\n SharingType,\n} from \"@powerhousedao/shared/document-drive\";\n\n// legacy sync status types\nexport type UISyncStatus =\n | \"INITIAL_SYNC\"\n | \"SUCCESS\"\n | \"CONFLICT\"\n | \"MISSING\"\n | \"ERROR\"\n | \"SYNCING\";\n\nconst syncStatusToUI: Record<SyncStatus, UISyncStatus> = {\n [SyncStatus.Synced]: \"SUCCESS\",\n [SyncStatus.Outgoing]: \"SYNCING\",\n [SyncStatus.Incoming]: \"SYNCING\",\n [SyncStatus.OutgoingAndIncoming]: \"SYNCING\",\n [SyncStatus.Error]: \"ERROR\",\n};\n\nexport async function getDrives(\n reactor: IReactorClient,\n): Promise<DocumentDriveDocument[]> {\n const results = await reactor.find({\n type: \"powerhouse/document-drive\",\n });\n return results.results as DocumentDriveDocument[];\n}\n\nexport function getSyncStatus(\n documentId: string,\n sharingType: SharingType,\n): Promise<UISyncStatus | undefined> {\n return Promise.resolve(getSyncStatusSync(documentId, sharingType));\n}\n\nexport function getSyncStatusSync(\n documentId: string,\n sharingType: SharingType,\n): UISyncStatus | undefined {\n if (sharingType === \"LOCAL\") return;\n\n const syncManager =\n window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n if (!syncManager) return;\n\n const status = syncManager.getSyncStatus(documentId);\n if (status === undefined) return;\n\n return syncStatusToUI[status];\n}\n","import type {\n DocumentModelDocument,\n PHDocument,\n ValidationError,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n validateInitialState,\n validateModules,\n validateStateSchemaName,\n} from \"@powerhousedao/shared/document-model\";\n\nexport const validateDocument = (document: PHDocument) => {\n const errors: ValidationError[] = [];\n\n if (document.header.documentType !== \"powerhouse/document-model\") {\n return errors;\n }\n\n const doc = document as DocumentModelDocument;\n const specs = doc.state.global.specifications[0];\n\n // validate initial state errors\n const initialStateErrors = Object.keys(specs.state).reduce<ValidationError[]>(\n (acc, scopeKey) => {\n const scope = scopeKey as keyof typeof specs.state;\n\n return [\n ...acc,\n ...validateInitialState(\n specs.state[scope].initialValue,\n scope !== \"global\",\n ).map((err) => ({\n ...err,\n message: `${err.message}. Scope: ${scope}`,\n details: { ...err.details, scope },\n })),\n ];\n },\n [],\n );\n\n // validate schema state errors\n const schemaStateErrors = Object.keys(specs.state).reduce<ValidationError[]>(\n (acc, scopeKey) => {\n const scope = scopeKey as keyof typeof specs.state;\n const isGlobalScope = scope === \"global\";\n\n return [\n ...acc,\n ...validateStateSchemaName(\n specs.state[scope].schema,\n doc.state.global?.name || doc.header.name || \"\",\n !isGlobalScope ? scope : \"\",\n !isGlobalScope,\n ).map((err) => ({\n ...err,\n message: `${err.message}. Scope: ${scope}`,\n details: { ...err.details, scope },\n })),\n ];\n },\n [],\n );\n\n // modules validation\n const modulesErrors = validateModules(specs.modules);\n\n return [...initialStateErrors, ...schemaStateErrors, ...modulesErrors];\n};\n","import type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { exportFile } from \"../actions/document.js\";\nimport { showPHModal } from \"../hooks/modals.js\";\nimport { validateDocument } from \"./validate-document.js\";\n\nexport const exportDocument = (document?: PHDocument) => {\n if (!document) return;\n const validationErrors = validateDocument(document);\n\n if (validationErrors.length) {\n showPHModal({\n type: \"exportDocumentWithErrors\",\n documentId: document.header.id,\n });\n } else {\n return exportFile(document);\n }\n};\n","import type { Operation } from \"@powerhousedao/shared/document-model\";\n\nexport const getRevisionFromDate = (\n startDate?: Date,\n endDate?: Date,\n operations: Operation[] = [],\n) => {\n if (!startDate || !endDate) return 0;\n\n const operation = operations.find((operation) => {\n const operationDate = new Date(operation.timestampUtcMs);\n return operationDate >= startDate && operationDate <= endDate;\n });\n\n return operation ? operation.index : 0;\n};\n","import * as lzString from \"lz-string\";\n\nexport async function getDriveIdBySlug(driveUrl: string, slug: string) {\n if (!driveUrl) {\n return;\n }\n\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"drives\"); // add /drives\n const drivesUrl = urlParts.join(\"/\");\n const result = await fetch(drivesUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n query: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n variables: {\n slug,\n },\n }),\n });\n\n const data = (await result.json()) as {\n data: { driveIdBySlug: string };\n };\n\n return data.data.driveIdBySlug;\n}\n\nexport function getSlugFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n return urlParts.pop();\n}\n\nexport function getSwitchboardGatewayUrlFromDriveUrl(driveUrl: string) {\n const urlParts = driveUrl.split(\"/\");\n urlParts.pop(); // remove id\n urlParts.pop(); // remove /d\n urlParts.push(\"graphql\"); // add /graphql\n return urlParts.join(\"/\");\n}\n\nexport function getDocumentGraphqlQuery() {\n return `query getDocument($documentId: String!) {\n document(id: $documentId) {\n id\n documentType\n createdAtUtcIso\n lastModifiedAtUtcIso\n name\n revision\n stateJSON\n }\n }`;\n}\n\nexport function buildDocumentSubgraphQuery(\n driveUrl: string,\n documentId: string,\n authToken?: string,\n) {\n const driveSlug = getSlugFromDriveUrl(driveUrl);\n const query = getDocumentGraphqlQuery();\n const variables = { documentId, driveId: driveSlug };\n const headers = authToken\n ? {\n Authorization: `Bearer ${authToken}`,\n }\n : undefined;\n\n const payload: Record<string, string> = {\n document: query.trim(),\n variables: JSON.stringify(variables, null, 2),\n };\n if (headers) {\n payload.headers = JSON.stringify(headers);\n }\n return lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\n\nexport function buildDocumentSubgraphUrl(\n driveUrl: string,\n documentId: string,\n authToken?: string,\n) {\n const encodedQuery = buildDocumentSubgraphQuery(\n driveUrl,\n documentId,\n authToken,\n );\n return `${driveUrl}?explorerURLState=${encodedQuery}`;\n}\n","import { driveCollectionId, GqlRequestChannel } from \"@powerhousedao/reactor\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { useMemo } from \"react\";\nimport { buildDocumentSubgraphUrl } from \"../utils/index.js\";\nimport { useRenown, useSyncList, useUser } from \"./connect.js\";\nimport { useSelectedDrive } from \"./selected-drive.js\";\n\n/**\n * Hook that returns a function to generate a document's switchboard URL.\n * Only returns a function for documents in remote drives.\n * Returns null for local drives or when the document/drive cannot be determined.\n *\n * The returned function generates a fresh bearer token and builds the switchboard URL\n * with authentication when called.\n *\n * @param document - The document to create a switchboard URL generator for\n * @returns An async function that returns the switchboard URL, or null if not applicable\n */\nexport function useGetSwitchboardLink(\n document: PHDocument | undefined,\n): (() => Promise<string>) | null {\n const [drive] = useSelectedDrive();\n const remotes = useSyncList();\n\n const isRemoteDrive = useMemo(() => {\n return remotes.some(\n (remote) =>\n remote.collectionId === driveCollectionId(\"main\", drive.header.id),\n );\n }, [remotes, drive]);\n const remoteUrl = useMemo(() => {\n const remote = remotes.find(\n (remote) =>\n remote.collectionId === driveCollectionId(\"main\", drive.header.id),\n );\n\n if (remote?.channel instanceof GqlRequestChannel) {\n return (remote.channel as GqlRequestChannel).config.url;\n }\n\n return null;\n }, [remotes, drive]);\n const renown = useRenown();\n const user = useUser();\n\n return useMemo(() => {\n if (!isRemoteDrive || !document?.header.id || !remoteUrl) {\n return null;\n }\n\n return async () => {\n // Get bearer token if user is authenticated\n const token = user?.address\n ? await renown?.getBearerToken({\n expiresIn: 600,\n aud: remoteUrl,\n })\n : undefined;\n\n // Build and return the switchboard URL with the document subgraph query\n return buildDocumentSubgraphUrl(remoteUrl, document.header.id, token);\n };\n }, [isRemoteDrive, remoteUrl, document, user, renown]);\n}\n","import { addFileWithProgress } from \"../actions/document.js\";\nimport type {\n ConflictResolution,\n FileUploadProgressCallback,\n UseOnDropFile,\n} from \"../types/upload.js\";\nimport { useDocumentTypes } from \"./document-types.js\";\nimport { useSelectedDriveId } from \"./selected-drive.js\";\nimport { useSelectedFolder } from \"./selected-folder.js\";\n\nexport const useOnDropFile: UseOnDropFile = (\n documentTypesOverride?: string[],\n) => {\n const selectedDriveId = useSelectedDriveId();\n const selectedFolder = useSelectedFolder();\n const documentTypes = useDocumentTypes();\n\n const onDropFile = async (\n file: File,\n onProgress?: FileUploadProgressCallback,\n resolveConflict?: ConflictResolution,\n ) => {\n if (!selectedDriveId) {\n console.warn(\"No selected drive - upload skipped\");\n return;\n }\n\n const fileName = file.name.replace(/\\..+/gim, \"\");\n const targetNodeId = selectedFolder?.id;\n\n // Return the FileNode directly from addFileWithProgress\n return await addFileWithProgress(\n file,\n selectedDriveId,\n fileName,\n targetNodeId,\n onProgress,\n documentTypesOverride ?? documentTypes,\n resolveConflict,\n );\n };\n\n return onDropFile;\n};\n","import { useAllowList } from \"./connect.js\";\nimport { useUser } from \"./renown.js\";\nexport function useUserPermissions() {\n const user = useUser();\n const allowList = useAllowList();\n if (!allowList) {\n return {\n isAllowedToCreateDocuments: true,\n isAllowedToEditDocuments: true,\n };\n }\n\n return {\n isAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n isAllowedToEditDocuments: allowList.includes(user?.address ?? \"\"),\n };\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport { REACTOR_SCHEMA } from \"@powerhousedao/reactor\";\n\nasync function dropTablesInSchema(pg: PGlite, schema: string): Promise<void> {\n await pg.exec(`\nDO $$\nDECLARE\n _schemaname text := '${schema}';\n _tablename text;\nBEGIN\n FOR _tablename IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = _schemaname LOOP\n RAISE INFO 'Dropping table %.%', _schemaname, _tablename;\n EXECUTE format('DROP TABLE %I.%I CASCADE;', _schemaname, _tablename);\n END LOOP;\n IF NOT FOUND THEN\n RAISE WARNING 'Schema % does not exist', _schemaname;\n END IF;\nEND $$;\n`);\n}\n\nexport async function truncateAllTables(\n pg: PGlite,\n schema: string = REACTOR_SCHEMA,\n): Promise<void> {\n await dropTablesInSchema(pg, schema);\n}\n\nexport async function dropAllReactorStorage(pg: PGlite): Promise<void> {\n await dropTablesInSchema(pg, REACTOR_SCHEMA);\n\n // legacy\n await dropTablesInSchema(pg, \"public\");\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport { type DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport { BrowserKeyStorage, RenownCryptoBuilder } from \"@renown/sdk\";\nimport { setDrives } from \"./hooks/drives.js\";\nimport { getDrives } from \"./utils/drives.js\";\n\nexport type ReactorDefaultDrivesConfig = {\n defaultDrivesUrl?: string[];\n};\n\nexport type RefreshReactorDataConfig = {\n debounceDelayMs?: number;\n immediateThresholdMs?: number;\n};\n\nconst DEFAULT_DEBOUNCE_DELAY_MS = 200;\nconst DEFAULT_IMMEDIATE_THRESHOLD_MS = 1000;\n\nasync function _refreshReactorData(reactor: IReactorClient) {\n const drives = await getDrives(reactor);\n\n setDrives(drives);\n}\n\nasync function _refreshReactorDataClient(reactor: IReactorClient | undefined) {\n if (!reactor) return;\n\n const result = await reactor.find({ type: \"powerhouse/document-drive\" });\n setDrives(result.results as DocumentDriveDocument[]);\n}\n\nfunction createDebouncedRefreshReactorData(\n debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS,\n immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS,\n) {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let lastRefreshTime = 0;\n\n return (reactor: IReactorClient, immediate = false) => {\n const now = Date.now();\n const timeSinceLastRefresh = now - lastRefreshTime;\n\n // Clear any pending timeout\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n // If caller requests immediate execution or enough time has passed, execute immediately\n if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n lastRefreshTime = now;\n return _refreshReactorData(reactor);\n }\n\n // Otherwise, debounce the call\n return new Promise<void>((resolve) => {\n timeout = setTimeout(() => {\n lastRefreshTime = Date.now();\n void _refreshReactorData(reactor).then(resolve);\n }, debounceDelayMs);\n });\n };\n}\n\nfunction createDebouncedRefreshReactorDataClient(\n debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS,\n immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS,\n) {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let lastRefreshTime = 0;\n\n return (reactor: IReactorClient | undefined, immediate = false) => {\n const now = Date.now();\n const timeSinceLastRefresh = now - lastRefreshTime;\n\n // Clear any pending timeout\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n // If caller requests immediate execution or enough time has passed, execute immediately\n if (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n lastRefreshTime = now;\n return _refreshReactorDataClient(reactor);\n }\n\n // Otherwise, debounce the call\n return new Promise<void>((resolve) => {\n timeout = setTimeout(() => {\n lastRefreshTime = Date.now();\n void _refreshReactorDataClient(reactor).then(resolve);\n }, debounceDelayMs);\n });\n };\n}\n\nexport const refreshReactorData = createDebouncedRefreshReactorData();\nexport const refreshReactorDataClient =\n createDebouncedRefreshReactorDataClient();\n\n/**\n * @deprecated Use {@link initRenownCrypto} instead\n *\n * Initialize ConnectCrypto\n * @returns ConnectCrypto instance\n */\nexport async function initConnectCrypto() {\n return initRenownCrypto();\n}\n\n/**\n * Initialize RenownCrypto\n * @returns RenownCrypto instance\n */\nexport async function initRenownCrypto() {\n const keyStorage = await BrowserKeyStorage.create();\n return await new RenownCryptoBuilder().withKeyPairStorage(keyStorage).build();\n}\n","import type { PackageInfo } from \"@powerhousedao/shared/registry\";\nexport async function getPackages(registryUrl: string) {\n const res = await fetch(`${registryUrl}/packages`);\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n const data = (await res.json()) as PackageInfo[];\n return data;\n}\n\nexport async function getPackagesByDocumentType(\n registryUrl: string,\n documentType: string,\n): Promise<string[]> {\n const encodedType = encodeURIComponent(documentType);\n const res = await fetch(\n `${registryUrl}/packages/by-document-type?type=${encodedType}`,\n );\n if (!res.ok) throw new Error(`Registry error: HTTP ${res.status}`);\n return (await res.json()) as string[];\n}\n","import type { PackageInfo } from \"@powerhousedao/shared/registry\";\nimport { getPackages, getPackagesByDocumentType } from \"./fetchers.js\";\nimport type { PublishEvent } from \"./types.js\";\n\nfunction cdnUrlToApiUrl(cdnUrl: string): string {\n return cdnUrl.replace(/\\/-\\/cdn\\/?$/, \"\");\n}\nexport class RegistryClient {\n readonly apiUrl: string;\n\n constructor(cdnUrl: string) {\n this.apiUrl = cdnUrlToApiUrl(cdnUrl);\n }\n\n async getPackages(): Promise<PackageInfo[]> {\n const data = await getPackages(this.apiUrl);\n return data;\n }\n\n async getPackagesByDocumentType(documentType: string): Promise<string[]> {\n return await getPackagesByDocumentType(this.apiUrl, documentType);\n }\n\n async searchPackages(query: string): Promise<PackageInfo[]> {\n const packages = await this.getPackages();\n if (!query) return packages;\n const lowerQuery = query.toLowerCase();\n return packages.filter(\n (pkg) =>\n pkg.name.toLowerCase().includes(lowerQuery) ||\n pkg.manifest?.description?.toLowerCase().includes(lowerQuery),\n );\n }\n\n onPublish(callback: (event: PublishEvent) => void): () => void {\n const eventSource = new EventSource(`${this.apiUrl}/-/events`);\n\n eventSource.addEventListener(\"publish\", (e: MessageEvent<string>) => {\n const data = JSON.parse(e.data) as PublishEvent;\n callback(data);\n });\n\n return () => {\n eventSource.close();\n };\n }\n}\n","import type { PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { useEffect, useState } from \"react\";\n\nexport const PGLITE_UPDATE_EVENT = \"ph:pglite-update\";\n\nexport interface PGliteState {\n db: PGliteWithLive | null;\n isLoading: boolean;\n error: Error | null;\n}\n\nconst defaultPGliteState: PGliteState = {\n db: null,\n isLoading: true,\n error: null,\n};\n\nexport const usePGliteDB = () => {\n const [state, setState] = useState<PGliteState>(\n () => window.powerhouse?.pglite ?? defaultPGliteState,\n );\n\n useEffect(() => {\n const handlePgliteUpdate = () =>\n setState(window.powerhouse?.pglite ?? defaultPGliteState);\n\n window.addEventListener(PGLITE_UPDATE_EVENT, handlePgliteUpdate);\n\n return () =>\n window.removeEventListener(PGLITE_UPDATE_EVENT, handlePgliteUpdate);\n }, []);\n\n return state;\n};\n\nexport const useSetPGliteDB = () => {\n const setPGliteState = (pglite: Partial<PGliteState>) => {\n const currentPowerhouse = window.powerhouse ?? {};\n const currentPGliteState = window.powerhouse?.pglite ?? defaultPGliteState;\n\n window.powerhouse = {\n ...currentPowerhouse,\n pglite: {\n ...currentPGliteState,\n ...pglite,\n },\n };\n window.dispatchEvent(new CustomEvent(PGLITE_UPDATE_EVENT));\n };\n\n return setPGliteState;\n};\n\nexport const usePGlite = () => {\n const pglite = usePGliteDB();\n const setPGlite = useSetPGliteDB();\n\n return [pglite, setPGlite];\n};\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport type { LiveNamespace, PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { createRelationalDb } from \"@powerhousedao/reactor\";\nimport type { IRelationalDb as IRelationalDbCore } from \"@powerhousedao/shared/processors\";\nimport { Kysely } from \"kysely\";\nimport { PGliteDialect } from \"kysely-pglite-dialect\";\nimport { useMemo } from \"react\";\nimport { usePGliteDB } from \"../../pglite/usePGlite.js\";\n\n// Type for Relational DB instance enhanced with live capabilities\nexport type RelationalDbWithLive<Schema> = IRelationalDbCore<Schema> & {\n live: LiveNamespace;\n};\n\ninterface IRelationalDbState<Schema> {\n db: RelationalDbWithLive<Schema> | null;\n isLoading: boolean;\n error: Error | null;\n}\n\n// Custom initializer that creates enhanced Kysely instance with live capabilities\nfunction createRelationalDbWithLive<Schema>(\n pgliteInstance: PGliteWithLive,\n): RelationalDbWithLive<Schema> {\n const baseDb = new Kysely<Schema>({\n dialect: new PGliteDialect(pgliteInstance as unknown as PGlite),\n });\n const relationalDb = createRelationalDb(baseDb);\n\n // Inject the live namespace with proper typing\n const relationalDBWithLive =\n relationalDb as unknown as RelationalDbWithLive<Schema>;\n relationalDBWithLive.live = pgliteInstance.live;\n\n return relationalDBWithLive;\n}\n\nexport const useRelationalDb = <Schema>(): IRelationalDbState<Schema> => {\n const pglite = usePGliteDB();\n\n const relationalDb = useMemo<IRelationalDbState<Schema>>(() => {\n if (!pglite.db || pglite.isLoading || pglite.error) {\n return {\n db: null,\n isLoading: pglite.isLoading,\n error: pglite.error,\n };\n }\n\n const db = createRelationalDbWithLive<Schema>(pglite.db);\n\n return {\n db,\n isLoading: false,\n error: null,\n };\n }, [pglite]);\n\n return relationalDb;\n};\n","import type { LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport type {\n IRelationalQueryBuilder,\n RelationalDbProcessorClass,\n} from \"@powerhousedao/shared/processors\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useRelationalDb } from \"./useRelationalDb.js\";\n\nexport type QueryCallbackReturnType = {\n sql: string;\n parameters?: readonly unknown[];\n};\n\nexport type useRelationalQueryOptions = {\n // Whether to hash the namespace to avoid namespace size limit. True by default\n hashNamespace?: boolean;\n};\n\nconst MAX_RETRIES = 5;\nconst RETRY_DELAY = 200;\n\nconst isRelationNotExistError = (error: unknown): boolean => {\n const errorMessage =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : String(error);\n\n return (\n errorMessage.toLowerCase().includes(\"relation\") &&\n errorMessage.toLowerCase().includes(\"does not exist\")\n );\n};\n\ntype LiveQueryType = {\n unsubscribe: () => void;\n};\n\nexport function useRelationalQuery<Schema, T = unknown, TParams = undefined>(\n ProcessorClass: RelationalDbProcessorClass<Schema>,\n driveId: string,\n queryCallback: (\n db: IRelationalQueryBuilder<Schema>,\n parameters?: TParams,\n ) => QueryCallbackReturnType,\n parameters?: TParams,\n options?: useRelationalQueryOptions,\n) {\n const [result, setResult] = useState<LiveQueryResults<T> | null>(null);\n const [queryLoading, setQueryLoading] = useState(true);\n const [error, setError] = useState<Error | undefined>(undefined);\n const retryCount = useRef(0);\n const retryTimeoutRef = useRef<NodeJS.Timeout>(null);\n\n const relationalDb = useRelationalDb<Schema>();\n\n const executeLiveQuery = async (\n sql: string,\n queryParameters: readonly unknown[] | undefined,\n retryAttempt = 0,\n ): Promise<LiveQueryType | null> => {\n if (!relationalDb.db) {\n return null;\n }\n\n try {\n const live = await relationalDb.db.live.query<T>(\n sql,\n queryParameters ? [...queryParameters] : [],\n (result) => {\n setResult(result);\n setQueryLoading(false);\n retryCount.current = 0; // Reset retry count on success\n },\n );\n\n return live as LiveQueryType;\n } catch (err: unknown) {\n if (isRelationNotExistError(err) && retryAttempt < MAX_RETRIES) {\n return new Promise((resolve) => {\n retryTimeoutRef.current = setTimeout(() => {\n resolve(executeLiveQuery(sql, queryParameters, retryAttempt + 1));\n }, RETRY_DELAY);\n });\n }\n\n setQueryLoading(false);\n setError(err instanceof Error ? err : new Error(String(err)));\n return null;\n }\n };\n\n useEffect(() => {\n setError(undefined);\n setQueryLoading(true);\n retryCount.current = 0;\n\n if (!relationalDb.db) {\n return;\n }\n\n // Use the processor helper to obtain a typed namespaced query builder\n const db = ProcessorClass.query(driveId, relationalDb.db);\n\n const compiledQuery = queryCallback(db, parameters);\n const { sql, parameters: queryParameters } = compiledQuery;\n\n const liveQueryPromise = executeLiveQuery(sql, queryParameters);\n\n return () => {\n if (retryTimeoutRef.current) {\n clearTimeout(retryTimeoutRef.current);\n }\n void liveQueryPromise.then((live) => {\n if (live?.unsubscribe) {\n live.unsubscribe();\n }\n });\n };\n }, [relationalDb.db, ProcessorClass, driveId, queryCallback, parameters]);\n\n return {\n isLoading: relationalDb.isLoading || queryLoading,\n error: error || relationalDb.error,\n result,\n } as const;\n}\n","import type { LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport type {\n QueryCallbackReturnType,\n useRelationalQueryOptions,\n} from \"@powerhousedao/reactor-browser\";\nimport type {\n IRelationalQueryBuilder,\n RelationalDbProcessorClass,\n} from \"@powerhousedao/shared/processors\";\nimport type { CompiledQuery } from \"kysely\";\nimport deepEqual from \"lodash.isequal\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport { useRelationalQuery } from \"../hooks/useRelationalQuery.js\";\n\n// Custom hook for parameter memoization\nfunction useStableParams<T>(params: T): T {\n const prevParamsRef = useRef<T>(null);\n\n return useMemo(() => {\n if (!deepEqual(prevParamsRef.current, params)) {\n prevParamsRef.current = params;\n }\n return prevParamsRef.current as T;\n }, [params]);\n}\n\nexport function createProcessorQuery<TSchema>(\n ProcessorClass: RelationalDbProcessorClass<TSchema>,\n) {\n // Overload for queries without parameters\n function useQuery<\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n };\n\n // Overload for queries with parameters\n function useQuery<\n TParams,\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n parameters: TParams,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n parameters: TParams,\n options?: useRelationalQueryOptions,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n };\n\n function useQuery<\n TParams,\n TQueryBuilder extends (\n db: IRelationalQueryBuilder<TSchema>,\n parameters?: TParams,\n ) => QueryCallbackReturnType,\n >(\n driveId: string,\n queryCallback: TQueryBuilder,\n parameters?: TParams,\n options?: useRelationalQueryOptions,\n ): {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any\n > | null;\n } {\n type InferredResult =\n ReturnType<TQueryBuilder> extends CompiledQuery<infer R> ? R : any;\n\n // Automatically memoize parameters using deep comparison\n const stableParams = useStableParams(parameters);\n\n // Memoize the callback to prevent infinite loops, updating when parameters change\n const memoizedCallback = useCallback(queryCallback, [stableParams]);\n\n return useRelationalQuery<TSchema, InferredResult, TParams>(\n ProcessorClass,\n driveId,\n memoizedCallback,\n stableParams,\n options,\n ) as {\n isLoading: boolean;\n error: Error | null;\n result: LiveQueryResults<InferredResult> | null;\n };\n }\n\n return useQuery;\n}\n","import type { Action } from \"@powerhousedao/shared/document-model\";\nimport type { TrackedAction } from \"./types.js\";\n\n/**\n * Tracks pending actions with their operation context (prevOpHash, prevOpIndex).\n * Actions are accumulated until flushed (on push).\n */\nexport class ActionTracker {\n private pending: TrackedAction[] = [];\n\n /** Track a new action with its operation context. */\n track(action: Action, prevOpHash: string, prevOpIndex: number): void {\n this.pending.push({ action, prevOpHash, prevOpIndex });\n }\n\n /** Flush all pending actions and return them. Clears the internal queue. */\n flush(): TrackedAction[] {\n const actions = this.pending;\n this.pending = [];\n return actions;\n }\n\n /** Number of pending actions. */\n get count(): number {\n return this.pending.length;\n }\n\n /** Prepend previously flushed actions back to the queue (for retry on failure). */\n restore(actions: TrackedAction[]): void {\n this.pending = [...actions, ...this.pending];\n }\n\n /** Clear all pending actions without returning them. */\n clear(): void {\n this.pending = [];\n }\n}\n","import type {\n GetDocumentResult,\n GetDocumentWithOperationsResult,\n GetOperationsResult,\n IRemoteClient,\n PropagationMode,\n ReactorGraphQLClient,\n RemoteDocumentData,\n RemoteOperation,\n RemoteOperationResultPage,\n} from \"./types.js\";\n\n/**\n * Thin facade over the GraphQL SDK for remote document operations.\n */\nconst DEFAULT_PAGE_SIZE = 100;\n\nexport class RemoteClient implements IRemoteClient {\n private readonly pageSize: number;\n\n constructor(\n private readonly client: ReactorGraphQLClient,\n pageSize?: number,\n ) {\n this.pageSize = pageSize ?? DEFAULT_PAGE_SIZE;\n }\n\n /** Fetch a document by identifier. Returns null if not found. */\n async getDocument(\n identifier: string,\n branch?: string,\n ): Promise<GetDocumentResult | null> {\n const result = await this.client.GetDocument({\n identifier,\n view: branch ? { branch } : undefined,\n });\n return result.document ?? null;\n }\n\n /**\n * Fetch a document and its operations.\n *\n * When scopes are provided and BatchGetDocumentWithOperations is available,\n * fetches the document and per-scope operations in a single HTTP request.\n * Otherwise falls back to GetDocumentWithOperations for the first page,\n * then paginates remaining operations per scope.\n */\n async getDocumentWithOperations(\n identifier: string,\n branch?: string,\n sinceRevision?: Record<string, number>,\n scopes?: string[],\n ): Promise<GetDocumentWithOperationsResult | null> {\n // Fast path: batch document + per-scope operations in one request\n if (\n this.client.BatchGetDocumentWithOperations &&\n scopes &&\n scopes.length > 0\n ) {\n return this.batchGetDocumentWithOperations(\n identifier,\n branch,\n sinceRevision,\n scopes,\n );\n }\n\n // Standard path: GetDocumentWithOperations + paginate if needed\n const result = await this.client.GetDocumentWithOperations({\n identifier,\n view: branch ? { branch } : undefined,\n operationsPaging: {\n limit: this.pageSize,\n cursor: null,\n },\n });\n\n if (!result.document) return null;\n\n const doc = result.document.document;\n const opsPage = doc.operations;\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n\n if (opsPage) {\n for (const op of opsPage.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n }\n\n // Check if we have all expected operations by comparing against revisionsList\n const expectedTotal = doc.revisionsList.reduce(\n (sum, r) => sum + r.revision,\n 0,\n );\n const fetchedTotal = opsPage?.items.length ?? 0;\n\n if (fetchedTotal >= expectedTotal) {\n return {\n document: doc,\n childIds: result.document.childIds,\n operations: { operationsByScope },\n };\n }\n\n // Missing operations — fetch all per scope\n const allScopes = doc.revisionsList.map((r) => r.scope);\n const allOps = await this.getAllOperations(\n doc.id,\n branch,\n sinceRevision,\n allScopes,\n );\n\n return {\n document: doc,\n childIds: result.document.childIds,\n operations: allOps,\n };\n }\n\n /**\n * Fetch document + per-scope operations in a single HTTP request\n * via BatchGetDocumentWithOperations, then paginate any remaining pages.\n */\n private async batchGetDocumentWithOperations(\n identifier: string,\n branch: string | undefined,\n sinceRevision: Record<string, number> | undefined,\n scopes: string[],\n ): Promise<GetDocumentWithOperationsResult | null> {\n const view = branch ? { branch } : undefined;\n const filters = scopes.map((scope) => ({\n documentId: identifier,\n branch: branch ?? null,\n sinceRevision: sinceRevision?.[scope] ?? 0,\n scopes: [scope],\n }));\n const pagings = scopes.map(() => ({\n limit: this.pageSize,\n cursor: null as string | null,\n }));\n\n const result = await this.client.BatchGetDocumentWithOperations!(\n identifier,\n view,\n filters,\n pagings,\n );\n\n if (!result.document) return null;\n\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n let pending: {\n scope: string;\n filter: (typeof filters)[0];\n cursor: string;\n }[] = [];\n\n for (let i = 0; i < scopes.length; i++) {\n const page = result.operations[i];\n for (const op of page.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n if (page.hasNextPage && page.cursor) {\n pending.push({\n scope: scopes[i],\n filter: filters[i],\n cursor: page.cursor,\n });\n }\n }\n\n // Continue pagination for scopes with more pages\n while (pending.length > 0) {\n const pages = await this.fetchOperationPages(\n pending.map((p) => p.filter),\n pending.map((p) => ({ limit: this.pageSize, cursor: p.cursor })),\n );\n\n const nextPending: typeof pending = [];\n for (let i = 0; i < pending.length; i++) {\n const page = pages[i];\n for (const op of page.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n if (page.hasNextPage && page.cursor) {\n nextPending.push({ ...pending[i], cursor: page.cursor });\n }\n }\n pending = nextPending;\n }\n\n return {\n document: result.document.document,\n childIds: result.document.childIds,\n operations: { operationsByScope },\n };\n }\n\n /**\n * Fetch all operations for a document, paginating through all pages.\n * Each scope is queried individually because the API only returns\n * pagination cursors for single-scope queries.\n */\n async getAllOperations(\n documentId: string,\n branch?: string,\n sinceRevision?: Record<string, number>,\n scopes?: string[],\n ): Promise<GetOperationsResult> {\n // When scopes are specified, query each scope in parallel.\n // Uses a single composed request per pagination round when available.\n if (scopes && scopes.length > 0) {\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n\n // Tracks scopes still being paginated, each with its own filter and cursor\n let pending = scopes.map((scope) => ({\n scope,\n filter: {\n documentId,\n branch: branch ?? null,\n sinceRevision: sinceRevision?.[scope] ?? 0,\n scopes: [scope],\n },\n cursor: null as string | null,\n }));\n\n while (pending.length > 0) {\n const pages = await this.fetchOperationPages(\n pending.map((p) => p.filter),\n pending.map((p) => ({ limit: this.pageSize, cursor: p.cursor })),\n );\n\n const nextPending: typeof pending = [];\n\n for (let i = 0; i < pending.length; i++) {\n const page = pages[i];\n for (const op of page.items) {\n (operationsByScope[op.action.scope] ??= []).push(op);\n }\n if (page.hasNextPage && page.cursor) {\n nextPending.push({ ...pending[i], cursor: page.cursor });\n }\n }\n\n pending = nextPending;\n }\n\n return { operationsByScope };\n }\n\n // No scopes specified — single query for all scopes (no per-scope sinceRevision)\n return this.fetchOperationsForScope(documentId, branch);\n }\n\n /**\n * Fetch one page of operations per filter.\n * Uses the composed query (single HTTP request) when available,\n * otherwise falls back to parallel individual requests.\n */\n private async fetchOperationPages(\n filters: Parameters<\n ReactorGraphQLClient[\"GetDocumentOperations\"]\n >[0][\"filter\"][],\n pagings: Parameters<\n ReactorGraphQLClient[\"GetDocumentOperations\"]\n >[0][\"paging\"][],\n ): Promise<RemoteOperationResultPage[]> {\n if (this.client.BatchGetDocumentOperations) {\n return this.client.BatchGetDocumentOperations(filters, pagings);\n }\n\n return Promise.all(\n filters.map((filter, i) =>\n this.client\n .GetDocumentOperations({ filter, paging: pagings[i] })\n .then((r) => r.documentOperations),\n ),\n );\n }\n\n /** Fetch all pages of operations for a single scope (or all scopes if none specified). */\n private async fetchOperationsForScope(\n documentId: string,\n branch?: string,\n sinceRevision?: number,\n scope?: string,\n ): Promise<GetOperationsResult> {\n const operationsByScope: Record<string, RemoteOperation[]> = {};\n let cursor: string | null | undefined;\n let hasNextPage = true;\n\n while (hasNextPage) {\n const result = await this.client.GetDocumentOperations({\n filter: {\n documentId,\n branch: branch ?? null,\n sinceRevision: sinceRevision ?? 0,\n scopes: scope ? [scope] : null,\n },\n paging: {\n limit: this.pageSize,\n cursor: cursor ?? null,\n },\n });\n\n const page = result.documentOperations;\n\n for (const op of page.items) {\n const s = op.action.scope;\n (operationsByScope[s] ??= []).push(op);\n }\n\n hasNextPage = page.hasNextPage;\n cursor = page.cursor;\n }\n\n return { operationsByScope };\n }\n\n /** Push actions to an existing document via MutateDocument. */\n async pushActions(\n documentIdentifier: string,\n actions: ReadonlyArray<NonNullable<unknown>>,\n branch?: string,\n ): Promise<RemoteDocumentData> {\n const result = await this.client.MutateDocument({\n documentIdentifier,\n actions,\n view: branch ? { branch } : undefined,\n });\n return result.mutateDocument;\n }\n\n /** Create a new document on the remote. */\n async createDocument(\n document: NonNullable<unknown>,\n parentIdentifier?: string,\n ): Promise<RemoteDocumentData> {\n const result = await this.client.CreateDocument({\n document,\n parentIdentifier: parentIdentifier ?? null,\n });\n return result.createDocument;\n }\n\n /** Create an empty document of a given type on the remote. */\n async createEmptyDocument(\n documentType: string,\n parentIdentifier?: string,\n ): Promise<RemoteDocumentData> {\n const result = await this.client.CreateEmptyDocument({\n documentType,\n parentIdentifier: parentIdentifier ?? null,\n });\n return result.createEmptyDocument;\n }\n\n /** Delete a document on the remote. Returns true if successful. */\n async deleteDocument(\n identifier: string,\n propagate?: PropagationMode,\n ): Promise<boolean> {\n const result = await this.client.DeleteDocument({\n identifier,\n propagate,\n });\n return result.deleteDocument;\n }\n}\n","import type {\n DocumentOperations,\n Operation,\n PHBaseState,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n ConflictInfo,\n RemoteDocumentData,\n RemoteOperation,\n} from \"./types.js\";\n\n/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. \"SET_MODEL_NAME\" → \"setModelName\"). */\nexport function screamingSnakeToCamel(s: string): string {\n return s\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\n/** Error thrown when a push conflict is detected with the \"reject\" strategy. */\nexport class ConflictError extends Error {\n constructor(public readonly conflict: ConflictInfo) {\n super(\"Push conflict: remote has new operations since last pull\");\n this.name = \"ConflictError\";\n }\n}\n\n/** Convert a remote operation to the local Operation type. */\nexport function remoteOperationToLocal(remote: RemoteOperation): Operation {\n return {\n id: remote.id ?? \"\",\n index: remote.index,\n skip: remote.skip,\n timestampUtcMs: remote.timestampUtcMs,\n hash: remote.hash,\n error: remote.error ?? undefined,\n action: {\n id: remote.action.id,\n type: remote.action.type,\n timestampUtcMs: remote.action.timestampUtcMs,\n input: remote.action.input,\n scope: remote.action.scope,\n attachments: remote.action.attachments?.map((a) => ({\n data: a.data,\n mimeType: a.mimeType,\n hash: a.hash,\n extension: a.extension ?? undefined,\n fileName: a.fileName ?? undefined,\n })),\n context: remote.action.context?.signer\n ? {\n signer: {\n user: remote.action.context.signer.user ?? {\n address: \"\",\n networkId: \"\",\n chainId: 0,\n },\n app: remote.action.context.signer.app ?? {\n name: \"\",\n key: \"\",\n },\n signatures: remote.action.context.signer.signatures.map((s) =>\n deserializeSignature(s),\n ),\n },\n }\n : undefined,\n },\n };\n}\n\n/**\n * Deserialize a signature string back to a 5-element tuple.\n * The server serializes tuples via `tuple.join(\", \")`.\n */\nexport function deserializeSignature(\n s: string,\n): [string, string, string, string, string] {\n const parts = s.split(\", \");\n return [\n parts[0] ?? \"\",\n parts[1] ?? \"\",\n parts[2] ?? \"\",\n parts[3] ?? \"\",\n parts[4] ?? \"\",\n ];\n}\n\n/** Convert remote operations to local DocumentOperations format. */\nexport function convertRemoteOperations(\n operationsByScope: Record<string, RemoteOperation[]>,\n): DocumentOperations {\n const operations: DocumentOperations = {};\n for (const [scope, remoteOps] of Object.entries(operationsByScope)) {\n operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));\n }\n return operations;\n}\n\n/** Reconstruct a PHDocument from remote document data and operations. */\nexport function buildPulledDocument(\n remoteDoc: RemoteDocumentData,\n operations: DocumentOperations,\n initialDoc: PHDocument<PHBaseState>,\n branch: string,\n): PHDocument<PHBaseState> {\n return {\n header: {\n ...initialDoc.header,\n id: remoteDoc.id,\n name: remoteDoc.name,\n slug: remoteDoc.slug ?? \"\",\n documentType: remoteDoc.documentType,\n createdAtUtcIso:\n typeof remoteDoc.createdAtUtcIso === \"string\"\n ? remoteDoc.createdAtUtcIso\n : remoteDoc.createdAtUtcIso.toISOString(),\n lastModifiedAtUtcIso:\n typeof remoteDoc.lastModifiedAtUtcIso === \"string\"\n ? remoteDoc.lastModifiedAtUtcIso\n : remoteDoc.lastModifiedAtUtcIso.toISOString(),\n revision: Object.fromEntries(\n remoteDoc.revisionsList.map((r) => [r.scope, r.revision]),\n ),\n branch,\n },\n state: remoteDoc.state as PHBaseState,\n initialState: initialDoc.initialState,\n operations,\n clipboard: [],\n };\n}\n\n/** Extract revision map from a remote document's revisionsList. */\nexport function extractRevisionMap(\n revisionsList: RemoteDocumentData[\"revisionsList\"],\n): Record<string, number> {\n return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n\n/**\n * Check if any scope in currentRevision is ahead of knownRevision.\n * When `scopes` is provided, only those scopes are checked.\n */\nexport function hasRevisionConflict(\n currentRevision: Record<string, number>,\n knownRevision: Record<string, number>,\n scopes?: ReadonlySet<string>,\n): boolean {\n for (const scope in currentRevision) {\n if (scopes && !scopes.has(scope)) continue;\n if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) {\n return true;\n }\n }\n return false;\n}\n","import type {\n Action,\n DocumentOperations,\n Operation,\n PHBaseState,\n PHDocument,\n PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport type { PHDocumentController } from \"document-model\";\nimport { ActionTracker } from \"./action-tracker.js\";\nimport { RemoteClient } from \"./remote-client.js\";\nimport type {\n ConflictStrategy,\n DocumentChangeListener,\n IRemoteClient,\n IRemoteController,\n PropagationMode,\n PushResult,\n RemoteControllerOptions,\n RemoteDocumentChangeEvent,\n RemoteDocumentData,\n RemoteOperation,\n SyncStatus,\n TrackedAction,\n} from \"./types.js\";\nimport {\n ConflictError,\n buildPulledDocument,\n convertRemoteOperations,\n extractRevisionMap,\n hasRevisionConflict,\n screamingSnakeToCamel,\n} from \"./utils.js\";\n\n/** Extract TState from a PHDocumentController subclass. */\ntype InferState<C> = C extends PHDocumentController<infer S> ? S : never;\n\n/**\n * Extract action methods from a controller type.\n * These are the dynamically-added methods (not on the base PHDocumentController prototype).\n */\ntype ActionMethodsOf<C, TRemote> = {\n [K in Exclude<keyof C, keyof PHDocumentController<any>>]: C[K] extends (\n input: infer I,\n ) => unknown\n ? (input: I) => TRemote & ActionMethodsOf<C, TRemote>\n : C[K];\n};\n\n/** The full return type: RemoteDocumentController + action methods. */\nexport type RemoteDocumentControllerWith<C extends PHDocumentController<any>> =\n RemoteDocumentController<C> & ActionMethodsOf<C, RemoteDocumentController<C>>;\n\n/**\n * A controller that wraps a PHDocumentController with remote push/pull capabilities.\n * Composes a local controller and adds GraphQL-based sync with a reactor server.\n */\nexport class RemoteDocumentController<\n TController extends PHDocumentController<any>,\n> implements IRemoteController<InferState<TController>> {\n private inner: TController;\n private readonly remoteClient: IRemoteClient;\n private readonly tracker = new ActionTracker();\n private readonly options: RemoteControllerOptions;\n private documentId: string;\n private remoteRevision: Record<string, number> = {};\n private hasPulled = false;\n private pushScheduled = false;\n private pushQueue: Promise<void> = Promise.resolve();\n private listeners: DocumentChangeListener[] = [];\n\n private constructor(inner: TController, options: RemoteControllerOptions) {\n this.inner = inner;\n this.options = options;\n this.documentId = options.documentId ?? \"\";\n this.remoteClient = new RemoteClient(\n options.client,\n options.operationsPageSize,\n );\n\n this.setupActionInterceptors();\n }\n\n // --- State access (delegated to inner controller) ---\n\n get header(): PHDocumentHeader {\n return this.inner.header;\n }\n\n get state(): InferState<TController> {\n return this.inner.state as InferState<TController>;\n }\n\n get operations(): DocumentOperations {\n return this.inner.operations;\n }\n\n get document(): PHDocument<InferState<TController>> {\n return this.inner.document as PHDocument<InferState<TController>>;\n }\n\n get status(): SyncStatus {\n return {\n pendingActionCount: this.tracker.count,\n connected: this.documentId !== \"\",\n documentId: this.documentId,\n remoteRevision: { ...this.remoteRevision },\n };\n }\n\n /** Register a listener for document changes. Returns an unsubscribe function. */\n onChange(listener: DocumentChangeListener): () => void {\n this.listeners.push(listener);\n return () => {\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n\n private notifyListeners(source: RemoteDocumentChangeEvent[\"source\"]): void {\n if (this.listeners.length === 0) return;\n const event: RemoteDocumentChangeEvent = {\n source,\n document: this.document,\n };\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n\n // --- Remote operations ---\n\n /** Push all pending actions to remote, then pull latest state. */\n async push(): Promise<PushResult> {\n let tracked = this.tracker.flush();\n\n if (tracked.length === 0 && this.documentId !== \"\") {\n // Nothing to push, just pull (reuses the fetched document)\n const remoteDocument = await this.pull();\n return {\n remoteDocument,\n actionCount: 0,\n operations: [],\n };\n }\n\n try {\n await this.ensureRemoteDocument();\n\n // Conflict detection: check if remote has changed since last pull\n if (this.options.onConflict && tracked.length > 0) {\n tracked = await this.handleConflicts(tracked, this.options.onConflict);\n }\n } catch (error) {\n // Pre-push failure: restore actions so they can be retried\n this.tracker.restore(tracked);\n throw error;\n }\n\n let pushedActions: Action[] = [];\n\n try {\n if (tracked.length > 0) {\n const actions = await this.prepareActionsForPush(tracked);\n pushedActions = actions;\n\n await this.remoteClient.pushActions(\n this.documentId,\n actions,\n this.options.branch,\n );\n }\n } catch (error) {\n // Push failed: restore actions so they can be retried\n this.tracker.restore(tracked);\n throw error;\n }\n\n // Pull remote state to reconcile (remote is source of truth).\n // If this fails, actions were already pushed — do NOT restore them.\n const remoteDocument = await this.pull();\n\n return {\n remoteDocument,\n actionCount: tracked.length,\n operations: pushedActions,\n };\n }\n\n /** Delete the document on the remote. */\n async delete(propagate?: PropagationMode): Promise<boolean> {\n if (this.documentId === \"\") {\n throw new Error(\"Cannot delete: no document ID set\");\n }\n const result = await this.remoteClient.deleteDocument(\n this.documentId,\n propagate,\n );\n return result;\n }\n\n /** Pull latest state from remote, replacing local document. Returns the remote document data. */\n async pull(): Promise<RemoteDocumentData> {\n if (this.documentId === \"\") {\n throw new Error(\"Cannot pull: no document ID set\");\n }\n\n const { remoteDoc, operations } = await this.fetchDocumentAndOperations();\n\n // Get module from inner controller\n const initialDoc = this.inner.module.utils.createDocument();\n const pulledDocument = buildPulledDocument(\n remoteDoc,\n operations,\n initialDoc,\n this.options.branch ?? \"main\",\n );\n\n // Recreate inner controller with pulled document\n const ControllerClass = this.inner.constructor as new (\n doc?: PHDocument<PHBaseState>,\n ) => TController;\n this.inner = new ControllerClass(pulledDocument);\n\n // Re-setup interceptors on the new inner instance\n this.setupActionInterceptors();\n\n // Clear tracker (remote is source of truth)\n this.tracker.clear();\n\n // Update remote revision\n this.remoteRevision = extractRevisionMap(remoteDoc.revisionsList);\n\n this.notifyListeners(\"pull\");\n\n return remoteDoc;\n }\n\n // --- Static factories ---\n\n /**\n * Pull an existing document from remote and create a controller for it.\n */\n static async pull<C extends PHDocumentController<any>>(\n ControllerClass: new (doc?: PHDocument<any>) => C,\n options: RemoteControllerOptions,\n ): Promise<RemoteDocumentControllerWith<C>> {\n // Create a temporary instance to access the module\n const temp = new ControllerClass();\n const remote = new RemoteDocumentController(temp, options);\n\n if (options.documentId) {\n await remote.pull();\n }\n\n return remote as RemoteDocumentControllerWith<C>;\n }\n\n /**\n * Wrap an existing controller instance with remote capabilities.\n * Pending local actions on the inner controller are NOT tracked\n * (only new actions through the remote controller are tracked).\n */\n static from<C extends PHDocumentController<any>>(\n controller: C,\n options: RemoteControllerOptions,\n ): RemoteDocumentControllerWith<C> {\n return new RemoteDocumentController(\n controller,\n options,\n ) as RemoteDocumentControllerWith<C>;\n }\n\n // --- Private methods ---\n\n /** Create the document on the remote if it doesn't exist yet. */\n private async ensureRemoteDocument(): Promise<void> {\n if (this.documentId !== \"\") return;\n const remoteDoc = await this.remoteClient.createEmptyDocument(\n this.inner.header.documentType,\n this.options.parentIdentifier,\n );\n this.documentId = remoteDoc.id;\n }\n\n /** Set up interceptors for all action methods on the inner controller. */\n private setupActionInterceptors(): void {\n // Get the module's action keys from the inner controller\n const module = (this.inner as Record<string, unknown>)[\"module\"] as {\n actions: Record<string, unknown>;\n };\n\n for (const actionType in module.actions) {\n // Skip if it's a property on our own class\n if (actionType in RemoteDocumentController.prototype) {\n continue;\n }\n\n Object.defineProperty(this, actionType, {\n value: (input: unknown) => {\n // Snapshot operation counts per scope BEFORE applying\n const opCountsBefore: Record<string, number> = {};\n for (const scope in this.inner.operations) {\n opCountsBefore[scope] = this.inner.operations[scope].length;\n }\n\n // Apply locally via inner controller\n (\n this.inner as unknown as Record<string, (input: unknown) => unknown>\n )[actionType](input);\n\n // Find which scope got the new operation\n const newOp = this.findNewOperation(opCountsBefore);\n\n // Get prevOp in the SAME scope as the new operation\n const prevOp = newOp\n ? this.getLastOperationInScope(newOp.action.scope, newOp)\n : undefined;\n const prevOpHash = prevOp?.hash ?? \"\";\n const prevOpIndex = prevOp?.index ?? -1;\n\n if (!newOp) {\n // Action produced no operation (NOOP) — nothing to track\n return this;\n }\n\n // Track the action for push\n this.tracker.track(newOp.action, prevOpHash, prevOpIndex);\n this.notifyListeners(\"action\");\n\n if (this.options.mode === \"streaming\") {\n this.schedulePush();\n }\n\n return this;\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n /**\n * Find the new operation added after applying an action,\n * by comparing current operation counts against a previous snapshot.\n */\n private findNewOperation(\n opCountsBefore: Record<string, number>,\n ): Operation | undefined {\n const ops = this.inner.operations;\n for (const scope in ops) {\n const scopeOps = ops[scope];\n const prevCount = opCountsBefore[scope] ?? 0;\n if (scopeOps.length > prevCount) {\n return scopeOps[scopeOps.length - 1];\n }\n }\n return undefined;\n }\n\n /**\n * Get the last operation in a specific scope, optionally excluding\n * a given operation (e.g. the one just added).\n */\n private getLastOperationInScope(\n scope: string,\n excludeOp?: Operation,\n ): Operation | undefined {\n const scopeOps = this.inner.operations[scope];\n if (scopeOps.length === 0) return undefined;\n for (let i = scopeOps.length - 1; i >= 0; i--) {\n if (scopeOps[i] !== excludeOp) return scopeOps[i];\n }\n return undefined;\n }\n\n /**\n * Detect and handle conflicts between local pending actions and remote state.\n * Returns the (possibly rebased) tracked actions to push.\n */\n private async handleConflicts(\n localTracked: TrackedAction[],\n strategy: ConflictStrategy,\n ): Promise<TrackedAction[]> {\n // Fetch current remote document to get latest revisions\n const remoteResult = await this.remoteClient.getDocument(\n this.documentId,\n this.options.branch,\n );\n if (!remoteResult) {\n throw new Error(`Document \"${this.documentId}\" not found on remote`);\n }\n\n const currentRevision = extractRevisionMap(\n remoteResult.document.revisionsList,\n );\n\n // Only check scopes that local actions touch\n const localScopes = new Set(localTracked.map((t) => t.action.scope));\n\n if (\n !hasRevisionConflict(currentRevision, this.remoteRevision, localScopes)\n ) {\n return localTracked;\n }\n\n // Fetch new remote operations for conflicting scopes in parallel,\n // using the correct sinceRevision for each scope.\n const conflictingScopes = [...localScopes].filter(\n (scope) =>\n (currentRevision[scope] ?? 0) > (this.remoteRevision[scope] ?? 0),\n );\n const { operationsByScope } = await this.remoteClient.getAllOperations(\n this.documentId,\n this.options.branch,\n this.remoteRevision,\n conflictingScopes,\n );\n const remoteOperations: Record<string, RemoteOperation[]> = {};\n for (const [scope, ops] of Object.entries(operationsByScope)) {\n remoteOperations[scope] = ops;\n }\n\n const conflictInfo = {\n remoteOperations,\n localActions: localTracked,\n knownRevision: { ...this.remoteRevision },\n currentRevision: { ...currentRevision },\n };\n\n if (strategy === \"reject\") {\n throw new ConflictError(conflictInfo);\n }\n\n if (strategy === \"rebase\") {\n return this.pullAndReplay(localTracked.map((t) => t.action));\n }\n\n // Custom merge handler (only possibility left after narrowing)\n const mergedActions = await strategy(conflictInfo);\n return this.pullAndReplay(mergedActions);\n }\n\n /**\n * Pull latest remote state and replay actions through interceptors.\n * Returns newly tracked actions with correct prevOpHash values.\n */\n private async pullAndReplay(actions: Action[]): Promise<TrackedAction[]> {\n await this.pull();\n\n for (const action of actions) {\n // Action types are SCREAMING_SNAKE_CASE but interceptors use camelCase\n const methodName = screamingSnakeToCamel(action.type);\n const method = (\n this as unknown as Record<string, (input: unknown) => unknown>\n )[methodName];\n if (typeof method === \"function\") {\n method.call(this, action.input);\n }\n }\n\n return this.tracker.flush();\n }\n\n /** Prepare actions for push, optionally signing them. */\n private async prepareActionsForPush(\n tracked: { action: Action; prevOpHash: string; prevOpIndex: number }[],\n ) {\n const actions: Action[] = [];\n\n for (const { action, prevOpHash, prevOpIndex } of tracked) {\n let prepared: Action = {\n ...action,\n context: {\n ...action.context,\n prevOpHash,\n prevOpIndex,\n },\n };\n\n if (this.options.signer) {\n prepared = await this.signAction(prepared);\n }\n\n actions.push(prepared);\n }\n\n return actions;\n }\n\n /** Sign an action using the configured signer, preserving existing signatures. */\n private async signAction(action: Action): Promise<Action> {\n const signer = this.options.signer!;\n const signature = await signer.signAction(action);\n const existingSignatures = action.context?.signer?.signatures ?? [];\n return {\n ...action,\n context: {\n ...action.context,\n signer: {\n user: signer.user!,\n app: signer.app!,\n signatures: [...existingSignatures, signature],\n },\n },\n };\n }\n\n /**\n * Fetch document and operations from the remote.\n *\n * On the first pull, uses the combined document+operations query.\n * On subsequent pulls, fetches only new operations per scope using\n * sinceRevision, then merges with existing local operations.\n * Falls back to a full fetch if the merge produces a count mismatch.\n */\n private async fetchDocumentAndOperations(): Promise<{\n remoteDoc: RemoteDocumentData;\n operations: DocumentOperations;\n }> {\n // Incremental fetch: use sinceRevision per scope\n if (this.hasPulled) {\n return this.incrementalFetch();\n }\n\n // Initial fetch: combined document + operations query\n const result = await this.remoteClient.getDocumentWithOperations(\n this.documentId,\n this.options.branch,\n );\n\n if (!result) {\n throw new Error(`Document \"${this.documentId}\" not found on remote`);\n }\n\n this.hasPulled = true;\n return {\n remoteDoc: result.document,\n operations: convertRemoteOperations(result.operations.operationsByScope),\n };\n }\n\n /**\n * Incremental fetch: fetches the document and only new operations per scope\n * using sinceRevision in a single request when possible.\n * Falls back to a full fetch on count mismatch.\n */\n private async incrementalFetch(): Promise<{\n remoteDoc: RemoteDocumentData;\n operations: DocumentOperations;\n }> {\n const scopes = Object.keys(this.remoteRevision);\n\n const result = await this.remoteClient.getDocumentWithOperations(\n this.documentId,\n this.options.branch,\n this.remoteRevision,\n scopes.length > 0 ? scopes : undefined,\n );\n\n if (!result) {\n throw new Error(`Document \"${this.documentId}\" not found on remote`);\n }\n\n const remoteDoc = result.document;\n const expectedRevision = extractRevisionMap(remoteDoc.revisionsList);\n\n const newOps = convertRemoteOperations(result.operations.operationsByScope);\n const merged = this.mergeOperations(this.inner.operations, newOps);\n\n // Validate: merged operation counts must match remote revisions\n if (this.hasExpectedOperationCounts(merged, expectedRevision)) {\n return { remoteDoc, operations: merged };\n }\n\n // Mismatch — do a full fetch\n return this.fullFetch(remoteDoc);\n }\n\n /**\n * Full fetch fallback: fetches all operations from the beginning.\n * Used when an incremental fetch produces a count mismatch.\n */\n private async fullFetch(remoteDoc: RemoteDocumentData): Promise<{\n remoteDoc: RemoteDocumentData;\n operations: DocumentOperations;\n }> {\n const { operationsByScope } = await this.remoteClient.getAllOperations(\n this.documentId,\n this.options.branch,\n );\n\n return {\n remoteDoc,\n operations: convertRemoteOperations(operationsByScope),\n };\n }\n\n /**\n * Validate that the merged operations match the expected revision per scope.\n * Each scope's operation count should equal its revision number.\n */\n private hasExpectedOperationCounts(\n operations: DocumentOperations,\n expectedRevision: Record<string, number>,\n ): boolean {\n for (const [scope, revision] of Object.entries(expectedRevision)) {\n const opCount = scope in operations ? operations[scope].length : 0;\n if (opCount !== revision) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Merge existing local operations with newly fetched operations.\n * Appends new operations to existing ones per scope.\n */\n private mergeOperations(\n existingOps: DocumentOperations,\n newOps: DocumentOperations,\n ): DocumentOperations {\n const merged: DocumentOperations = {};\n\n // Copy existing operations\n for (const [scope, ops] of Object.entries(existingOps)) {\n if (ops.length > 0) {\n merged[scope] = [...ops];\n }\n }\n\n // Append new operations per scope\n for (const [scope, ops] of Object.entries(newOps)) {\n if (ops.length > 0) {\n (merged[scope] ??= []).push(...ops);\n }\n }\n\n return merged;\n }\n\n /** Schedule a push via microtask (for streaming mode coalescing). */\n private schedulePush(): void {\n if (this.pushScheduled) return;\n this.pushScheduled = true;\n queueMicrotask(() => {\n this.pushScheduled = false;\n // Chain onto the push queue to prevent concurrent pushes\n this.pushQueue = this.pushQueue.then(async () => {\n try {\n await this.push();\n } catch (error: unknown) {\n // Actions remain in tracker for retry\n this.options.onPushError?.(error);\n }\n });\n });\n }\n}\n","import type { CSSProperties } from \"react\";\n\ninterface IconProps {\n size?: number;\n width?: number;\n height?: number;\n color?: string;\n style?: CSSProperties;\n className?: string;\n}\n\ninterface RenownLogoProps extends IconProps {\n hovered?: boolean;\n}\n\nexport function RenownLogo({\n width = 71,\n height = 19,\n hovered = false,\n color = \"currentColor\",\n className,\n}: RenownLogoProps) {\n return (\n <svg\n width={width}\n height={height}\n viewBox=\"0 0 71 19\"\n fill={color}\n xmlns=\"http://www.w3.org/2000/svg\"\n className={className}\n >\n <path d=\"M53.6211 18.4887V9.0342H56.435V10.8096H56.4923C56.7377 10.181 57.1085 9.70244 57.6047 9.37398C58.101 9.03986 58.6981 8.8728 59.3962 8.8728C60.4105 8.8728 61.2039 9.1871 61.7765 9.8157C62.3546 10.4443 62.6436 11.3164 62.6436 12.432V18.4887H59.7397V13.0776C59.7397 12.5283 59.6007 12.1007 59.3225 11.7949C59.0499 11.4835 58.6654 11.3277 58.1692 11.3277C57.6784 11.3277 57.2803 11.4976 56.9749 11.8374C56.6695 12.1772 56.5168 12.6161 56.5168 13.1541V18.4887H53.6211Z\" />\n <path d=\"M53.097 9.03394L50.7412 18.4884H47.6164L46.1522 12.075H46.0949L44.6389 18.4884H41.5632L39.1992 9.03394H42.1195L43.3056 15.7532H43.3628L44.7861 9.03394H47.551L48.9906 15.7532H49.0479L50.234 9.03394H53.097Z\" />\n <path d=\"M37.8661 17.3926C37.0427 18.2591 35.9084 18.6923 34.4632 18.6923C33.0181 18.6923 31.8838 18.2591 31.0604 17.3926C30.2369 16.5205 29.8252 15.3086 29.8252 13.7569C29.8252 12.2336 30.2424 11.033 31.0767 10.1552C31.9111 9.2718 33.0399 8.83008 34.4632 8.83008C35.892 8.83008 37.0208 9.26896 37.8497 10.1467C38.6841 11.0188 39.1013 12.2222 39.1013 13.7569C39.1013 15.3143 38.6896 16.5262 37.8661 17.3926ZM33.2117 15.7702C33.5116 16.2402 33.9288 16.4752 34.4632 16.4752C34.9977 16.4752 35.4148 16.2402 35.7148 15.7702C36.0147 15.2945 36.1647 14.6234 36.1647 13.7569C36.1647 12.9131 36.012 12.2506 35.7066 11.7692C35.4012 11.2878 34.9868 11.0472 34.4632 11.0472C33.9343 11.0472 33.5171 11.2878 33.2117 11.7692C32.9118 12.2449 32.7618 12.9075 32.7618 13.7569C32.7618 14.6234 32.9118 15.2945 33.2117 15.7702Z\" />\n <path d=\"M20.0088 18.4887V9.0342H22.8227V10.8096H22.88C23.1254 10.181 23.4962 9.70244 23.9924 9.37398C24.4887 9.03986 25.0858 8.8728 25.7838 8.8728C26.7982 8.8728 27.5916 9.1871 28.1642 9.8157C28.7423 10.4443 29.0313 11.3164 29.0313 12.432V18.4887H26.1274V13.0776C26.1274 12.5283 25.9883 12.1007 25.7102 11.7949C25.4376 11.4835 25.0531 11.3277 24.5569 11.3277C24.0661 11.3277 23.668 11.4976 23.3626 11.8374C23.0572 12.1772 22.9045 12.6161 22.9045 13.1541V18.4887H20.0088Z\" />\n <path d=\"M14.7486 10.9707C14.2851 10.9707 13.8952 11.1321 13.5789 11.4549C13.2626 11.7777 13.0854 12.1911 13.0472 12.6951H16.4337C16.4064 12.1741 16.2374 11.7579 15.9265 11.4464C15.6212 11.1293 15.2285 10.9707 14.7486 10.9707ZM16.4991 15.5153H19.1167C18.9749 16.4837 18.5141 17.2567 17.7343 17.8343C16.9599 18.4063 15.9838 18.6923 14.8059 18.6923C13.3662 18.6923 12.2374 18.2591 11.4194 17.3926C10.6014 16.5262 10.1924 15.3313 10.1924 13.8079C10.1924 12.2845 10.5987 11.0755 11.4112 10.1807C12.2237 9.28029 13.3226 8.83008 14.7077 8.83008C16.0656 8.83008 17.1481 9.26047 17.9552 10.1213C18.7677 10.9764 19.174 12.1231 19.174 13.5616V14.4195H13.0145V14.6064C13.0145 15.184 13.1835 15.6541 13.5216 16.0165C13.8597 16.3733 14.3015 16.5517 14.8468 16.5517C15.2503 16.5517 15.5993 16.461 15.8938 16.2798C16.1883 16.0929 16.3901 15.8381 16.4991 15.5153Z\" />\n <path d=\"M3.00205 8.58396V12.0667H4.7771C5.32789 12.0667 5.7587 11.911 6.06954 11.5995C6.38038 11.2881 6.5358 10.8662 6.5358 10.3338C6.5358 9.80718 6.37492 9.38528 6.05318 9.06815C5.73143 8.74535 5.30335 8.58396 4.76892 8.58396H3.00205ZM3.00205 14.1989V18.4886H0V6.23096H5.07158C6.53307 6.23096 7.65373 6.5849 8.43355 7.29278C9.21337 8.00066 9.60328 8.99453 9.60328 10.2744C9.60328 11.0446 9.42605 11.7439 9.07159 12.3725C8.71712 12.9955 8.2236 13.4514 7.59101 13.7402L9.94684 18.4886H6.5767L4.55624 14.1989H3.00205Z\" />\n <path\n d=\"M65.7255 0.211478C65.0841 2.46724 63.3737 4.2455 61.2041 4.90969C60.932 4.99366 60.932 5.39096 61.2041 5.47492C63.3725 6.13912 65.0841 7.91738 65.7255 10.1731C65.8056 10.4551 66.1932 10.4551 66.2745 10.1731C66.9159 7.91738 68.6263 6.13912 70.7959 5.47492C71.068 5.39096 71.068 4.99366 70.7959 4.90969C68.6276 4.2455 66.9159 2.46724 66.2745 0.211478C66.1944 -0.0704925 65.8068 -0.0704925 65.7255 0.211478Z\"\n fill={hovered ? \"#21FFB4\" : color}\n />\n </svg>\n );\n}\n\nexport function CopyIcon({ size = 14, color = \"#9EA0A1\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <rect\n x=\"5\"\n y=\"5\"\n width=\"9\"\n height=\"9\"\n rx=\"1\"\n stroke={color}\n strokeWidth=\"1.5\"\n />\n <path\n d=\"M11 5V3C11 2.44772 10.5523 2 10 2H3C2.44772 2 2 2.44772 2 3V10C2 10.5523 2.44772 11 3 11H5\"\n stroke={color}\n strokeWidth=\"1.5\"\n />\n </svg>\n );\n}\n\nexport function DisconnectIcon({ size = 14, color = \"#EA4335\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M6 14H3.33333C2.97971 14 2.64057 13.8595 2.39052 13.6095C2.14048 13.3594 2 13.0203 2 12.6667V3.33333C2 2.97971 2.14048 2.64057 2.39052 2.39052C2.64057 2.14048 2.97971 2 3.33333 2H6\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M10.6667 11.3333L14 8L10.6667 4.66667\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path\n d=\"M14 8H6\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\nexport function SpinnerIcon({ size = 14, color = \"currentColor\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n style={{ animation: \"spin 1s linear infinite\" }}\n >\n <style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>\n <path d=\"M8 1V4\" stroke={color} strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n <path\n d=\"M8 12V15\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.3\"\n />\n <path\n d=\"M3.05 3.05L5.17 5.17\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.9\"\n />\n <path\n d=\"M10.83 10.83L12.95 12.95\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.4\"\n />\n <path\n d=\"M1 8H4\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.8\"\n />\n <path\n d=\"M12 8H15\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.5\"\n />\n <path\n d=\"M3.05 12.95L5.17 10.83\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.7\"\n />\n <path\n d=\"M10.83 5.17L12.95 3.05\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n opacity=\"0.6\"\n />\n </svg>\n );\n}\n\nexport function ChevronDownIcon({\n size = 14,\n color = \"currentColor\",\n style,\n}: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n style={style}\n >\n <path\n d=\"M4 6L8 10L12 6\"\n stroke={color}\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n );\n}\n\nexport function UserIcon({ size = 24, color = \"#6366f1\" }: IconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <circle cx=\"12\" cy=\"8\" r=\"4\" stroke={color} strokeWidth=\"2\" />\n <path\n d=\"M4 20C4 16.6863 7.58172 14 12 14C16.4183 14 20 16.6863 20 20\"\n stroke={color}\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n />\n </svg>\n );\n}\n","import {\n type HTMLAttributes,\n type ReactElement,\n type ReactNode,\n type Ref,\n Children,\n cloneElement,\n forwardRef,\n isValidElement,\n} from \"react\";\n\ntype AnyProps = Record<string, unknown>;\n\nfunction mergeProps(parentProps: AnyProps, childProps: AnyProps): AnyProps {\n const merged: AnyProps = { ...parentProps };\n\n for (const key of Object.keys(childProps)) {\n const parentValue = parentProps[key];\n const childValue = childProps[key];\n\n if (key === \"style\") {\n merged[key] = { ...(parentValue as object), ...(childValue as object) };\n } else if (key === \"className\") {\n merged[key] = [parentValue, childValue].filter(Boolean).join(\" \");\n } else if (\n typeof parentValue === \"function\" &&\n typeof childValue === \"function\"\n ) {\n merged[key] = (...args: unknown[]) => {\n (childValue as (...a: unknown[]) => void)(...args);\n (parentValue as (...a: unknown[]) => void)(...args);\n };\n } else if (childValue !== undefined) {\n merged[key] = childValue;\n }\n }\n\n return merged;\n}\n\ninterface SlotProps extends HTMLAttributes<HTMLElement> {\n children?: ReactNode;\n ref?: Ref<HTMLElement>;\n}\n\nexport const Slot = forwardRef<HTMLElement, SlotProps>(\n ({ children, ...props }, ref) => {\n const child = Children.only(children);\n\n if (!isValidElement(child)) {\n return null;\n }\n\n const childElement = child as ReactElement<AnyProps>;\n const mergedProps = mergeProps(props, childElement.props);\n\n if (ref) {\n mergedProps.ref = ref;\n }\n\n return cloneElement(childElement, mergedProps);\n },\n);\n\nSlot.displayName = \"Slot\";\n","import type { CSSProperties, ReactNode } from \"react\";\nimport { useCallback, useState } from \"react\";\nimport { openRenown } from \"../utils.js\";\nimport { SpinnerIcon } from \"./icons.js\";\nimport { Slot } from \"./slot.js\";\n\nexport interface RenownLoginButtonProps {\n onLogin?: () => void;\n darkMode?: boolean;\n style?: CSSProperties;\n className?: string;\n asChild?: boolean;\n children?: ReactNode;\n}\n\nconst lightStyles = {\n trigger: {\n backgroundColor: \"#ffffff\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#d1d5db\",\n color: \"#111827\",\n },\n triggerHover: {\n backgroundColor: \"#ecf3f8\",\n borderColor: \"#9ca3af\",\n },\n} as const;\n\nconst darkStyles = {\n trigger: {\n backgroundColor: \"#1f2937\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#4b5563\",\n color: \"#ecf3f8\",\n },\n triggerHover: {\n backgroundColor: \"#374151\",\n borderColor: \"#6b7280\",\n },\n} as const;\n\nconst styles: Record<string, CSSProperties> = {\n wrapper: {\n position: \"relative\",\n display: \"inline-block\",\n },\n trigger: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n gap: \"8px\",\n padding: \"8px 32px\",\n borderRadius: \"8px\",\n cursor: \"pointer\",\n fontSize: \"14px\",\n fontWeight: 500,\n fontFamily: \"inherit\",\n lineHeight: \"20px\",\n transition: \"background-color 150ms, border-color 150ms\",\n },\n};\n\nexport function RenownLoginButton({\n onLogin: onLoginProp,\n darkMode = false,\n style,\n className,\n asChild = false,\n children,\n}: RenownLoginButtonProps) {\n const onLogin = onLoginProp ?? (() => openRenown());\n const [isLoading, setIsLoading] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n\n const handleMouseEnter = useCallback(() => setIsHovered(true), []);\n const handleMouseLeave = useCallback(() => setIsHovered(false), []);\n\n const handleClick = () => {\n if (!isLoading) {\n setIsLoading(true);\n onLogin();\n }\n };\n\n const themeStyles = darkMode ? darkStyles : lightStyles;\n\n const triggerStyle: CSSProperties = {\n ...styles.trigger,\n ...themeStyles.trigger,\n ...(isHovered && !isLoading ? themeStyles.triggerHover : {}),\n cursor: isLoading ? \"wait\" : \"pointer\",\n ...style,\n };\n\n const triggerElement = asChild ? (\n <Slot\n onClick={handleClick}\n data-renown-state=\"login\"\n {...(isLoading ? { \"data-loading\": \"\" } : {})}\n >\n {children}\n </Slot>\n ) : (\n <button\n type=\"button\"\n style={triggerStyle}\n aria-label=\"Log in with Renown\"\n onClick={handleClick}\n data-renown-state=\"login\"\n {...(isLoading ? { \"data-loading\": \"\" } : {})}\n >\n {isLoading ? <SpinnerIcon size={16} /> : <span>Log in</span>}\n </button>\n );\n\n return (\n <div\n style={styles.wrapper}\n className={className}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n {triggerElement}\n </div>\n );\n}\n","import type { CSSProperties, ReactNode } from \"react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useUser } from \"../../hooks/renown.js\";\nimport { logout as defaultLogout, openRenown } from \"../utils.js\";\nimport {\n ChevronDownIcon,\n CopyIcon,\n DisconnectIcon,\n UserIcon,\n} from \"./icons.js\";\nimport { Slot } from \"./slot.js\";\n\nconst POPOVER_GAP = 4;\nconst POPOVER_HEIGHT = 150;\n\nexport interface RenownUserButtonMenuItem {\n label: string;\n icon?: ReactNode;\n onClick: () => void;\n style?: CSSProperties;\n}\n\nexport interface RenownUserButtonProps {\n address?: string;\n username?: string;\n avatarUrl?: string;\n userId?: string;\n onDisconnect?: () => void;\n style?: CSSProperties;\n className?: string;\n asChild?: boolean;\n children?: ReactNode;\n menuItems?: RenownUserButtonMenuItem[];\n}\n\nconst styles: Record<string, CSSProperties> = {\n wrapper: {\n position: \"relative\",\n display: \"inline-block\",\n },\n trigger: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n padding: \"6px 12px\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#e5e7eb\",\n backgroundColor: \"#ffffff\",\n cursor: \"pointer\",\n borderRadius: \"8px\",\n fontSize: \"12px\",\n fontWeight: 500,\n fontFamily: \"inherit\",\n color: \"#111827\",\n transition: \"background-color 150ms, border-color 150ms\",\n },\n triggerHover: {\n backgroundColor: \"#f9fafb\",\n borderColor: \"#9ca3af\",\n },\n avatar: {\n width: \"28px\",\n height: \"28px\",\n borderRadius: \"50%\",\n objectFit: \"cover\",\n flexShrink: 0,\n },\n avatarPlaceholder: {\n width: \"28px\",\n height: \"28px\",\n borderRadius: \"50%\",\n background: \"linear-gradient(135deg, #8b5cf6, #3b82f6)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n flexShrink: 0,\n },\n avatarInitial: {\n fontSize: \"12px\",\n fontWeight: 700,\n color: \"#ffffff\",\n lineHeight: 1,\n },\n displayName: {\n maxWidth: \"120px\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n },\n chevron: {\n flexShrink: 0,\n transition: \"transform 150ms\",\n color: \"#6b7280\",\n },\n chevronOpen: {\n transform: \"rotate(180deg)\",\n },\n popoverBase: {\n position: \"absolute\",\n right: 0,\n backgroundColor: \"#ffffff\",\n borderRadius: \"8px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 3px rgba(0, 0, 0, 0.08)\",\n width: \"100%\",\n zIndex: 1000,\n color: \"#111827\",\n borderWidth: \"1px\",\n borderStyle: \"solid\",\n borderColor: \"#e5e7eb\",\n overflow: \"hidden\",\n },\n header: {\n padding: \"12px 16px\",\n borderBottom: \"1px solid #e5e7eb\",\n },\n headerUsername: {\n fontSize: \"14px\",\n fontWeight: 600,\n color: \"#111827\",\n margin: 0,\n },\n addressRow: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n marginTop: \"4px\",\n },\n addressButton: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n padding: 0,\n border: \"none\",\n backgroundColor: \"transparent\",\n cursor: \"pointer\",\n fontSize: \"12px\",\n color: \"#6b7280\",\n fontFamily: \"inherit\",\n position: \"relative\",\n width: \"100%\",\n },\n copiedText: {\n fontSize: \"12px\",\n color: \"#059669\",\n position: \"absolute\",\n left: 0,\n transition: \"opacity 150ms\",\n fontWeight: 500,\n },\n addressText: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n transition: \"opacity 150ms\",\n },\n menuSection: {\n padding: \"4px 0\",\n },\n menuItem: {\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n width: \"100%\",\n padding: \"8px 16px\",\n border: \"none\",\n backgroundColor: \"transparent\",\n cursor: \"pointer\",\n fontSize: \"14px\",\n color: \"#374151\",\n textDecoration: \"none\",\n fontFamily: \"inherit\",\n transition: \"background-color 150ms\",\n },\n menuItemHover: {\n backgroundColor: \"#f3f4f6\",\n },\n disconnectItem: {\n color: \"#dc2626\",\n },\n separator: {\n height: \"1px\",\n backgroundColor: \"#e5e7eb\",\n margin: 0,\n border: \"none\",\n },\n};\n\nfunction truncateAddress(address: string): string {\n if (address.length <= 13) return address;\n return `${address.slice(0, 7)}...${address.slice(-5)}`;\n}\n\nexport function RenownUserButton({\n address: addressProp,\n username: usernameProp,\n avatarUrl: avatarUrlProp,\n userId: userIdProp,\n onDisconnect: onDisconnectProp,\n style,\n className,\n asChild = false,\n children,\n menuItems,\n}: RenownUserButtonProps) {\n const user = useUser();\n\n const address = addressProp ?? user?.address ?? \"\";\n const username = usernameProp ?? user?.profile?.username ?? user?.ens?.name;\n const avatarUrl =\n avatarUrlProp ?? user?.profile?.userImage ?? user?.ens?.avatarUrl;\n const userId = userIdProp ?? user?.profile?.documentId;\n const onDisconnect = onDisconnectProp ?? (() => void defaultLogout());\n const displayName =\n username ?? (address ? truncateAddress(address) : \"Account\");\n const profileId = userId ?? address;\n\n const [isOpen, setIsOpen] = useState(false);\n const [isHovered, setIsHovered] = useState(false);\n const [isCopied, setIsCopied] = useState(false);\n const [showAbove, setShowAbove] = useState(true);\n const [hoveredItem, setHoveredItem] = useState<string | null>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const closeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const calculatePosition = useCallback(() => {\n if (!wrapperRef.current) return;\n const rect = wrapperRef.current.getBoundingClientRect();\n const spaceAbove = rect.top;\n setShowAbove(spaceAbove >= POPOVER_HEIGHT + POPOVER_GAP);\n }, []);\n\n const handleMouseEnter = useCallback(() => {\n setIsHovered(true);\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = null;\n }\n calculatePosition();\n setIsOpen(true);\n }, [calculatePosition]);\n\n const handleMouseLeave = useCallback(() => {\n closeTimeoutRef.current = setTimeout(() => {\n setIsOpen(false);\n setIsHovered(false);\n setHoveredItem(null);\n }, 150);\n }, []);\n\n useEffect(() => {\n return () => {\n if (closeTimeoutRef.current) {\n clearTimeout(closeTimeoutRef.current);\n }\n };\n }, []);\n\n const copyToClipboard = useCallback(async () => {\n try {\n await navigator.clipboard.writeText(address);\n setIsCopied(true);\n setTimeout(() => setIsCopied(false), 2000);\n } catch (err) {\n console.error(\"Failed to copy address:\", err);\n }\n }, [address]);\n\n const triggerElement = asChild ? (\n <Slot data-renown-state=\"authenticated\">{children}</Slot>\n ) : (\n <button\n type=\"button\"\n style={{\n ...styles.trigger,\n ...(isHovered ? styles.triggerHover : {}),\n ...style,\n }}\n aria-label=\"Open account menu\"\n data-renown-state=\"authenticated\"\n >\n {avatarUrl ? (\n <img src={avatarUrl} alt=\"Avatar\" style={styles.avatar} />\n ) : (\n <div style={styles.avatarPlaceholder}>\n <span style={styles.avatarInitial}>\n {(displayName || \"U\")[0].toUpperCase()}\n </span>\n </div>\n )}\n <span style={styles.displayName}>{displayName}</span>\n <ChevronDownIcon\n size={14}\n style={{\n ...styles.chevron,\n ...(isOpen ? styles.chevronOpen : {}),\n }}\n />\n </button>\n );\n\n return (\n <div\n ref={wrapperRef}\n style={styles.wrapper}\n className={className}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n >\n {triggerElement}\n {isOpen && (\n <div\n style={{\n ...styles.popoverBase,\n ...(showAbove\n ? { bottom: `calc(100% + ${POPOVER_GAP}px)` }\n : { top: `calc(100% + ${POPOVER_GAP}px)` }),\n }}\n >\n <div style={styles.header}>\n {username && <div style={styles.headerUsername}>{username}</div>}\n {address && (\n <div style={styles.addressRow}>\n <button\n type=\"button\"\n onClick={() => void copyToClipboard()}\n style={styles.addressButton}\n >\n <div\n style={{\n position: \"relative\",\n display: \"flex\",\n alignItems: \"center\",\n gap: \"4px\",\n width: \"100%\",\n }}\n >\n <div\n style={{\n ...styles.addressText,\n opacity: isCopied ? 0 : 1,\n }}\n >\n <span>{truncateAddress(address)}</span>\n <CopyIcon size={12} color=\"#9ca3af\" />\n </div>\n <div\n style={{\n ...styles.copiedText,\n opacity: isCopied ? 1 : 0,\n }}\n >\n Copied!\n </div>\n </div>\n </button>\n </div>\n )}\n </div>\n <div style={styles.menuSection}>\n {profileId && (\n <button\n type=\"button\"\n onClick={() => openRenown(profileId)}\n onMouseEnter={() => setHoveredItem(\"profile\")}\n onMouseLeave={() => setHoveredItem(null)}\n style={{\n ...styles.menuItem,\n ...(hoveredItem === \"profile\" ? styles.menuItemHover : {}),\n }}\n >\n <UserIcon size={14} color=\"#6b7280\" />\n View Profile\n </button>\n )}\n {menuItems?.map((item) => (\n <button\n key={item.label}\n type=\"button\"\n onClick={item.onClick}\n onMouseEnter={() => setHoveredItem(item.label)}\n onMouseLeave={() => setHoveredItem(null)}\n style={{\n ...styles.menuItem,\n ...(hoveredItem === item.label ? styles.menuItemHover : {}),\n ...item.style,\n }}\n >\n {item.icon}\n {item.label}\n </button>\n ))}\n </div>\n <hr style={styles.separator} />\n <div style={styles.menuSection}>\n <button\n type=\"button\"\n onClick={onDisconnect}\n onMouseEnter={() => setHoveredItem(\"disconnect\")}\n onMouseLeave={() => setHoveredItem(null)}\n style={{\n ...styles.menuItem,\n ...styles.disconnectItem,\n ...(hoveredItem === \"disconnect\" ? styles.menuItemHover : {}),\n }}\n >\n <DisconnectIcon size={14} color=\"#dc2626\" />\n Log out\n </button>\n </div>\n </div>\n )}\n </div>\n );\n}\n","import type { ReactNode } from \"react\";\nimport { type RenownAuth, useRenownAuth } from \"../use-renown-auth.js\";\nimport { RenownLoginButton } from \"./RenownLoginButton.js\";\nimport { RenownUserButton } from \"./RenownUserButton.js\";\n\nexport interface RenownAuthButtonProps {\n className?: string;\n darkMode?: boolean;\n loginContent?: ReactNode;\n userContent?: ReactNode;\n loadingContent?: ReactNode;\n children?: (auth: RenownAuth) => ReactNode;\n}\n\nexport function RenownAuthButton({\n className = \"\",\n darkMode,\n loginContent,\n userContent,\n loadingContent,\n children,\n}: RenownAuthButtonProps) {\n const auth = useRenownAuth();\n\n if (children) {\n return <>{children(auth)}</>;\n }\n\n if (auth.status === \"loading\" || auth.status === \"checking\") {\n if (loadingContent) {\n return <div className={className}>{loadingContent}</div>;\n }\n\n return (\n <div className={className}>\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n padding: \"6px 12px\",\n borderRadius: \"8px\",\n border: \"1px solid #e5e7eb\",\n animation: \"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite\",\n }}\n >\n <div\n style={{\n width: \"28px\",\n height: \"28px\",\n borderRadius: \"50%\",\n backgroundColor: \"#e5e7eb\",\n }}\n />\n <div\n style={{\n width: \"80px\",\n height: \"14px\",\n borderRadius: \"4px\",\n backgroundColor: \"#e5e7eb\",\n }}\n />\n </div>\n <style>{`@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }`}</style>\n </div>\n );\n }\n\n if (auth.status === \"authorized\") {\n if (userContent) {\n return <div className={className}>{userContent}</div>;\n }\n\n return (\n <div className={className}>\n <RenownUserButton />\n </div>\n );\n }\n\n if (loginContent) {\n return <div className={className}>{loginContent}</div>;\n }\n\n return (\n <div className={className}>\n <RenownLoginButton darkMode={darkMode} />\n </div>\n );\n}\n","import type { IRenown } from \"@renown/sdk\";\nimport { RenownBuilder } from \"@renown/sdk\";\nimport { useRef } from \"react\";\nimport { loading } from \"../hooks/loading.js\";\nimport { addRenownEventHandler, setRenown } from \"../hooks/renown.js\";\nimport { login } from \"./utils.js\";\n\nexport interface RenownInitOptions {\n appName: string;\n /**\n * Prefix for localStorage keys, allowing multiple apps\n * to use Renown on the same domain without conflicts.\n */\n namespace?: string;\n url?: string;\n}\n\nasync function initRenown(\n appName: string,\n namespace: string | undefined,\n url: string | undefined,\n): Promise<IRenown> {\n addRenownEventHandler();\n setRenown(loading);\n\n const builder = new RenownBuilder(appName, {\n basename: namespace,\n baseUrl: url,\n });\n const renown = await builder.build();\n setRenown(renown);\n\n await login(undefined, renown);\n\n return renown;\n}\n\n/**\n * Hook that initializes the Renown SDK.\n * Call once at the top of your app. Options are read only on first mount.\n * Returns a promise that resolves with the Renown instance.\n *\n * @example\n * ```tsx\n * function App() {\n * const renownPromise = useRenownInit({ appName: \"my-app\" });\n * return <MyApp />;\n * }\n * ```\n */\nexport function useRenownInit({\n appName,\n namespace,\n url,\n}: RenownInitOptions): Promise<IRenown> {\n const promiseRef = useRef(Promise.withResolvers<IRenown>());\n const initRef = useRef(false);\n\n if (typeof window === \"undefined\") {\n promiseRef.current.reject(new Error(\"window is undefined\"));\n return promiseRef.current.promise;\n }\n\n if (initRef.current) {\n return promiseRef.current.promise;\n }\n\n initRef.current = true;\n\n initRenown(appName, namespace, url)\n .then(promiseRef.current.resolve)\n .catch(promiseRef.current.reject);\n\n return promiseRef.current.promise;\n}\n","import { type RenownInitOptions, useRenownInit } from \"./use-renown-init.js\";\n\nexport interface RenownProps extends RenownInitOptions {\n onError?: (error: unknown) => void;\n}\n\n/**\n * Side-effect component that initializes the Renown SDK.\n * Renders nothing — place it alongside your app tree.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <>\n * <Renown appName=\"my-app\" onError={console.error} />\n * <MyApp />\n * </>\n * );\n * }\n * ```\n */\nexport function Renown({ onError, ...initOptions }: RenownProps) {\n useRenownInit(initOptions).catch(onError ?? console.error);\n return null;\n}\n","export abstract class BaseStorage<V> implements Iterable<[string, V]> {\n abstract get(key: string): V | undefined;\n abstract set(key: string, value: V): void;\n abstract delete(key: string): boolean;\n abstract has(key: string): boolean;\n abstract clear(): void;\n abstract entries(): IterableIterator<[string, V]>;\n abstract keys(): IterableIterator<string>;\n abstract values(): IterableIterator<V>;\n\n [Symbol.iterator](): IterableIterator<[string, V]> {\n return this.entries();\n }\n\n forEach(\n callback: (value: V, key: string, storage: BaseStorage<V>) => void,\n ): void {\n for (const [key, value] of this) {\n callback(value, key, this);\n }\n }\n}\n","import { BaseStorage } from \"./base-storage.js\";\n\nexport class BrowserLocalStorage<V> extends BaseStorage<V> {\n #namespace: string;\n #storage = window.localStorage;\n constructor(namespace: string) {\n super();\n this.#namespace = namespace;\n }\n\n #readMap(): Map<string, V> {\n const raw = this.#storage.getItem(this.#namespace);\n\n if (!raw) {\n return new Map();\n }\n\n return new Map(JSON.parse(raw) as [string, V][]);\n }\n\n #writeMap(map: Map<string, V>): void {\n this.#storage.setItem(\n this.#namespace,\n JSON.stringify(Array.from(map.entries())),\n );\n }\n\n get(key: string): V | undefined {\n return this.#readMap().get(key);\n }\n\n set(key: string, value: V): void {\n const map = this.#readMap();\n map.set(key, value);\n this.#writeMap(map);\n }\n\n delete(key: string): boolean {\n const map = this.#readMap();\n const deleted = map.delete(key);\n if (deleted) {\n this.#writeMap(map);\n }\n return deleted;\n }\n\n has(key: string): boolean {\n return this.#readMap().has(key);\n }\n\n clear(): void {\n this.#storage.removeItem(this.#namespace);\n }\n\n entries(): IterableIterator<[string, V]> {\n return this.#readMap().entries();\n }\n\n keys(): IterableIterator<string> {\n return this.#readMap().keys();\n }\n\n values(): IterableIterator<V> {\n return this.#readMap().values();\n }\n\n [Symbol.iterator](): IterableIterator<[string, V]> {\n return this.#readMap().entries();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AASA,eAAsB,aACpB,UACA,iBACA;AACA,KAAI,CAAC,SACH,OAAM,IAAI,MAAM,uBAAuB;AAEzC,KAAI,CAAC,gBACH,OAAM,IAAI,MAAM,sBAAsB;CAExC,MAAM,UAAU,MAAM,QAAQ,gBAAgB,GAC1C,kBACA,CAAC,gBAAgB;AAErB,KAAI,QAAQ,WAAW,EACrB,OAAM,IAAI,MAAM,sBAAsB;CAGxC,MAAM,gBAAgB,OAAO,IAAI;AACjC,KAAI,CAAC,cACH,OAAM,IAAI,MAAM,gCAAgC;AAGlD,QAAO,MAAM,cAAc,QAAQ,SAAS,OAAO,IAAI,QAAQ,QAAQ;;AAGzE,eAAsB,gBACpB,YACA,uBACA;AACA,KAAI,CAAC,WACH,OAAM,IAAI,MAAM,yBAAyB;AAE3C,KAAI,CAAC,sBACH,OAAM,IAAI,MAAM,yBAAyB;CAE3C,MAAM,aAAa,MAAM,QAAQ,sBAAsB,GACnD,wBACA,CAAC,sBAAsB;AAE3B,KAAI,WAAW,WAAW,EACxB,OAAM,IAAI,MAAM,yBAAyB;CAG3C,MAAM,gBAAgB,OAAO,IAAI;AACjC,KAAI,CAAC,cACH,OAAM,IAAI,MAAM,gCAAgC;CAGlD,MAAM,UAAU,WAAW,KAAK,OAAO,GAAG,OAAO;AACjD,QAAO,MAAM,cAAc,QAAQ,YAAY,QAAQ,QAAQ;;AAqFjE,eAAsB,iBACpB,YACA,eACA,gBAIA,SAI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