@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.2 → 6.2.3-dev.4

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.
Files changed (51) hide show
  1. package/dist/browser/{connect-BqgnsniX.js → connect-BtHSAuSc.js} +10 -4
  2. package/dist/browser/{connect-BqgnsniX.js.map → connect-BtHSAuSc.js.map} +1 -1
  3. package/dist/browser/{dist-C-xkNfyD.js → dist-D69hfRZN.js} +8 -8
  4. package/dist/browser/dist-D69hfRZN.js.map +1 -0
  5. package/dist/browser/{document-drive-ZQzPQfEL.js → document-drive-BEXJ-rHp.js} +61 -21
  6. package/dist/browser/{document-drive-ZQzPQfEL.js.map → document-drive-BEXJ-rHp.js.map} +1 -1
  7. package/dist/browser/document-models/index.js +1 -1
  8. package/dist/browser/{editor-DZP1WlYy.js → editor-Cbl_EDjI.js} +5 -5
  9. package/dist/browser/{editor-DZP1WlYy.js.map → editor-Cbl_EDjI.js.map} +1 -1
  10. package/dist/browser/{editor-BNgF9-uX.js → editor-mNThkZOv.js} +6 -6
  11. package/dist/browser/{editor-BNgF9-uX.js.map → editor-mNThkZOv.js.map} +1 -1
  12. package/dist/browser/editors/document-model-editor/module.js +1 -1
  13. package/dist/browser/editors/generic-drive-explorer/index.js +4 -4
  14. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  15. package/dist/browser/{folder-view-tx0A96ZI.js → folder-view-D8AkN1Oj.js} +3 -3
  16. package/dist/browser/{folder-view-tx0A96ZI.js.map → folder-view-D8AkN1Oj.js.map} +1 -1
  17. package/dist/browser/{graphql-editor-Cbkb5KRZ.js → graphql-editor-BcL3-Zha.js} +3 -3
  18. package/dist/browser/{graphql-editor-Cbkb5KRZ.js.map → graphql-editor-BcL3-Zha.js.map} +1 -1
  19. package/dist/browser/index.js +1 -1
  20. package/dist/browser/{json-editor-CN6kPtl1.js → json-editor-DHXQRIN5.js} +3 -3
  21. package/dist/browser/{json-editor-CN6kPtl1.js.map → json-editor-DHXQRIN5.js.map} +1 -1
  22. package/dist/browser/lib-ewnRj2dJ.js.map +1 -1
  23. package/dist/browser/{state-schemas-CKh98ehP.js → state-schemas-C4F8lReN.js} +3 -3
  24. package/dist/browser/{state-schemas-CKh98ehP.js.map → state-schemas-C4F8lReN.js.map} +1 -1
  25. package/dist/node/{connect-CeLh6yfj.mjs → connect-B6IQsY6u.mjs} +10 -4
  26. package/dist/node/{connect-CeLh6yfj.mjs.map → connect-B6IQsY6u.mjs.map} +1 -1
  27. package/dist/node/{dist-CUFTZwfc.mjs → dist-hd-KLWy7.mjs} +8 -8
  28. package/dist/node/dist-hd-KLWy7.mjs.map +1 -0
  29. package/dist/node/{document-drive-D1NMjQQc.mjs → document-drive-CkV9NvD7.mjs} +61 -21
  30. package/dist/node/{document-drive-D1NMjQQc.mjs.map → document-drive-CkV9NvD7.mjs.map} +1 -1
  31. package/dist/node/document-models/index.mjs +1 -1
  32. package/dist/node/{editor-CXQOsbup.mjs → editor-C93fdI28.mjs} +6 -6
  33. package/dist/node/{editor-CXQOsbup.mjs.map → editor-C93fdI28.mjs.map} +1 -1
  34. package/dist/node/{editor-Dg2OZEJu.mjs → editor-DG1q4Y55.mjs} +5 -5
  35. package/dist/node/{editor-Dg2OZEJu.mjs.map → editor-DG1q4Y55.mjs.map} +1 -1
  36. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  37. package/dist/node/editors/generic-drive-explorer/index.mjs +4 -4
  38. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  39. package/dist/node/{folder-view-DZ0o2-Ef.mjs → folder-view-BGabHV7H.mjs} +3 -3
  40. package/dist/node/{folder-view-DZ0o2-Ef.mjs.map → folder-view-BGabHV7H.mjs.map} +1 -1
  41. package/dist/node/{graphql-editor-DNxebuTn.mjs → graphql-editor-B-XIb6az.mjs} +3 -3
  42. package/dist/node/{graphql-editor-DNxebuTn.mjs.map → graphql-editor-B-XIb6az.mjs.map} +1 -1
  43. package/dist/node/index.mjs +1 -1
  44. package/dist/node/{json-editor-BpnEn9AS.mjs → json-editor-DB0vi6tV.mjs} +3 -3
  45. package/dist/node/{json-editor-BpnEn9AS.mjs.map → json-editor-DB0vi6tV.mjs.map} +1 -1
  46. package/dist/node/main-B1tRsYOp.mjs.map +1 -1
  47. package/dist/node/{state-schemas-CuSHxrn6.mjs → state-schemas-BGsgtEG1.mjs} +3 -3
  48. package/dist/node/{state-schemas-CuSHxrn6.mjs.map → state-schemas-BGsgtEG1.mjs.map} +1 -1
  49. package/package.json +7 -7
  50. package/dist/browser/dist-C-xkNfyD.js.map +0 -1
  51. package/dist/node/dist-CUFTZwfc.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-hd-KLWy7.mjs","names":["isServer","isPlainObject","isPlainObject","Kind","createClient","e","t","e","t","e","n","e","t","n","e","t","e","n","e","t","n","e","e","e","e","e","isLikeCloseEvent","conditional","isNot","isDefined","constant","isStrictEqual","Kind","funnel","isTruthy","allPass","isString","once","isPlainObj","hasAtLeast","addFolder","Kind","lzString","isDefined","DriveCollectionId$1"],"sources":["../../../reactor-browser/dist/make-ph-event-functions-DBq3iWYn.js","../../../reactor-browser/dist/document-by-id-B4FIzG1w.js","../../../../node_modules/.pnpm/slug@11.0.1/node_modules/slug/slug.js","../../../reactor-browser/dist/document-model-modules-bTP87nyr.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/classes/ClientError.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/lib/prelude.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/functions/batchRequests.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/functions/rawRequest.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/lib/http.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/lib/graphql.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/helpers/analyzeDocument.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/helpers/defaultJsonSerializer.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/helpers/runRequest.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/classes/GraphQLClient.js","../../../../node_modules/.pnpm/graphql-request@7.4.0_graphql@16.12.0/node_modules/graphql-request/build/legacy/functions/request.js","../../../reactor-browser/dist/client-D66jVnot.js","../../../reactor-browser/dist/renown-BHxwP7xU.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/lazyDataLastImpl-DtF3cihj.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/purry.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/allPass.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/conditional-CTEJD5TX.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/constant.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/hasAtLeast.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/funnel.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isDefined.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isNot.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isStrictEqual.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isString.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/isTruthy.js","../../../../node_modules/.pnpm/remeda@2.33.7/node_modules/remeda/dist/once.js","../../../../node_modules/.pnpm/graphql-ws@6.0.7_@fastify+websocket@11.2.0_bufferutil@4.1.0_utf-8-validate@5.0.10__cros_de7c65f79652658db92f49b1a0ce8072/node_modules/graphql-ws/dist/common-CGW11Fyb.js","../../../../node_modules/.pnpm/graphql-ws@6.0.7_@fastify+websocket@11.2.0_bufferutil@4.1.0_utf-8-validate@5.0.10__cros_de7c65f79652658db92f49b1a0ce8072/node_modules/graphql-ws/dist/client.js","../../../reactor-browser/dist/document-operations-WeE6wIDt.js","../../../reactor-browser/dist/switchboard-CaXQ4-5Q.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/descriptors.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/aggregate.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/cause.js","../../../../node_modules/.pnpm/is-error-instance@3.0.1/node_modules/is-error-instance/build/src/main.js","../../../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/modifiable.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/stack.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/copy.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/object.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/string.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/create/main.js","../../../../node_modules/.pnpm/normalize-exception@4.0.1/node_modules/normalize-exception/build/src/main.js","../../../../node_modules/.pnpm/lz-string@1.5.0/node_modules/lz-string/libs/lz-string.js","../../../reactor-browser/dist/index.js"],"sourcesContent":["import { capitalCase } from \"change-case\";\nimport { useSyncExternalStore } from \"react\";\n//#region src/hooks/make-ph-event-functions.ts\nconst isServer = typeof window === \"undefined\";\nfunction makePHEventFunctions(key) {\n\tconst setEventName = `ph:set${capitalCase(key)}`;\n\tconst updateEventName = `ph:${key}Updated`;\n\tfunction setValue(value) {\n\t\tif (isServer) return;\n\t\tconst event = new CustomEvent(setEventName, { detail: { [key]: value } });\n\t\twindow.dispatchEvent(event);\n\t}\n\tfunction dispatchUpdatedEvent() {\n\t\tif (isServer) return;\n\t\tconst event = new CustomEvent(updateEventName);\n\t\twindow.dispatchEvent(event);\n\t}\n\tfunction handleSetValueEvent(event) {\n\t\tif (isServer) return;\n\t\tconst value = event.detail[key];\n\t\tif (!window.ph) window.ph = {};\n\t\twindow.ph[key] = value;\n\t\tdispatchUpdatedEvent();\n\t}\n\tfunction addEventHandler() {\n\t\tif (isServer) return;\n\t\twindow.addEventListener(setEventName, handleSetValueEvent);\n\t}\n\tfunction subscribeToValue(onStoreChange) {\n\t\tif (isServer) return () => {};\n\t\twindow.addEventListener(updateEventName, onStoreChange);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(updateEventName, onStoreChange);\n\t\t};\n\t}\n\tfunction getSnapshot() {\n\t\tif (isServer) return;\n\t\treturn window.ph?.[key];\n\t}\n\tfunction getServerSnapshot() {}\n\tfunction useValue() {\n\t\treturn useSyncExternalStore(subscribeToValue, getSnapshot, getServerSnapshot);\n\t}\n\treturn {\n\t\tuseValue,\n\t\tsetValue,\n\t\taddEventHandler\n\t};\n}\n//#endregion\nexport { makePHEventFunctions as t };\n\n//# sourceMappingURL=make-ph-event-functions-DBq3iWYn.js.map","import { t as makePHEventFunctions } from \"./make-ph-event-functions-DBq3iWYn.js\";\nimport { logger } from \"document-model\";\nimport { buildSignedAction } from \"@powerhousedao/shared/document-model\";\nimport { use, useCallback, useEffect, useReducer, useSyncExternalStore } from \"react\";\n//#region src/actions/queue.ts\nasync function queueActions(document, actionOrActions) {\n\tif (!document) throw new Error(\"No document provided\");\n\tif (!actionOrActions) throw new Error(\"No actions provided\");\n\tconst actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];\n\tif (actions.length === 0) throw new Error(\"No actions provided\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(document.header.id, \"main\", actions);\n}\nasync function queueOperations(documentId, operationOrOperations) {\n\tif (!documentId) throw new Error(\"No documentId provided\");\n\tif (!operationOrOperations) throw new Error(\"No operations provided\");\n\tconst operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];\n\tif (operations.length === 0) throw new Error(\"No operations provided\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst actions = operations.map((op) => op.action);\n\treturn await reactorClient.execute(documentId, \"main\", actions);\n}\nasync function uploadOperations(documentId, allOperations, pushOperations, options) {\n\tconst operationsLimit = options?.operationsLimit || 50;\n\tconst onProgress = options?.onProgress;\n\tlogger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(\",\")}, limit:${operationsLimit})`);\n\tconst allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);\n\tconst totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);\n\tlet uploadedOperations = 0;\n\tfor (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {\n\t\tlogger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);\n\t\tconst chunk = operations.slice(i, i + operationsLimit);\n\t\tconst operation = chunk.at(-1);\n\t\tif (!operation) break;\n\t\tconst scope = operation.action.scope;\n\t\tawait pushOperations(documentId, chunk);\n\t\tuploadedOperations += chunk.length;\n\t\tif (onProgress) onProgress({\n\t\t\tstage: \"uploading\",\n\t\t\tprogress: Math.round(uploadedOperations / totalOperations * 100),\n\t\t\ttotalOperations,\n\t\t\tuploadedOperations\n\t\t});\n\t\tlogger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);\n\t}\n\tlogger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);\n}\n//#endregion\n//#region src/actions/sign.ts\nasync function signAction(action, document) {\n\tconst renown = window.ph?.renown;\n\tif (!renown?.user) return action;\n\tif (!action.context?.signer) return action;\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) return action;\n\tconst reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;\n\tconst actionSigner = action.context.signer;\n\treturn await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);\n}\nfunction addActionContext(action) {\n\tconst renown = window.ph?.renown;\n\tif (!renown?.user) return action;\n\treturn {\n\t\tcontext: { signer: {\n\t\t\tapp: {\n\t\t\t\tname: \"Connect\",\n\t\t\t\tkey: renown.did\n\t\t\t},\n\t\t\tuser: {\n\t\t\t\taddress: renown.user.address,\n\t\t\t\tnetworkId: renown.user.networkId,\n\t\t\t\tchainId: renown.user.chainId\n\t\t\t},\n\t\t\tsignatures: []\n\t\t} },\n\t\t...action\n\t};\n}\nasync function makeSignedActionWithContext(action, document) {\n\tif (!action) {\n\t\tlogger.error(\"No action found\");\n\t\treturn;\n\t}\n\tif (!document) {\n\t\tlogger.error(\"No document found\");\n\t\treturn;\n\t}\n\treturn addActionContext(await signAction(action, document));\n}\nasync function makeSignedActionsWithContext(actionOrActions, document) {\n\tif (!actionOrActions) {\n\t\tlogger.error(\"No actions found\");\n\t\treturn;\n\t}\n\tconst actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];\n\treturn (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);\n}\n//#endregion\n//#region src/actions/dispatch.ts\nasync function getDocument(documentId) {\n\ttry {\n\t\treturn await window.ph?.reactorClient?.get(documentId);\n\t} catch (error) {\n\t\tlogger.debug(`Failed to get document with id ${documentId}:`, error);\n\t\treturn;\n\t}\n}\nfunction getActionErrors(result, actions) {\n\treturn actions.reduce((errors, a) => {\n\t\tconst scopeOperations = result.operations[a.scope];\n\t\tif (!scopeOperations) return errors;\n\t\tconst op = scopeOperations.findLast((op) => op.action.id === a.id);\n\t\tif (op?.error) errors.push(new Error(op.error));\n\t\treturn errors;\n\t}, new Array());\n}\nasync function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {\n\tconst document = typeof documentOrDocumentId === \"string\" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;\n\tif (!document) {\n\t\tlogger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);\n\t\treturn;\n\t}\n\tconst signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);\n\tif (!signedActionsWithContext) {\n\t\tlogger.error(\"No signed actions with context found\");\n\t\treturn;\n\t}\n\tconst result = await queueActions(document, signedActionsWithContext);\n\tif (onErrors && result) {\n\t\tconst errors = getActionErrors(result, signedActionsWithContext);\n\t\tif (errors.length) onErrors(errors);\n\t}\n\tif (onSuccess && result) onSuccess(result);\n\treturn result;\n}\n/**\n* The reactor's `DocumentChangeType` members, typed as the enum so they can be\n* assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a\n* TypeScript string enum is nominal, so no string literal is assignable to it\n* without one - and the two checks above are what make it safe.\n*/\nconst DOCUMENT_CHANGE_TYPE = {\n\tCreated: \"created\",\n\tDeleted: \"deleted\",\n\tUpdated: \"updated\",\n\tParentAdded: \"parent_added\",\n\tParentRemoved: \"parent_removed\",\n\tChildAdded: \"child_added\",\n\tChildRemoved: \"child_removed\"\n};\n/**\n* Structural equivalents of the reactor error classes' own static `isError`\n* guards. Those guards match on `error.name` rather than the prototype chain\n* (`packages/reactor/src/registry/errors.ts`), so re-implementing them here is\n* behaviour-preserving and does not need the class at runtime.\n*/\nfunction isDuplicateModuleError(error) {\n\treturn Error.isError(error) && error.name === \"DuplicateModuleError\";\n}\nfunction isDuplicateManifestError(error) {\n\treturn Error.isError(error) && error.name === \"DuplicateManifestError\";\n}\n//#endregion\n//#region src/document-cache.ts\nfunction addPromiseState(promise) {\n\tif (\"status\" in promise) return promise;\n\tconst promiseWithState = promise;\n\tpromiseWithState.status = \"pending\";\n\tpromiseWithState.then((value) => {\n\t\tpromiseWithState.status = \"fulfilled\";\n\t\tpromiseWithState.value = value;\n\t}, (reason) => {\n\t\tpromiseWithState.status = \"rejected\";\n\t\tpromiseWithState.reason = reason;\n\t\tthrow reason;\n\t});\n\treturn promiseWithState;\n}\nfunction readPromiseState(promise) {\n\treturn \"status\" in promise ? promise : { status: \"pending\" };\n}\n/**\n* Resolves an array of document promises using `Promise.allSettled`,\n* returning only the fulfilled values. A single missing/rejected\n* document does not poison the whole batch. Rejected entries are\n* logged at warn level so developers can see dangling references.\n*/\nfunction fulfilledOnly(promises) {\n\treturn Promise.allSettled(promises).then((results) => {\n\t\tconst documents = [];\n\t\tfor (const result of results) if (result.status === \"fulfilled\") documents.push(result.value);\n\t\telse console.warn(\"[DocumentCache] Skipped unavailable document:\", result.reason);\n\t\treturn documents;\n\t});\n}\n/**\n* Document cache implementation that uses the new ReactorClient API.\n*\n* This cache subscribes to document change events via IReactorBrowserClient.subscribe()\n* and automatically updates the cache when documents are created, updated, or deleted.\n*/\nvar DocumentCache = class {\n\tdocuments = /* @__PURE__ */ new Map();\n\tbatchPromises = /* @__PURE__ */ new Map();\n\tlisteners = /* @__PURE__ */ new Map();\n\t/**\n\t* Cache keys that fetched a document under a name other than its id --\n\t* slugs, which `client.get` resolves. Change events dispatch by `header.id`,\n\t* so without this mapping a slug-keyed entry (and its listeners) would never\n\t* see an update: keyed by the id the events carry, valued by the other keys\n\t* the same document is cached under.\n\t*/\n\taliasKeys = /* @__PURE__ */ new Map();\n\tunsubscribe = null;\n\tconstructor(client) {\n\t\tthis.client = client;\n\t\tthis.unsubscribe = client.subscribe({}, (event) => {\n\t\t\tthis.handleDocumentChange(event);\n\t\t});\n\t}\n\thandleDocumentChange(event) {\n\t\tif (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {\n\t\t\tconst documentId = event.context?.childId;\n\t\t\tif (documentId) this.handleDocumentDeleted(documentId);\n\t\t} else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) this.handleDocumentUpdated(doc.header.id).catch(console.warn);\n\t}\n\thandleDocumentDeleted(documentId) {\n\t\tfor (const key of this.cacheKeysFor(documentId)) {\n\t\t\tconst listeners = this.listeners.get(key);\n\t\t\tthis.documents.delete(key);\n\t\t\tthis.invalidateBatchesContaining(key);\n\t\t\tif (listeners) listeners.forEach((listener) => listener());\n\t\t\tthis.listeners.delete(key);\n\t\t}\n\t\tthis.aliasKeys.delete(documentId);\n\t}\n\tasync handleDocumentUpdated(documentId) {\n\t\tfor (const key of this.cacheKeysFor(documentId)) {\n\t\t\tif (!this.documents.has(key)) continue;\n\t\t\tawait this.get(key, true);\n\t\t\tconst listeners = this.listeners.get(key);\n\t\t\tif (listeners) listeners.forEach((listener) => listener());\n\t\t}\n\t}\n\t/** The id an event dispatches by, plus every alias the document is cached under. */\n\tcacheKeysFor(documentId) {\n\t\treturn [documentId, ...this.aliasKeys.get(documentId) ?? []];\n\t}\n\t/** Records that `key` cached the document change events know as `header.id`. */\n\trecordAlias(documentId, key) {\n\t\tconst keys = this.aliasKeys.get(documentId) ?? /* @__PURE__ */ new Set();\n\t\tkeys.add(key);\n\t\tthis.aliasKeys.set(documentId, keys);\n\t}\n\tinvalidateBatchesContaining(documentId) {\n\t\tfor (const key of this.batchPromises.keys()) if (key.split(\",\").includes(documentId)) this.batchPromises.delete(key);\n\t}\n\tget(id, refetch) {\n\t\tconst currentData = this.documents.get(id);\n\t\tif (currentData) {\n\t\t\tif (currentData.status === \"pending\") return currentData;\n\t\t\tif (!refetch) return currentData;\n\t\t}\n\t\tconst documentPromise = this.client.get(id);\n\t\tdocumentPromise.then((doc) => {\n\t\t\tif (doc.header.id !== id) this.recordAlias(doc.header.id, id);\n\t\t}, () => void 0);\n\t\tthis.documents.set(id, addPromiseState(documentPromise));\n\t\treturn documentPromise;\n\t}\n\tgetBatch(ids) {\n\t\tconst key = ids.join(\",\");\n\t\tconst cached = this.batchPromises.get(key);\n\t\tconst hasDeletedDocuments = ids.some((id) => !this.documents.has(id));\n\t\tconst currentPromises = ids.map((id) => this.get(id));\n\t\tif (hasDeletedDocuments) {\n\t\t\tconst batchPromise = fulfilledOnly(currentPromises);\n\t\t\tthis.batchPromises.set(key, {\n\t\t\t\tpromises: currentPromises,\n\t\t\t\tpromise: batchPromise\n\t\t\t});\n\t\t\treturn batchPromise;\n\t\t}\n\t\tif (cached) {\n\t\t\tif (currentPromises.every((p, i) => p === cached.promises[i])) return cached.promise;\n\t\t}\n\t\tconst states = currentPromises.map((p) => readPromiseState(p));\n\t\tif (states.every((s) => s.status !== \"pending\")) {\n\t\t\tconst values = states.filter((s) => s.status === \"fulfilled\").map((s) => s.value);\n\t\t\tconst batchPromise = Promise.resolve(values);\n\t\t\tbatchPromise.status = \"fulfilled\";\n\t\t\tbatchPromise.value = values;\n\t\t\tthis.batchPromises.set(key, {\n\t\t\t\tpromises: currentPromises,\n\t\t\t\tpromise: batchPromise\n\t\t\t});\n\t\t\treturn batchPromise;\n\t\t}\n\t\tif (cached) return cached.promise;\n\t\tconst batchPromise = fulfilledOnly(currentPromises);\n\t\tthis.batchPromises.set(key, {\n\t\t\tpromises: currentPromises,\n\t\t\tpromise: batchPromise\n\t\t});\n\t\treturn batchPromise;\n\t}\n\tsubscribe(id, callback) {\n\t\tconst ids = Array.isArray(id) ? id : [id];\n\t\tfor (const docId of ids) {\n\t\t\tconst listeners = this.listeners.get(docId) ?? [];\n\t\t\tthis.listeners.set(docId, [...listeners, callback]);\n\t\t}\n\t\treturn () => {\n\t\t\tfor (const docId of ids) {\n\t\t\t\tconst listeners = this.listeners.get(docId) ?? [];\n\t\t\t\tthis.listeners.set(docId, listeners.filter((listener) => listener !== callback));\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Disposes of the cache and unsubscribes from document change events.\n\t*/\n\tdispose() {\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t\tthis.unsubscribe = null;\n\t\t}\n\t}\n};\n//#endregion\n//#region src/hooks/document-cache.ts\nconst documentEventFunctions = makePHEventFunctions(\"documentCache\");\n/** Returns all documents in the reactor. */\nconst useDocumentCache = documentEventFunctions.useValue;\n/** Sets all of the documents in the reactor. */\nconst setDocumentCache = documentEventFunctions.setValue;\n/** Adds an event handler for all of the documents in the reactor. */\nconst addDocumentCacheEventHandler = documentEventFunctions.addEventHandler;\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) {\n\tconst state = readPromiseState(promise);\n\tswitch (state.status) {\n\t\tcase \"pending\": return {\n\t\t\tstatus: \"pending\",\n\t\t\tisPending: true,\n\t\t\terror: void 0,\n\t\t\tdata: void 0\n\t\t};\n\t\tcase \"fulfilled\": return {\n\t\t\tstatus: \"success\",\n\t\t\tisPending: false,\n\t\t\terror: void 0,\n\t\t\tdata: state.value\n\t\t};\n\t\tcase \"rejected\": return {\n\t\t\tstatus: \"error\",\n\t\t\tisPending: false,\n\t\t\terror: state.reason,\n\t\t\tdata: void 0\n\t\t};\n\t}\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*/\nfunction useDocument(id) {\n\tconst documentCache = useDocumentCache();\n\tconst document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);\n\treturn document ? use(document) : void 0;\n}\n/**\n* Retrieves a document from the reactor and subscribes to changes without\n* suspending or throwing. Use this when the ID might be stale (e.g., a\n* previously selected node that has since been deleted) and the consumer\n* wants to render a placeholder instead of crashing.\n*\n* Unlike {@link useGetDocumentAsync}, this hook subscribes to cache\n* updates, so the returned state stays in sync with reactor changes.\n*\n* @param id - The document ID to retrieve, or null/undefined to skip retrieval\n* @returns An object containing:\n* - status: \"initial\" | \"pending\" | \"success\" | \"error\"\n* - data: The document if successfully loaded\n* - isPending: Whether the document is currently loading\n* - error: Any error that occurred during loading (e.g., document not found)\n* - reload: Function to force a refetch, or undefined when no id is supplied\n*/\nfunction useDocumentSafe(id) {\n\tconst documentCache = useDocumentCache();\n\tconst promise = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);\n\tconst [, bumpOnSettle] = useReducer((count) => count + 1, 0);\n\tconst pendingPromise = promise && readPromiseState(promise).status === \"pending\" ? promise : null;\n\tuseEffect(() => {\n\t\tif (!pendingPromise) return;\n\t\tlet active = true;\n\t\tconst settled = () => {\n\t\t\tif (active) bumpOnSettle();\n\t\t};\n\t\tpendingPromise.then(settled, settled);\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t};\n\t}, [pendingPromise]);\n\tif (!promise || !documentCache || !id) return {\n\t\tstatus: \"initial\",\n\t\tisPending: false,\n\t\terror: void 0,\n\t\tdata: void 0,\n\t\treload: void 0\n\t};\n\treturn {\n\t\t...getDocumentQueryState(promise),\n\t\treload: () => documentCache.get(id, true)\n\t};\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*/\nfunction useDocuments(ids) {\n\tconst documentCache = useDocumentCache();\n\tconst documents = useSyncExternalStore((cb) => ids?.length && documentCache ? documentCache.subscribe(ids, cb) : () => {}, () => ids?.length && documentCache ? documentCache.getBatch(ids) : void 0);\n\treturn documents ? use(documents) : [];\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*/\nfunction useGetDocument() {\n\tconst documentCache = useDocumentCache();\n\treturn useCallback((id) => {\n\t\tif (!documentCache) return Promise.reject(/* @__PURE__ */ new Error(\"Document cache not initialized\"));\n\t\treturn documentCache.get(id);\n\t}, [documentCache]);\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*/\nfunction useGetDocuments() {\n\tconst documentCache = useDocumentCache();\n\treturn useCallback((ids) => {\n\t\tif (!documentCache) return Promise.reject(/* @__PURE__ */ new Error(\"Document cache not initialized\"));\n\t\treturn documentCache.getBatch(ids);\n\t}, [documentCache]);\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*/\nfunction useGetDocumentAsync(id) {\n\tconst documentCache = useDocumentCache();\n\tif (!id || !documentCache) return {\n\t\tstatus: \"initial\",\n\t\tdata: void 0,\n\t\tisPending: false,\n\t\terror: void 0,\n\t\treload: void 0\n\t};\n\treturn {\n\t\t...getDocumentQueryState(documentCache.get(id)),\n\t\treload: () => documentCache.get(id, true)\n\t};\n}\n//#endregion\n//#region src/hooks/dispatch.ts\nfunction useDispatch(document) {\n\t/**\n\t* Dispatches actions to the document.\n\t* @param actionOrActions - The action or actions to dispatch.\n\t* @param onErrors - Callback invoked with any errors that occurred during action execution.\n\t*/\n\tfunction dispatch(actionOrActions, onErrors, onSuccess) {\n\t\tdispatchActions(actionOrActions, document, onErrors, onSuccess).catch((error) => {\n\t\t\tlogger.error(\"Failed to dispatch actions: @error\", error);\n\t\t});\n\t}\n\treturn [document, dispatch];\n}\n//#endregion\n//#region src/hooks/document-by-id.ts\n/** Returns a document by id. */\nfunction useDocumentById(id) {\n\tconst document = useDocument(id);\n\tconst [, dispatch] = useDispatch(document);\n\treturn [document, dispatch];\n}\n/** Returns documents by ids. */\nfunction useDocumentsByIds(ids) {\n\treturn useDocuments(ids);\n}\n//#endregion\nexport { uploadOperations as S, isDuplicateManifestError as _, setDocumentCache as a, queueActions as b, useDocumentSafe as c, useGetDocumentAsync as d, useGetDocuments as f, DOCUMENT_CHANGE_TYPE as g, readPromiseState as h, addDocumentCacheEventHandler as i, useDocuments as l, addPromiseState as m, useDocumentsByIds as n, useDocument as o, DocumentCache as p, useDispatch as r, useDocumentCache as s, useDocumentById as t, useGetDocument as u, isDuplicateModuleError as v, queueOperations as x, dispatchActions as y };\n\n//# sourceMappingURL=document-by-id-B4FIzG1w.js.map","/* global btoa */\nlet base64\n\nif (typeof window !== 'undefined') {\n if (window.btoa) {\n base64 = function (input) {\n return btoa(unescape(encodeURIComponent(input)))\n }\n } else {\n // Polyfill for environments that don't have btoa or Buffer class (notably, React Native).\n // Based on https://github.com/davidchambers/Base64.js/blob/a121f75bb10c8dd5d557886c4b1069b31258d230/base64.js\n base64 = function (input) {\n const str = unescape(encodeURIComponent(input + ''))\n let output = ''\n for (\n let block, charCode, idx = 0, map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n str.charAt(idx | 0) || (map = '=', idx % 1);\n output += map.charAt(63 & block >> 8 - idx % 1 * 8)\n ) {\n charCode = str.charCodeAt(idx += 3 / 4)\n // This is a coherence check. The result of unescape(encodeURIComponent()) should always be\n // characters with code points that fit into two bytes.\n /* c8 ignore next 3 */\n if (charCode > 0xFF) {\n throw new Error(\"'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.\")\n }\n block = block << 8 | charCode\n }\n return output\n }\n }\n} else {\n base64 = function (input) {\n return Buffer.from(input).toString('base64')\n }\n}\n\nfunction slug (string, opts) {\n let result = slugify(string, opts)\n const fallback = opts && opts.fallback !== undefined ? opts.fallback : slug.defaults.fallback\n // If output is an empty string, try slug for base64 of string.\n if (fallback === true && result === '') {\n result = slugify(base64(string), opts)\n }\n return result\n}\n\nconst locales = {\n // http://www.eki.ee/wgrs/rom1_bg.pdf\n bg: { Й: 'Y', й: 'y', X: 'H', x: 'h', Ц: 'Ts', ц: 'ts', Щ: 'Sht', щ: 'sht', Ъ: 'A', ъ: 'a', Ь: 'Y', ь: 'y' },\n // Need a reference URL for German, although this is pretty well-known.\n de: { Ä: 'AE', ä: 'ae', Ö: 'OE', ö: 'oe', Ü: 'UE', ü: 'ue' },\n // Need a reference URL for Serbian.\n sr: { đ: 'dj', Đ: 'DJ' },\n // https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/864314/ROMANIZATION_OF_UKRAINIAN.pdf\n uk: { И: 'Y', и: 'y', Й: 'Y', й: 'y', Ц: 'Ts', ц: 'ts', Х: 'Kh', х: 'kh', Щ: 'Shch', щ: 'shch', Г: 'H', г: 'h' }\n}\n\nlet defaultLocale = {}\n\nfunction slugify (string, opts) {\n if (typeof string !== 'string') {\n throw new Error('slug() requires a string argument, received ' + typeof string)\n }\n if (!string.isWellFormed()) {\n throw new Error('slug() received a malformed string with lone surrogates')\n }\n if (typeof opts === 'string') { opts = { replacement: opts } }\n opts = opts ? Object.assign({}, opts) : {}\n opts.mode = opts.mode || slug.defaults.mode\n const defaults = slug.defaults.modes[opts.mode]\n const keys = ['replacement', 'multicharmap', 'charmap', 'remove', 'lower', 'trim']\n for (let key, i = 0, l = keys.length; i < l; i++) {\n key = keys[i]\n opts[key] = (key in opts) ? opts[key] : defaults[key]\n }\n const localeMap = locales[opts.locale] || defaultLocale\n\n let lengths = []\n for (const key in opts.multicharmap) {\n if (!Object.prototype.hasOwnProperty.call(opts.multicharmap, key)) { continue }\n\n const len = key.length\n if (lengths.indexOf(len) === -1) { lengths.push(len) }\n }\n\n // We want to match the longest string if there are multiple matches, so\n // sort lengths in descending order.\n lengths = lengths.sort(function (a, b) { return b - a })\n\n const disallowedChars = opts.mode === 'rfc3986' ? /[^\\w\\s\\-.~]/ : /[^A-Za-z0-9\\s]/\n\n let result = ''\n for (let char, i = 0, l = string.length; i < l; i++) {\n char = string[i]\n let matchedMultichar = false\n for (let j = 0; j < lengths.length; j++) {\n const len = lengths[j]\n const str = string.substr(i, len)\n if (opts.multicharmap[str]) {\n i += len - 1\n char = opts.multicharmap[str]\n matchedMultichar = true\n break\n }\n }\n if (!matchedMultichar) {\n if (localeMap[char]) {\n char = localeMap[char]\n } else if (opts.charmap[char]) {\n char = opts.charmap[char].replace(opts.replacement, ' ')\n } else if (char.includes(opts.replacement)) {\n // preserve the replacement character in case it is excluded by disallowedChars\n char = char.replace(opts.replacement, ' ')\n } else {\n char = char.replace(disallowedChars, '')\n }\n }\n result += char\n }\n\n if (opts.remove) {\n result = result.replace(opts.remove, '')\n }\n if (opts.trim) {\n result = result.trim()\n }\n result = result.replace(/\\s+/g, opts.replacement) // convert spaces\n if (opts.lower) {\n result = result.toLowerCase()\n }\n return result\n}\n\nconst initialMulticharmap = {\n // multibyte devanagari characters (hindi, sanskrit, etc.)\n फ़: 'Fi',\n ग़: 'Ghi',\n ख़: 'Khi',\n क़: 'Qi',\n ड़: 'ugDha',\n ढ़: 'ugDhha',\n य़: 'Yi',\n ज़: 'Za',\n // hebrew\n // Refs: http://www.eki.ee/wgrs/rom1_he.pdf\n // Refs: https://en.wikipedia.org/wiki/Niqqud\n בִי: 'i',\n בֵ: 'e',\n בֵי: 'e',\n בֶ: 'e',\n בַ: 'a',\n בָ: 'a',\n בֹ: 'o',\n וֹ: 'o',\n בֻ: 'u',\n וּ: 'u',\n בּ: 'b',\n כּ: 'k',\n ךּ: 'k',\n פּ: 'p',\n שׁ: 'sh',\n שׂ: 's',\n בְ: 'e',\n חֱ: 'e',\n חֲ: 'a',\n חֳ: 'o',\n בִ: 'i'\n}\n\n// https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js\nconst initialCharmap = {\n // latin\n À: 'A',\n Á: 'A',\n Â: 'A',\n Ã: 'A',\n Ä: 'A',\n Å: 'A',\n Æ: 'AE',\n Ç: 'C',\n È: 'E',\n É: 'E',\n Ê: 'E',\n Ë: 'E',\n Ì: 'I',\n Í: 'I',\n Î: 'I',\n Ï: 'I',\n Ð: 'D',\n Ñ: 'N',\n Ò: 'O',\n Ó: 'O',\n Ô: 'O',\n Õ: 'O',\n Ö: 'O',\n Ő: 'O',\n Ø: 'O',\n Ō: 'O',\n Ù: 'U',\n Ú: 'U',\n Û: 'U',\n Ü: 'U',\n Ű: 'U',\n Ý: 'Y',\n Þ: 'TH',\n ß: 'ss',\n à: 'a',\n á: 'a',\n â: 'a',\n ã: 'a',\n ä: 'a',\n å: 'a',\n æ: 'ae',\n ç: 'c',\n è: 'e',\n é: 'e',\n ê: 'e',\n ë: 'e',\n ì: 'i',\n í: 'i',\n î: 'i',\n ï: 'i',\n ð: 'd',\n ñ: 'n',\n ò: 'o',\n ó: 'o',\n ô: 'o',\n õ: 'o',\n ö: 'o',\n ő: 'o',\n ø: 'o',\n ō: 'o',\n Œ: 'OE',\n œ: 'oe',\n ù: 'u',\n ú: 'u',\n û: 'u',\n ü: 'u',\n ű: 'u',\n ý: 'y',\n þ: 'th',\n ÿ: 'y',\n ẞ: 'SS',\n // greek\n α: 'a',\n β: 'b',\n γ: 'g',\n δ: 'd',\n ε: 'e',\n ζ: 'z',\n η: 'h',\n θ: 'th',\n ι: 'i',\n κ: 'k',\n λ: 'l',\n μ: 'm',\n ν: 'n',\n ξ: '3',\n ο: 'o',\n π: 'p',\n ρ: 'r',\n σ: 's',\n τ: 't',\n υ: 'y',\n φ: 'f',\n χ: 'x',\n ψ: 'ps',\n ω: 'w',\n ά: 'a',\n έ: 'e',\n ί: 'i',\n ό: 'o',\n ύ: 'y',\n ή: 'h',\n ώ: 'w',\n ς: 's',\n ϊ: 'i',\n ΰ: 'y',\n ϋ: 'y',\n ΐ: 'i',\n Α: 'A',\n Β: 'B',\n Γ: 'G',\n Δ: 'D',\n Ε: 'E',\n Ζ: 'Z',\n Η: 'H',\n Θ: 'Th',\n Ι: 'I',\n Κ: 'K',\n Λ: 'L',\n Μ: 'M',\n Ν: 'N',\n Ξ: '3',\n Ο: 'O',\n Π: 'P',\n Ρ: 'R',\n Σ: 'S',\n Τ: 'T',\n Υ: 'Y',\n Φ: 'F',\n Χ: 'X',\n Ψ: 'PS',\n Ω: 'W',\n Ά: 'A',\n Έ: 'E',\n Ί: 'I',\n Ό: 'O',\n Ύ: 'Y',\n Ή: 'H',\n Ώ: 'W',\n Ϊ: 'I',\n Ϋ: 'Y',\n // turkish\n ş: 's',\n Ş: 'S',\n ı: 'i',\n İ: 'I',\n ğ: 'g',\n Ğ: 'G',\n // russian\n а: 'a',\n б: 'b',\n в: 'v',\n г: 'g',\n д: 'd',\n е: 'e',\n ё: 'yo',\n ж: 'zh',\n з: 'z',\n и: 'i',\n й: 'j',\n к: 'k',\n л: 'l',\n м: 'm',\n н: 'n',\n о: 'o',\n п: 'p',\n р: 'r',\n с: 's',\n т: 't',\n у: 'u',\n ф: 'f',\n х: 'h',\n ц: 'c',\n ч: 'ch',\n ш: 'sh',\n щ: 'sh',\n ъ: 'u',\n ы: 'y',\n ь: '',\n э: 'e',\n ю: 'yu',\n я: 'ya',\n А: 'A',\n Б: 'B',\n В: 'V',\n Г: 'G',\n Д: 'D',\n Е: 'E',\n Ё: 'Yo',\n Ж: 'Zh',\n З: 'Z',\n И: 'I',\n Й: 'J',\n К: 'K',\n Л: 'L',\n М: 'M',\n Н: 'N',\n О: 'O',\n П: 'P',\n Р: 'R',\n С: 'S',\n Т: 'T',\n У: 'U',\n Ф: 'F',\n Х: 'H',\n Ц: 'C',\n Ч: 'Ch',\n Ш: 'Sh',\n Щ: 'Sh',\n Ъ: 'U',\n Ы: 'Y',\n Ь: '',\n Э: 'E',\n Ю: 'Yu',\n Я: 'Ya',\n // ukranian\n Є: 'Ye',\n І: 'I',\n Ї: 'Yi',\n Ґ: 'G',\n є: 'ye',\n і: 'i',\n ї: 'yi',\n ґ: 'g',\n // czech\n č: 'c',\n ď: 'd',\n ě: 'e',\n ň: 'n',\n ř: 'r',\n š: 's',\n ť: 't',\n ů: 'u',\n ž: 'z',\n Č: 'C',\n Ď: 'D',\n Ě: 'E',\n Ň: 'N',\n Ř: 'R',\n Š: 'S',\n Ť: 'T',\n Ů: 'U',\n Ž: 'Z',\n // slovak\n ľ: 'l',\n ĺ: 'l',\n ŕ: 'r',\n Ľ: 'L',\n Ĺ: 'L',\n Ŕ: 'R',\n // polish\n ą: 'a',\n ć: 'c',\n ę: 'e',\n ł: 'l',\n ń: 'n',\n ś: 's',\n ź: 'z',\n ż: 'z',\n Ą: 'A',\n Ć: 'C',\n Ę: 'E',\n Ł: 'L',\n Ń: 'N',\n Ś: 'S',\n Ź: 'Z',\n Ż: 'Z',\n // latvian\n ā: 'a',\n ē: 'e',\n ģ: 'g',\n ī: 'i',\n ķ: 'k',\n ļ: 'l',\n ņ: 'n',\n ū: 'u',\n Ā: 'A',\n Ē: 'E',\n Ģ: 'G',\n Ī: 'I',\n Ķ: 'K',\n Ļ: 'L',\n Ņ: 'N',\n Ū: 'U',\n // arabic\n أ: 'a',\n إ: 'i',\n ب: 'b',\n ت: 't',\n ث: 'th',\n ج: 'g',\n ح: 'h',\n خ: 'kh',\n د: 'd',\n ذ: 'th',\n ر: 'r',\n ز: 'z',\n س: 's',\n ش: 'sh',\n ص: 's',\n ض: 'd',\n ط: 't',\n ظ: 'th',\n ع: 'aa',\n غ: 'gh',\n ف: 'f',\n ق: 'k',\n ك: 'k',\n ل: 'l',\n م: 'm',\n ن: 'n',\n ه: 'h',\n و: 'o',\n ي: 'y',\n ء: 'aa',\n ة: 'a',\n // farsi\n آ: 'a',\n ا: 'a',\n پ: 'p',\n ژ: 'zh',\n گ: 'g',\n چ: 'ch',\n ک: 'k',\n ی: 'i',\n // lithuanian\n ė: 'e',\n į: 'i',\n ų: 'u',\n Ė: 'E',\n Į: 'I',\n Ų: 'U',\n // romanian\n ț: 't',\n Ț: 'T',\n ţ: 't',\n Ţ: 'T',\n ș: 's',\n Ș: 'S',\n ă: 'a',\n Ă: 'A',\n // vietnamese\n Ạ: 'A',\n Ả: 'A',\n Ầ: 'A',\n Ấ: 'A',\n Ậ: 'A',\n Ẩ: 'A',\n Ẫ: 'A',\n Ằ: 'A',\n Ắ: 'A',\n Ặ: 'A',\n Ẳ: 'A',\n Ẵ: 'A',\n Ẹ: 'E',\n Ẻ: 'E',\n Ẽ: 'E',\n Ề: 'E',\n Ế: 'E',\n Ệ: 'E',\n Ể: 'E',\n Ễ: 'E',\n Ị: 'I',\n Ỉ: 'I',\n Ĩ: 'I',\n Ọ: 'O',\n Ỏ: 'O',\n Ồ: 'O',\n Ố: 'O',\n Ộ: 'O',\n Ổ: 'O',\n Ỗ: 'O',\n Ơ: 'O',\n Ờ: 'O',\n Ớ: 'O',\n Ợ: 'O',\n Ở: 'O',\n Ỡ: 'O',\n Ụ: 'U',\n Ủ: 'U',\n Ũ: 'U',\n Ư: 'U',\n Ừ: 'U',\n Ứ: 'U',\n Ự: 'U',\n Ử: 'U',\n Ữ: 'U',\n Ỳ: 'Y',\n Ỵ: 'Y',\n Ỷ: 'Y',\n Ỹ: 'Y',\n Đ: 'D',\n ạ: 'a',\n ả: 'a',\n ầ: 'a',\n ấ: 'a',\n ậ: 'a',\n ẩ: 'a',\n ẫ: 'a',\n ằ: 'a',\n ắ: 'a',\n ặ: 'a',\n ẳ: 'a',\n ẵ: 'a',\n ẹ: 'e',\n ẻ: 'e',\n ẽ: 'e',\n ề: 'e',\n ế: 'e',\n ệ: 'e',\n ể: 'e',\n ễ: 'e',\n ị: 'i',\n ỉ: 'i',\n ĩ: 'i',\n ọ: 'o',\n ỏ: 'o',\n ồ: 'o',\n ố: 'o',\n ộ: 'o',\n ổ: 'o',\n ỗ: 'o',\n ơ: 'o',\n ờ: 'o',\n ớ: 'o',\n ợ: 'o',\n ở: 'o',\n ỡ: 'o',\n ụ: 'u',\n ủ: 'u',\n ũ: 'u',\n ư: 'u',\n ừ: 'u',\n ứ: 'u',\n ự: 'u',\n ử: 'u',\n ữ: 'u',\n ỳ: 'y',\n ỵ: 'y',\n ỷ: 'y',\n ỹ: 'y',\n đ: 'd',\n // kazakh\n Ә: 'AE',\n ә: 'ae',\n Ғ: 'GH',\n ғ: 'gh',\n Қ: 'KH',\n қ: 'kh',\n Ң: 'NG',\n ң: 'ng',\n Ү: 'UE',\n ү: 'ue',\n Ұ: 'U',\n ұ: 'u',\n Һ: 'H',\n һ: 'h',\n Ө: 'OE',\n ө: 'oe',\n // serbian\n ђ: 'dj',\n ј: 'j',\n љ: 'lj',\n њ: 'nj',\n ћ: 'c',\n џ: 'dz',\n Ђ: 'Dj',\n Ј: 'j',\n Љ: 'Lj',\n Њ: 'Nj',\n Ћ: 'C',\n Џ: 'Dz',\n nj: 'nj',\n lj: 'lj',\n Nj: 'NJ',\n Lj: 'LJ',\n // hindi\n अ: 'a',\n आ: 'aa',\n ए: 'e',\n ई: 'ii',\n ऍ: 'ei',\n ऎ: 'ae',\n ऐ: 'ai',\n इ: 'i',\n ओ: 'o',\n ऑ: 'oi',\n ऒ: 'oii',\n ऊ: 'uu',\n औ: 'ou',\n उ: 'u',\n ब: 'B',\n भ: 'Bha',\n च: 'Ca',\n छ: 'Chha',\n ड: 'Da',\n ढ: 'Dha',\n फ: 'Fa',\n ग: 'Ga',\n घ: 'Gha',\n ग़: 'Ghi',\n ह: 'Ha',\n ज: 'Ja',\n झ: 'Jha',\n क: 'Ka',\n ख: 'Kha',\n ख़: 'Khi',\n ल: 'L',\n ळ: 'Li',\n ऌ: 'Li',\n ऴ: 'Lii',\n ॡ: 'Lii',\n म: 'Ma',\n न: 'Na',\n ङ: 'Na',\n ञ: 'Nia',\n ण: 'Nae',\n ऩ: 'Ni',\n ॐ: 'oms',\n प: 'Pa',\n क़: 'Qi',\n र: 'Ra',\n ऋ: 'Ri',\n ॠ: 'Ri',\n ऱ: 'Ri',\n स: 'Sa',\n श: 'Sha',\n ष: 'Shha',\n ट: 'Ta',\n त: 'Ta',\n ठ: 'Tha',\n द: 'Tha',\n थ: 'Tha',\n ध: 'Thha',\n ड़: 'ugDha',\n ढ़: 'ugDhha',\n व: 'Va',\n य: 'Ya',\n य़: 'Yi',\n ज़: 'Za',\n // azerbaijani\n ə: 'e',\n Ə: 'E',\n // georgian\n ა: 'a',\n ბ: 'b',\n გ: 'g',\n დ: 'd',\n ე: 'e',\n ვ: 'v',\n ზ: 'z',\n თ: 't',\n ი: 'i',\n კ: 'k',\n ლ: 'l',\n მ: 'm',\n ნ: 'n',\n ო: 'o',\n პ: 'p',\n ჟ: 'zh',\n რ: 'r',\n ს: 's',\n ტ: 't',\n უ: 'u',\n ფ: 'p',\n ქ: 'k',\n ღ: 'gh',\n ყ: 'q',\n შ: 'sh',\n ჩ: 'ch',\n ც: 'ts',\n ძ: 'dz',\n წ: 'ts',\n ჭ: 'ch',\n ხ: 'kh',\n ჯ: 'j',\n ჰ: 'h',\n // hebrew\n ב: 'v',\n גּ: 'g',\n ג: 'g',\n ד: 'd',\n דּ: 'd',\n ה: 'h',\n ו: 'v',\n ז: 'z',\n ח: 'h',\n ט: 't',\n י: 'y',\n כ: 'kh',\n ך: 'kh',\n ל: 'l',\n מ: 'm',\n ם: 'm',\n נ: 'n',\n ן: 'n',\n ס: 's',\n פ: 'f',\n ף: 'f',\n ץ: 'ts',\n צ: 'ts',\n ק: 'k',\n ר: 'r',\n תּ: 't',\n ת: 't'\n}\n\nslug.charmap = Object.assign({}, initialCharmap)\nslug.multicharmap = Object.assign({}, initialMulticharmap)\nslug.defaults = {\n charmap: slug.charmap,\n mode: 'pretty',\n modes: {\n rfc3986: {\n replacement: '-',\n remove: null,\n lower: true,\n charmap: slug.charmap,\n multicharmap: slug.multicharmap,\n trim: true\n },\n pretty: {\n replacement: '-',\n remove: null,\n lower: true,\n charmap: slug.charmap,\n multicharmap: slug.multicharmap,\n trim: true\n }\n },\n multicharmap: slug.multicharmap,\n fallback: true\n}\n\nslug.reset = function () {\n slug.defaults.modes.rfc3986.charmap = slug.defaults.modes.pretty.charmap = slug.charmap = slug.defaults.charmap = Object.assign({}, initialCharmap)\n slug.defaults.modes.rfc3986.multicharmap = slug.defaults.modes.pretty.multicharmap = slug.multicharmap = slug.defaults.multicharmap = Object.assign({}, initialMulticharmap)\n defaultLocale = ''\n}\n\nslug.extend = function (customMap) {\n const keys = Object.keys(customMap)\n const multi = {}\n const single = {}\n for (let i = 0; i < keys.length; i++) {\n if (keys[i].length > 1) {\n multi[keys[i]] = customMap[keys[i]]\n } else {\n single[keys[i]] = customMap[keys[i]]\n }\n }\n Object.assign(slug.charmap, single)\n Object.assign(slug.multicharmap, multi)\n}\n\nslug.setLocale = function (locale) {\n defaultLocale = locales[locale] || {}\n}\n\nexport default slug\n","import { _ as isDuplicateManifestError, n as useDocumentsByIds, r as useDispatch, v as isDuplicateModuleError } from \"./document-by-id-B4FIzG1w.js\";\nimport { t as makePHEventFunctions } from \"./make-ph-event-functions-DBq3iWYn.js\";\nimport { useSyncExternalStore } from \"react\";\nimport slug from \"slug\";\n//#region src/graphql-client/auth.ts\n/** Lifetime requested for an ambient Renown token, in seconds. */\nconst ambientTokenExpiresInSeconds = 600;\n/**\n* The default token provider: the token of the currently logged-in Renown user.\n*\n* It is deliberately resolved from `window.ph` on every call rather than\n* captured at construction time, so a client built before login starts sending\n* the token as soon as there is one.\n*\n* The token is requested WITHOUT an `aud` claim - the Switchboard verifier\n* rejects tokens that carry an audience.\n*/\nasync function ambientRenownTokenProvider() {\n\tif (typeof window === \"undefined\") return;\n\tconst renown = window.ph?.renown;\n\tif (!renown?.user) return;\n\treturn renown.getBearerToken({ expiresIn: ambientTokenExpiresInSeconds });\n}\n/**\n* Builds the SDK middleware that authenticates every request.\n*\n* The token is resolved per request and never cached, so a login, a logout or\n* an expiry between two calls is picked up by the next one. When no token is\n* available the request goes out unauthenticated.\n*/\nfunction makeAuthMiddleware(tokenProvider) {\n\treturn async (action) => {\n\t\tconst token = await tokenProvider();\n\t\tif (!token) return action();\n\t\treturn action({ authorization: `Bearer ${token}` });\n\t};\n}\n//#endregion\n//#region src/errors.ts\nvar UnsupportedDocumentTypeError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Document type ${documentType} is not supported`);\n\t\tthis.name = \"UnsupportedDocumentTypeError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UnsupportedDocumentTypeError\";\n\t}\n};\nvar DocumentModelNotFoundError = class extends Error {\n\tdocumentType;\n\tname = \"DocumentModelNotFoundError\";\n\tconstructor(documentType) {\n\t\tsuper(`Document model module for type ${documentType} not found`);\n\t\tthis.documentType = documentType;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentModelNotFoundError\";\n\t}\n};\nvar DocumentTypeMismatchError = class extends Error {\n\tconstructor(documentId, expectedType, actualType) {\n\t\tsuper(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);\n\t}\n};\nvar NoSelectedDocumentError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?\");\n\t}\n};\n//#endregion\n//#region src/utils/url.ts\nfunction resolveUrlPathname(path) {\n\treturn new URL(path.replace(/^\\/+/, \"\"), window.location.origin + (window.ph?.basePath ?? \"/\")).pathname;\n}\n/** Returns the current path without the base path */\nfunction getPathWithoutBase(path) {\n\tconst basePath = window.ph?.basePath ?? \"/\";\n\treturn path.replace(basePath, basePath.endsWith(\"/\") ? \"/\" : \"\");\n}\n/** Makes a URL component for a drive. */\nfunction makeDriveUrlComponent(drive) {\n\tif (!drive) return \"\";\n\treturn `/d/${slug(drive.header.slug)}`;\n}\n/** Makes a URL component for a node. */\nfunction makeNodeSlug(node) {\n\tif (!node) return \"\";\n\tconst nodeName = node.name;\n\tif (!nodeName) return slug(node.id);\n\treturn slug(`${nodeName}-${node.id}`);\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*/\nfunction extractNodeSlugFromPath(path) {\n\tconst currentPath = getPathWithoutBase(path);\n\treturn /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath)?.[1];\n}\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nfunction findUuid(input) {\n\tif (!input) return void 0;\n\treturn /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/.exec(input)?.[0];\n}\nfunction extractNodeIdFromSlug(nodeSlug) {\n\treturn findUuid(nodeSlug);\n}\nfunction extractNodeIdFromPath(path) {\n\treturn extractNodeIdFromSlug(extractNodeSlugFromPath(path));\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*/\nfunction extractDriveSlugFromPath(path) {\n\tconst currentPath = getPathWithoutBase(path);\n\treturn /^\\/d\\/([^/]+)/.exec(currentPath)?.[1] ?? \"\";\n}\nfunction extractDriveIdFromSlug(driveSlug) {\n\treturn findUuid(driveSlug);\n}\nfunction extractDriveIdFromPath(path) {\n\treturn extractDriveIdFromSlug(extractDriveSlugFromPath(path));\n}\n/**\n* Creates a URL string with the given pathname while preserving existing query parameters.\n*/\nfunction createUrlWithPreservedParams(pathname) {\n\tconst search = window.location.search;\n\treturn search ? `${pathname}${search}` : pathname;\n}\n//#endregion\n//#region src/hooks/drives.ts\nconst drivesEventFunctions = makePHEventFunctions(\"drives\");\n/** Returns all of the drives in the reactor */\nconst useDrives = drivesEventFunctions.useValue;\n/** Sets the drives in the reactor */\nconst setDrives = drivesEventFunctions.setValue;\n/** Adds an event handler for the drives */\nconst addDrivesEventHandler = drivesEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/set-selected-node.ts\nconst selectedNodeIdEventFunctions = makePHEventFunctions(\"selectedNodeId\");\nconst useSelectedNodeId = selectedNodeIdEventFunctions.useValue;\nconst setSelectedNodeId = selectedNodeIdEventFunctions.setValue;\nconst addSelectedNodeIdEventHandler = selectedNodeIdEventFunctions.addEventHandler;\n/** Sets the selected node (file or folder). */\nfunction setSelectedNode(nodeOrNodeSlug) {\n\tconst nodeSlug = typeof nodeOrNodeSlug === \"string\" ? nodeOrNodeSlug : makeNodeSlug(nodeOrNodeSlug);\n\tsetSelectedNodeId(extractNodeIdFromSlug(nodeSlug));\n\tconst driveSlugFromPath = extractDriveSlugFromPath(window.location.pathname);\n\tif (!driveSlugFromPath) return;\n\tif (!nodeSlug) {\n\t\tconst pathname = resolveUrlPathname(`/d/${driveSlugFromPath}`);\n\t\tif (pathname === window.location.pathname) return;\n\t\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n\t\treturn;\n\t}\n\tconst pathname = resolveUrlPathname(`/d/${driveSlugFromPath}/${nodeSlug}`);\n\tif (pathname === window.location.pathname) return;\n\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\nfunction addResetSelectedNodeEventHandler() {\n\twindow.addEventListener(\"ph:selectedDriveIdUpdated\", () => {\n\t\tsetSelectedNodeId(void 0);\n\t});\n}\nfunction addSetSelectedNodeOnPopStateEventHandler() {\n\twindow.addEventListener(\"popstate\", () => {\n\t\tconst pathname = window.location.pathname;\n\t\tconst nodeSlug = extractNodeSlugFromPath(pathname);\n\t\tif (extractNodeIdFromSlug(nodeSlug) !== window.ph?.selectedNodeId) setSelectedNode(nodeSlug);\n\t});\n}\n//#endregion\n//#region src/hooks/selected-drive.ts\nconst selectedDriveIdEventFunctions = makePHEventFunctions(\"selectedDriveId\");\n/** Returns the selected drive id */\nconst useSelectedDriveId = selectedDriveIdEventFunctions.useValue;\n/** Sets the selected drive id */\nconst setSelectedDriveId = selectedDriveIdEventFunctions.setValue;\n/** Adds an event handler for the selected drive id */\nconst addSelectedDriveIdEventHandler = selectedDriveIdEventFunctions.addEventHandler;\n/** Returns the selected drive */\nfunction useSelectedDrive() {\n\tconst drive = useSelectedDriveSafe();\n\tif (!drive[0]) throw new Error(\"There is no drive selected. Did you mean to call 'useSelectedDriveSafe'?\");\n\treturn drive;\n}\n/** Returns the selected drive, or undefined if no drive is selected */\nfunction useSelectedDriveSafe() {\n\tconst selectedDriveId = useSelectedDriveId();\n\tconst selectedDrive = useDrives()?.find((drive) => drive.header.id === selectedDriveId);\n\tconst [drive, dispatch] = useDispatch(selectedDrive);\n\tif (!selectedDrive) return [void 0, void 0];\n\treturn [drive, dispatch];\n}\nfunction setSelectedDrive(driveOrDriveSlug) {\n\tconst driveSlug = typeof driveOrDriveSlug === \"string\" ? driveOrDriveSlug : driveOrDriveSlug?.header.slug;\n\tconst drives = window.ph?.drives;\n\tconst driveId = (typeof driveOrDriveSlug === \"object\" && driveOrDriveSlug !== null ? driveOrDriveSlug : drives?.find((d) => d.header.slug === driveSlug))?.header.id;\n\tif (!driveId && driveSlug && extractDriveSlugFromPath(window.location.pathname) === driveSlug) {\n\t\tif (window.ph?.selectedDriveId) setSelectedDriveId(void 0);\n\t\tdeferDriveSelection(driveSlug);\n\t\treturn;\n\t}\n\tcancelPendingDriveSelection();\n\tsetSelectedDriveId(driveId);\n\tif (!driveId) {\n\t\tconst pathname = resolveUrlPathname(\"/\");\n\t\tif (pathname === window.location.pathname) return;\n\t\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n\t\treturn;\n\t}\n\tconst pathname = resolveUrlPathname(`/d/${driveSlug}`);\n\tif (pathname === window.location.pathname) return;\n\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n}\nconst DEFERRED_DRIVE_TICK_MS = 2e3;\nconst DEFERRED_DRIVE_MAX_WAIT_MS = 15e3;\nfunction isInitialSyncInFlight() {\n\tconst remotes = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager?.list();\n\tif (!remotes?.length) return false;\n\treturn remotes.some((remote) => {\n\t\ttry {\n\t\t\tconst snapshot = remote.channel.getConnectionState();\n\t\t\treturn snapshot.receivingPages || !snapshot.lastSuccessUtcMs && snapshot.state !== \"error\";\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\nlet pendingHandler;\nlet pendingTimeout;\nfunction cancelPendingDriveSelection() {\n\tif (pendingHandler) {\n\t\twindow.removeEventListener(\"ph:drivesUpdated\", pendingHandler);\n\t\tpendingHandler = void 0;\n\t}\n\tif (pendingTimeout) {\n\t\tclearTimeout(pendingTimeout);\n\t\tpendingTimeout = void 0;\n\t}\n}\nfunction deferDriveSelection(driveSlug) {\n\tcancelPendingDriveSelection();\n\tconst nodeSlug = extractNodeSlugFromPath(window.location.pathname);\n\tconst handler = () => {\n\t\tif (!window.ph?.drives?.find((d) => d.header.slug === driveSlug)) return;\n\t\tcancelPendingDriveSelection();\n\t\tsetSelectedDrive(driveSlug);\n\t\tsetSelectedNode(nodeSlug);\n\t};\n\tpendingHandler = handler;\n\twindow.addEventListener(\"ph:drivesUpdated\", handler);\n\tconst deadline = Date.now() + DEFERRED_DRIVE_MAX_WAIT_MS;\n\tconst scheduleTick = () => {\n\t\tpendingTimeout = setTimeout(() => {\n\t\t\tif (Date.now() < deadline && isInitialSyncInFlight()) {\n\t\t\t\tscheduleTick();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcancelPendingDriveSelection();\n\t\t\tconst pathname = resolveUrlPathname(\"/\");\n\t\t\tif (pathname === window.location.pathname) return;\n\t\t\twindow.history.pushState(null, \"\", createUrlWithPreservedParams(pathname));\n\t\t}, DEFERRED_DRIVE_TICK_MS);\n\t};\n\tscheduleTick();\n}\nfunction addSetSelectedDriveOnPopStateEventHandler() {\n\twindow.addEventListener(\"popstate\", () => {\n\t\tconst pathname = window.location.pathname;\n\t\tconst driveId = extractDriveIdFromPath(pathname);\n\t\tif (driveId !== window.ph?.selectedDriveId) setSelectedDrive(driveId);\n\t});\n}\n//#endregion\n//#region src/utils/nodes.ts\n/** Sorts nodes by name. */\nfunction sortNodesByName(nodes) {\n\treturn nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n/** Returns whether a node is a file. */\nfunction isFileNodeKind(node) {\n\tif (!node) return false;\n\treturn node.kind.toUpperCase() === \"FILE\";\n}\n/** Returns whether a node is a folder. */\nfunction isFolderNodeKind(node) {\n\tif (!node) return false;\n\treturn node.kind.toUpperCase() === \"FOLDER\";\n}\n//#endregion\n//#region src/hooks/items-in-selected-drive.ts\n/** Returns the nodes in the selected drive. */\nfunction useNodesInSelectedDrive() {\n\tconst [selectedDrive] = useSelectedDriveSafe();\n\treturn selectedDrive?.state.global.nodes;\n}\n/** Returns the file nodes in the selected drive. */\nfunction useFileNodesInSelectedDrive() {\n\treturn useNodesInSelectedDrive()?.filter((n) => isFileNodeKind(n));\n}\n/** Returns the folder nodes in the selected drive. */\nfunction useFolderNodesInSelectedDrive() {\n\treturn useNodesInSelectedDrive()?.filter((n) => isFolderNodeKind(n));\n}\n/** Returns the documents in the selected drive. */\nfunction useDocumentsInSelectedDrive() {\n\tconst fileNodeIds = useFileNodesInSelectedDrive()?.map((node) => node.id);\n\treturn useDocumentsByIds(fileNodeIds);\n}\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nfunction useDocumentTypesInSelectedDrive() {\n\treturn (useDocumentsInSelectedDrive()?.filter(isDocumentModelDocument))?.map((doc) => doc.state.global.id);\n}\nfunction isDocumentModelDocument(document) {\n\treturn document.header.documentType === \"powerhouse/document-model\";\n}\n//#endregion\n//#region src/hooks/selected-node.ts\n/** Returns the selected node. */\nfunction useSelectedNode() {\n\tconst selectedNodeId = useSelectedNodeId();\n\treturn useNodesInSelectedDrive()?.find((n) => n.id === selectedNodeId);\n}\n//#endregion\n//#region src/hooks/vetra-packages.ts\nconst vetraPackageManagerFunctions = makePHEventFunctions(\"vetraPackageManager\");\nconst useVetraPackageManager = vetraPackageManagerFunctions.useValue;\nconst EMPTY_VETRA_PACKAGES = [];\nconst noPackageManagerUnsubscribe = () => {};\n/**\n* Returns all of the Vetra packages loaded by the Connect instance.\n*\n* The snapshot and subscription must keep stable identity while no package\n* manager is registered: `useSyncExternalStore` loops when the snapshot\n* changes on every read, which a fresh `[]` does.\n*/\nconst useVetraPackages = () => {\n\tconst packageManager = useVetraPackageManager();\n\treturn useSyncExternalStore((cb) => packageManager ? packageManager.subscribe(cb) : noPackageManagerUnsubscribe, () => packageManager?.packages ?? EMPTY_VETRA_PACKAGES);\n};\n/** Adds the Vetra package manager event handler */\nconst addVetraPackageManagerEventHandler = vetraPackageManagerFunctions.addEventHandler;\n/** Sets the Vetra package manager and registers its packages */\nfunction setVetraPackageManager(packageManager) {\n\tvetraPackageManagerFunctions.setValue(packageManager);\n\tupdateReactorClientDocumentModels(packageManager.packages);\n\tupdateReactorClientUpgradeManifests(packageManager.packages);\n\tpackageManager.subscribe(({ packages }) => {\n\t\tupdateReactorClientDocumentModels(packages);\n\t\tupdateReactorClientUpgradeManifests(packages);\n\t});\n}\nfunction updateReactorClientDocumentModels(packages) {\n\tconst documentModelModules = packages.flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && (m.version ?? 1) === (module.version ?? 1)) === index);\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tif (!registry || documentModelModules.length === 0) return;\n\tconst results = registry.registerModules(...documentModelModules);\n\tconst duplicateTypes = /* @__PURE__ */ new Set();\n\tfor (const result of results) if (result.status === \"error\") if (isDuplicateModuleError(result.error)) duplicateTypes.add(result.item.documentModel.global.id);\n\telse console.error(\"Failed to register document model module:\", result.error);\n\tif (duplicateTypes.size > 0) {\n\t\tregistry.unregisterModules(...duplicateTypes);\n\t\tregistry.registerModules(...documentModelModules.filter((module) => duplicateTypes.has(module.documentModel.global.id)));\n\t}\n}\nfunction updateReactorClientUpgradeManifests(packages) {\n\tconst upgradeManifests = packages.flatMap((pkg) => pkg.upgradeManifests).filter((u) => u !== void 0);\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tif (!registry || upgradeManifests.length === 0) return;\n\tconst results = registry.registerUpgradeManifests(...upgradeManifests);\n\tconst duplicates = [];\n\tfor (const result of results) if (result.status === \"error\") if (isDuplicateManifestError(result.error)) duplicates.push(result);\n\telse console.error(\"Failed to register upgrade manifest:\", result.error);\n\tif (duplicates.length > 0) {\n\t\tconst duplicateTypes = duplicates.map((r) => r.item.documentType).filter((t) => !!t);\n\t\tregistry.unregisterUpgradeManifests(...duplicateTypes);\n\t\tregistry.registerUpgradeManifests(...duplicates.map((r) => r.item));\n\t}\n}\n//#endregion\n//#region src/hooks/document-model-modules.ts\nfunction useDocumentModelModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.documentModels).filter((module, index, modules) => modules.findIndex((m) => m.documentModel.global.id === module.documentModel.global.id && m.version === module.version) === index);\n}\n/**\n* Resolves a document model module by document type, mirroring the registry's\n* semantics (`IDocumentModelRegistry.getModule`): with `version` omitted the\n* LATEST version of the type wins (`version ?? 1` as each module's default),\n* with `version` given only an exact match is returned. The reactor resolves\n* modules the same way when a document is created, so metadata read through\n* this hook and the version a creation actually uses cannot disagree.\n*/\nfunction useDocumentModelModuleById(id, version) {\n\tconst documentModelModules = useDocumentModelModules();\n\tif (!id || !documentModelModules) return void 0;\n\tlet latestModule;\n\tlet latestVersion = -1;\n\tfor (const module of documentModelModules) {\n\t\tif (module.documentModel.global.id !== id) continue;\n\t\tconst moduleVersion = module.version ?? 1;\n\t\tif (version !== void 0) {\n\t\t\tif (moduleVersion === version) return module;\n\t\t\tcontinue;\n\t\t}\n\t\tif (moduleVersion > latestVersion) {\n\t\t\tlatestVersion = moduleVersion;\n\t\t\tlatestModule = module;\n\t\t}\n\t}\n\treturn latestModule;\n}\n//#endregion\nexport { createUrlWithPreservedParams as A, makeNodeSlug as B, addResetSelectedNodeEventHandler as C, addDrivesEventHandler as D, setSelectedNode as E, extractNodeIdFromSlug as F, UnsupportedDocumentTypeError as G, DocumentModelNotFoundError as H, extractNodeSlugFromPath as I, ambientRenownTokenProvider as K, findUuid as L, extractDriveIdFromSlug as M, extractDriveSlugFromPath as N, setDrives as O, extractNodeIdFromPath as P, getPathWithoutBase as R, useSelectedDriveSafe as S, addSetSelectedNodeOnPopStateEventHandler as T, DocumentTypeMismatchError as U, resolveUrlPathname as V, NoSelectedDocumentError as W, addSetSelectedDriveOnPopStateEventHandler as _, useVetraPackageManager as a, useSelectedDrive as b, useDocumentTypesInSelectedDrive as c, useFolderNodesInSelectedDrive as d, useNodesInSelectedDrive as f, addSelectedDriveIdEventHandler as g, sortNodesByName as h, setVetraPackageManager as i, extractDriveIdFromPath as j, useDrives as k, useDocumentsInSelectedDrive as l, isFolderNodeKind as m, useDocumentModelModules as n, useVetraPackages as o, isFileNodeKind as p, makeAuthMiddleware as q, addVetraPackageManagerEventHandler as r, useSelectedNode as s, useDocumentModelModuleById as t, useFileNodesInSelectedDrive as u, setSelectedDrive as v, addSelectedNodeIdEventHandler as w, useSelectedDriveId as x, setSelectedDriveId as y, makeDriveUrlComponent as z };\n\n//# sourceMappingURL=document-model-modules-bTP87nyr.js.map","export class ClientError extends Error {\n response;\n request;\n constructor(response, request) {\n const message = `${ClientError.extractMessage(response)}: ${JSON.stringify({\n response,\n request,\n })}`;\n super(message);\n Object.setPrototypeOf(this, ClientError.prototype);\n this.response = response;\n this.request = request;\n // this is needed as Safari doesn't support .captureStackTrace\n if (typeof Error.captureStackTrace === `function`) {\n Error.captureStackTrace(this, ClientError);\n }\n }\n static extractMessage(response) {\n return response.errors?.[0]?.message ?? `GraphQL Error (Code: ${String(response.status)})`;\n }\n}\n//# sourceMappingURL=ClientError.js.map","export const uppercase = (str) => str.toUpperCase();\nexport const callOrIdentity = (value) => {\n return typeof value === `function` ? value() : value;\n};\nexport const zip = (a, b) => a.map((k, i) => [k, b[i]]);\nexport const HeadersInitToPlainObject = (headers) => {\n let oHeaders = {};\n if (headers instanceof Headers) {\n oHeaders = HeadersInstanceToPlainObject(headers);\n }\n else if (Array.isArray(headers)) {\n headers.forEach(([name, value]) => {\n if (name && value !== undefined) {\n oHeaders[name] = value;\n }\n });\n }\n else if (headers) {\n oHeaders = headers;\n }\n return oHeaders;\n};\nexport const HeadersInstanceToPlainObject = (headers) => {\n const o = {};\n headers.forEach((v, k) => {\n o[k] = v;\n });\n return o;\n};\nexport const tryCatch = (fn) => {\n try {\n const result = fn();\n if (isPromiseLikeValue(result)) {\n return result.catch((error) => {\n return errorFromMaybeError(error);\n });\n }\n return result;\n }\n catch (error) {\n return errorFromMaybeError(error);\n }\n};\n/**\n * Ensure that the given value is an error and return it. If it is not an error than\n * wrap it in one, passing the given value as the error message.\n */\nexport const errorFromMaybeError = (maybeError) => {\n if (maybeError instanceof Error)\n return maybeError;\n return new Error(String(maybeError));\n};\nexport const isPromiseLikeValue = (value) => {\n return (typeof value === `object`\n && value !== null\n && `then` in value\n && typeof value.then === `function`\n && `catch` in value\n && typeof value.catch === `function`\n && `finally` in value\n && typeof value.finally === `function`);\n};\nexport const casesExhausted = (value) => {\n throw new Error(`Unhandled case: ${String(value)}`);\n};\nexport const isPlainObject = (value) => {\n return typeof value === `object` && value !== null && !Array.isArray(value);\n};\nexport const entries = (obj) => Object.entries(obj);\nexport const values = (obj) => Object.values(obj);\nexport const mapValues = (object, fn) => {\n return Object.fromEntries(Object.entries(object).map(([key, value]) => {\n return [key, fn(value, key)];\n }));\n};\nexport const lowerCaseFirstLetter = (s) => {\n return s.charAt(0).toLowerCase() + s.slice(1);\n};\nexport function assertArray(v) {\n if (!Array.isArray(v))\n throw new Error(`Expected array. Got: ${String(v)}`);\n}\nexport function assertObject(v) {\n if (v === null || typeof v !== `object`)\n throw new Error(`Expected object. Got: ${String(v)}`);\n}\nexport const capitalizeFirstLetter = (string) => string.charAt(0).toUpperCase() + string.slice(1);\nexport const createDeferred = (options) => {\n let isResolved = false;\n let resolve;\n let reject;\n const promise = new Promise(($resolve, $reject) => {\n resolve = $resolve;\n reject = $reject;\n });\n return {\n promise,\n isResolved: () => isResolved,\n resolve: (value) => {\n isResolved = true;\n if (options?.strict && isResolved) {\n throw new Error(`Deferred is already resolved. Attempted to resolve with: ${JSON.stringify(value)}`);\n }\n resolve(value);\n },\n reject: (error) => reject(error),\n };\n};\nexport const debug = (...args) => {\n if (process.env[`DEBUG`]) {\n console.log(...args);\n }\n};\nexport const debugSub = (...args) => (...subArgs) => {\n debug(...args, ...subArgs);\n};\nexport const partitionErrors = (array) => {\n const errors = [];\n const values = [];\n for (const item of array) {\n if (item instanceof Error) {\n errors.push(item);\n }\n else {\n values.push(item);\n }\n }\n return [values, errors];\n};\n//# sourceMappingURL=prelude.js.map","import { GraphQLClient } from '../classes/GraphQLClient.js';\n/**\n * Send a batch of GraphQL Document to the GraphQL server for execution.\n *\n * @example\n *\n * ```ts\n * // You can pass a raw string\n *\n * await batchRequests('https://foo.bar/graphql', [\n * {\n * query: `\n * {\n * query {\n * users\n * }\n * }`\n * },\n * {\n * query: `\n * {\n * query {\n * users\n * }\n * }`\n * }])\n *\n * // You can also pass a GraphQL DocumentNode as query. Convenient if you\n * // are using graphql-tag package.\n *\n * import gql from 'graphql-tag'\n *\n * await batchRequests('https://foo.bar/graphql', [{ query: gql`...` }])\n * ```\n */\nexport const batchRequests = async (...args) => {\n const params = parseBatchRequestsArgsExtended(args);\n const client = new GraphQLClient(params.url);\n return client.batchRequests(params);\n};\nexport const parseBatchRequestsArgsExtended = (args) => {\n if (args.length === 1) {\n return args[0];\n }\n else {\n return {\n url: args[0],\n documents: args[1],\n requestHeaders: args[2],\n signal: undefined,\n };\n }\n};\nexport const parseBatchRequestArgs = (documentsOrOptions, requestHeaders) => {\n // eslint-disable-next-line\n return documentsOrOptions.documents\n ? documentsOrOptions\n : {\n documents: documentsOrOptions,\n requestHeaders: requestHeaders,\n signal: undefined,\n };\n};\n//# sourceMappingURL=batchRequests.js.map","import { GraphQLClient } from '../classes/GraphQLClient.js';\n/**\n * Send a GraphQL Query to the GraphQL server for execution.\n */\nexport const rawRequest = async (...args) => {\n const [urlOrOptions, query, ...variablesAndRequestHeaders] = args;\n const requestOptions = parseRawRequestExtendedArgs(urlOrOptions, query, ...variablesAndRequestHeaders);\n const client = new GraphQLClient(requestOptions.url);\n return client.rawRequest({\n ...requestOptions,\n });\n};\nexport const parseRawRequestExtendedArgs = (urlOrOptions, query, ...variablesAndRequestHeaders) => {\n const [variables, requestHeaders] = variablesAndRequestHeaders;\n return typeof urlOrOptions === `string`\n ? {\n url: urlOrOptions,\n query: query,\n variables,\n requestHeaders,\n signal: undefined,\n }\n : urlOrOptions;\n};\nexport const parseRawRequestArgs = (queryOrOptions, variables, requestHeaders) => {\n return queryOrOptions.query\n ? queryOrOptions\n : {\n query: queryOrOptions,\n variables: variables,\n requestHeaders: requestHeaders,\n signal: undefined,\n };\n};\n//# sourceMappingURL=rawRequest.js.map","export const ACCEPT_HEADER = `Accept`;\nexport const CONTENT_TYPE_HEADER = `Content-Type`;\nexport const CONTENT_TYPE_JSON = `application/json`;\nexport const CONTENT_TYPE_GQL = `application/graphql-response+json`;\nexport const statusCodes = {\n success: 200,\n};\n//# sourceMappingURL=http.js.map","import { Kind } from 'graphql';\nimport { CONTENT_TYPE_GQL, CONTENT_TYPE_JSON } from '../../lib/http.js';\nimport { isPlainObject } from '../../lib/prelude.js';\n/**\n * Clean a GraphQL document to send it via a GET query\n */\nexport const cleanQuery = (str) => str.replace(/([\\s,]|#[^\\n\\r]+)+/g, ` `).trim();\nexport const isGraphQLContentType = (contentType) => {\n const contentTypeLower = contentType.toLowerCase();\n return contentTypeLower.includes(CONTENT_TYPE_GQL) || contentTypeLower.includes(CONTENT_TYPE_JSON);\n};\nexport const parseGraphQLExecutionResult = (result) => {\n try {\n if (Array.isArray(result)) {\n return {\n _tag: `Batch`,\n executionResults: result.map(parseExecutionResult),\n };\n }\n else if (isPlainObject(result)) {\n return {\n _tag: `Single`,\n executionResult: parseExecutionResult(result),\n };\n }\n else {\n throw new Error(`Invalid execution result: result is not object or array. \\nGot:\\n${String(result)}`);\n }\n }\n catch (e) {\n return e;\n }\n};\n/**\n * Example result:\n *\n * ```\n * {\n * \"data\": null,\n * \"errors\": [{\n * \"message\": \"custom error\",\n * \"locations\": [{ \"line\": 2, \"column\": 3 }],\n * \"path\": [\"playerNew\"]\n * }]\n * }\n * ```\n */\nexport const parseExecutionResult = (result) => {\n if (typeof result !== `object` || result === null) {\n throw new Error(`Invalid execution result: result is not object`);\n }\n let errors = undefined;\n let data = undefined;\n let extensions = undefined;\n if (`errors` in result) {\n if (!isPlainObject(result.errors) && !Array.isArray(result.errors)) {\n throw new Error(`Invalid execution result: errors is not plain object OR array`); // prettier-ignore\n }\n errors = result.errors;\n }\n // todo add test coverage for case of null. @see https://github.com/jasonkuhrt/graphql-request/issues/739\n if (`data` in result) {\n if (!isPlainObject(result.data) && result.data !== null) {\n throw new Error(`Invalid execution result: data is not plain object`); // prettier-ignore\n }\n data = result.data;\n }\n if (`extensions` in result) {\n if (!isPlainObject(result.extensions))\n throw new Error(`Invalid execution result: extensions is not plain object`); // prettier-ignore\n extensions = result.extensions;\n }\n return {\n data,\n errors,\n extensions,\n };\n};\nexport const isRequestResultHaveErrors = (result) => result._tag === `Batch`\n ? result.executionResults.some(isExecutionResultHaveErrors)\n : isExecutionResultHaveErrors(result.executionResult);\nexport const isExecutionResultHaveErrors = (result) => Array.isArray(result.errors) ? result.errors.length > 0 : Boolean(result.errors);\nexport const isOperationDefinitionNode = (definition) => {\n return (typeof definition === `object`\n && definition !== null\n && `kind` in definition\n && definition.kind === Kind.OPERATION_DEFINITION);\n};\n//# sourceMappingURL=graphql.js.map","import { tryCatch } from '../../lib/prelude.js';\nimport { isOperationDefinitionNode } from '../lib/graphql.js';\nimport { parse } from 'graphql';\nimport { print } from 'graphql';\n/**\n * helpers\n */\nconst extractOperationName = (document) => {\n let operationName = undefined;\n const defs = document.definitions.filter(isOperationDefinitionNode);\n if (defs.length === 1) {\n operationName = defs[0].name?.value;\n }\n return operationName;\n};\nconst extractIsMutation = (document) => {\n let isMutation = false;\n const defs = document.definitions.filter(isOperationDefinitionNode);\n if (defs.length === 1) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison --\n * graphql@15's `OperationTypeNode` is a type, but graphql@16's `OperationTypeNode` is a native TypeScript enum\n * Therefore, we cannot use `OperationTypeNode.MUTATION` here because it wouldn't work with graphql@15\n **/\n isMutation = defs[0].operation === `mutation`;\n }\n return isMutation;\n};\nexport const analyzeDocument = (document, excludeOperationName) => {\n /**\n * Normalize boxed String objects to primitive strings for compatibility with TypedDocumentString.\n *\n * Problem: \\@graphql-codegen with `documentMode: 'string'` generates a TypedDocumentString class that\n * extends the built-in String class, creating \"boxed String\" instances:\n *\n * @see https://github.com/dotansimha/graphql-code-generator/blob/c87b779b9b400813d733fa89dcb16724b30c6d16/packages/plugins/typescript/typed-document-node/src/index.ts#L40-L57\n *\n * ```\n * class TypedDocumentString<TResult, TVariables> extends String\n * constructor(value: string)\n * super(value) // Creates a boxed String object, not a primitive string\n * ```\n *\n * Boxed Strings are objects, not primitives:\n * - `typeof \"hello\" === \"string\"` returns true\n * - `typeof new String(\"hello\") === \"string\"` returns false (returns \"object\")\n *\n * Without normalization, TypedDocumentString instances would fail the `typeof === 'string'` check\n * and incorrectly be passed to `print()`, which expects a DocumentNode AST, causing a crash.\n *\n * Solution: Detect and convert boxed Strings to primitives using template literal coercion.\n * - Primitive strings pass through (typeof === \"string\")\n * - DocumentNode objects pass through (have .kind property)\n * - Boxed Strings get converted to primitives (template literal to primitive string)\n *\n * @see https://github.com/graffle-js/graffle/issues/1453\n */\n const normalizedDocument = typeof document === `string` || `kind` in document\n ? document\n : String(document);\n const expression = typeof normalizedDocument === `string` ? normalizedDocument : print(normalizedDocument);\n let isMutation = false;\n let operationName = undefined;\n if (excludeOperationName) {\n return { expression, isMutation, operationName };\n }\n const docNode = tryCatch(() => (typeof normalizedDocument === `string` ? parse(normalizedDocument) : normalizedDocument));\n if (docNode instanceof Error) {\n return { expression, isMutation, operationName };\n }\n operationName = extractOperationName(docNode);\n isMutation = extractIsMutation(docNode);\n return { expression, operationName, isMutation };\n};\n//# sourceMappingURL=analyzeDocument.js.map","export const defaultJsonSerializer = JSON;\n//# sourceMappingURL=defaultJsonSerializer.js.map","import { ACCEPT_HEADER, CONTENT_TYPE_GQL, CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON } from '../../lib/http.js';\nimport { casesExhausted, uppercase, zip } from '../../lib/prelude.js';\nimport { ClientError } from '../classes/ClientError.js';\nimport { cleanQuery, isGraphQLContentType, isRequestResultHaveErrors, parseGraphQLExecutionResult, } from '../lib/graphql.js';\nimport { defaultJsonSerializer } from './defaultJsonSerializer.js';\n// @ts-expect-error todo\nexport const runRequest = async (input) => {\n // todo make a Config type\n const config = {\n ...input,\n method: input.request._tag === `Single`\n ? input.request.document.isMutation\n ? `POST`\n : uppercase(input.method ?? `post`)\n : input.request.hasMutations\n ? `POST`\n : uppercase(input.method ?? `post`),\n fetchOptions: {\n ...input.fetchOptions,\n errorPolicy: input.fetchOptions.errorPolicy ?? `none`,\n },\n };\n const fetcher = createFetcher(config.method);\n const fetchResponse = await fetcher(config);\n // Read response body text first (can only be read once)\n const body = await fetchResponse.text();\n // Parse response body FIRST, regardless of HTTP status\n // This allows GraphQL errors to be extracted even when HTTP status is 4xx/5xx (fixes #1281)\n let result;\n try {\n result = parseResultFromText(body, fetchResponse.headers.get(CONTENT_TYPE_HEADER), input.fetchOptions.jsonSerializer ?? defaultJsonSerializer);\n }\n catch (error) {\n // If parsing fails, we'll handle it below based on HTTP status\n result = error;\n }\n const clientResponseBase = {\n status: fetchResponse.status,\n headers: fetchResponse.headers,\n body,\n };\n // Handle non-2xx HTTP status codes\n if (!fetchResponse.ok) {\n if (result instanceof Error) {\n // Parse failed - return ClientError without GraphQL data\n // Still returns ClientError (not generic Error) to allow status code access\n return new ClientError({ ...clientResponseBase }, {\n query: input.request._tag === `Single` ? input.request.document.expression : input.request.query,\n variables: input.request.variables,\n });\n }\n // Parse succeeded - return ClientError WITH GraphQL errors/data (fixes #1281)\n const clientResponse = result._tag === `Batch`\n ? { ...result.executionResults, ...clientResponseBase }\n : {\n ...result.executionResult,\n ...clientResponseBase,\n };\n // @ts-expect-error todo\n return new ClientError(clientResponse, {\n query: input.request._tag === `Single` ? input.request.document.expression : input.request.query,\n variables: input.request.variables,\n });\n }\n // For 2xx responses, parse errors should throw\n if (result instanceof Error)\n throw result;\n if (isRequestResultHaveErrors(result) && config.fetchOptions.errorPolicy === `none`) {\n // todo this client response on error is not consistent with the data type for success\n const clientResponse = result._tag === `Batch`\n ? { ...result.executionResults, ...clientResponseBase }\n : {\n ...result.executionResult,\n ...clientResponseBase,\n };\n // @ts-expect-error todo\n return new ClientError(clientResponse, {\n query: input.request._tag === `Single` ? input.request.document.expression : input.request.query,\n variables: input.request.variables,\n });\n }\n switch (result._tag) {\n case `Single`:\n // @ts-expect-error todo\n return {\n ...clientResponseBase,\n ...executionResultClientResponseFields(config)(result.executionResult),\n };\n case `Batch`:\n return {\n ...clientResponseBase,\n data: result.executionResults.map(executionResultClientResponseFields(config)),\n };\n default:\n casesExhausted(result);\n }\n};\nconst executionResultClientResponseFields = ($params) => (executionResult) => {\n return {\n extensions: executionResult.extensions,\n data: executionResult.data,\n errors: $params.fetchOptions.errorPolicy === `all` ? executionResult.errors : undefined,\n };\n};\nconst parseResultFromText = (text, contentType, jsonSerializer) => {\n if (contentType && isGraphQLContentType(contentType)) {\n return parseGraphQLExecutionResult(jsonSerializer.parse(text));\n }\n else {\n // todo what is this good for...? Seems very random/undefined\n return parseGraphQLExecutionResult(text);\n }\n};\nconst createFetcher = (method) => async (params) => {\n const headers = new Headers(params.headers);\n let searchParams = null;\n let body = undefined;\n if (!headers.has(ACCEPT_HEADER)) {\n headers.set(ACCEPT_HEADER, [CONTENT_TYPE_GQL, CONTENT_TYPE_JSON].join(`, `));\n }\n if (method === `POST`) {\n const $jsonSerializer = params.fetchOptions.jsonSerializer ?? defaultJsonSerializer;\n body = $jsonSerializer.stringify(buildBody(params));\n if (typeof body === `string` && !headers.has(CONTENT_TYPE_HEADER)) {\n headers.set(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON);\n }\n }\n else {\n searchParams = buildQueryParams(params);\n }\n const init = { method, headers, body, ...params.fetchOptions };\n let url = new URL(params.url);\n let initResolved = init;\n if (params.middleware) {\n const result = await Promise.resolve(params.middleware({\n ...init,\n url: params.url,\n operationName: params.request._tag === `Single` ? params.request.document.operationName : undefined,\n variables: params.request.variables,\n }));\n const { url: urlNew, ...initNew } = result;\n url = new URL(urlNew);\n initResolved = initNew;\n }\n if (searchParams) {\n searchParams.forEach((value, name) => {\n url.searchParams.append(name, value);\n });\n }\n const $fetch = params.fetch ?? fetch;\n return await $fetch(url, initResolved);\n};\nconst buildBody = (params) => {\n switch (params.request._tag) {\n case `Single`:\n return {\n query: params.request.document.expression,\n variables: params.request.variables,\n operationName: params.request.document.operationName,\n };\n case `Batch`:\n return zip(params.request.query, params.request.variables ?? []).map(([query, variables]) => ({\n query,\n variables,\n }));\n default:\n throw casesExhausted(params.request);\n }\n};\nconst buildQueryParams = (params) => {\n const $jsonSerializer = params.fetchOptions.jsonSerializer ?? defaultJsonSerializer;\n const searchParams = new URLSearchParams();\n switch (params.request._tag) {\n case `Single`: {\n searchParams.append(`query`, cleanQuery(params.request.document.expression));\n if (params.request.variables) {\n searchParams.append(`variables`, $jsonSerializer.stringify(params.request.variables));\n }\n if (params.request.document.operationName) {\n searchParams.append(`operationName`, params.request.document.operationName);\n }\n return searchParams;\n }\n case `Batch`: {\n const variablesSerialized = params.request.variables?.map((v) => $jsonSerializer.stringify(v)) ?? [];\n const queriesCleaned = params.request.query.map(cleanQuery);\n const payload = zip(queriesCleaned, variablesSerialized).map(([query, variables]) => ({\n query,\n variables,\n }));\n searchParams.append(`query`, $jsonSerializer.stringify(payload));\n return searchParams;\n }\n default:\n throw casesExhausted(params.request);\n }\n};\n//# sourceMappingURL=runRequest.js.map","import { callOrIdentity, HeadersInitToPlainObject } from '../../lib/prelude.js';\nimport { parseBatchRequestArgs } from '../functions/batchRequests.js';\nimport { parseRawRequestArgs } from '../functions/rawRequest.js';\nimport { parseRequestArgs } from '../functions/request.js';\nimport { analyzeDocument } from '../helpers/analyzeDocument.js';\nimport { runRequest } from '../helpers/runRequest.js';\n/**\n * GraphQL Client.\n */\nexport class GraphQLClient {\n url;\n requestConfig;\n constructor(url, requestConfig = {}) {\n this.url = url;\n this.requestConfig = requestConfig;\n }\n /**\n * Send a GraphQL query to the server.\n */\n rawRequest = async (...args) => {\n const [queryOrOptions, variables, requestHeaders] = args;\n const rawRequestOptions = parseRawRequestArgs(queryOrOptions, variables, requestHeaders);\n const { headers, fetch = globalThis.fetch, method = `POST`, requestMiddleware, responseMiddleware, excludeOperationName, ...fetchOptions } = this.requestConfig;\n const { url } = this;\n if (rawRequestOptions.signal !== undefined) {\n fetchOptions.signal = rawRequestOptions.signal;\n }\n const document = analyzeDocument(rawRequestOptions.query, excludeOperationName);\n const response = await runRequest({\n url,\n request: {\n _tag: `Single`,\n document,\n variables: rawRequestOptions.variables,\n },\n headers: {\n ...HeadersInitToPlainObject(callOrIdentity(headers)),\n ...HeadersInitToPlainObject(rawRequestOptions.requestHeaders),\n },\n fetch,\n method,\n fetchOptions,\n middleware: requestMiddleware,\n });\n if (responseMiddleware) {\n await responseMiddleware(response, {\n operationName: document.operationName,\n variables,\n url: this.url,\n });\n }\n if (response instanceof Error) {\n throw response;\n }\n return response;\n };\n async request(documentOrOptions, ...variablesAndRequestHeaders) {\n const [variables, requestHeaders] = variablesAndRequestHeaders;\n const requestOptions = parseRequestArgs(documentOrOptions, variables, requestHeaders);\n const { headers, fetch = globalThis.fetch, method = `POST`, requestMiddleware, responseMiddleware, excludeOperationName, ...fetchOptions } = this.requestConfig;\n const { url } = this;\n if (requestOptions.signal !== undefined) {\n fetchOptions.signal = requestOptions.signal;\n }\n const analyzedDocument = analyzeDocument(requestOptions.document, excludeOperationName);\n const response = await runRequest({\n url,\n request: {\n _tag: `Single`,\n document: analyzedDocument,\n variables: requestOptions.variables,\n },\n headers: {\n ...HeadersInitToPlainObject(callOrIdentity(headers)),\n ...HeadersInitToPlainObject(requestOptions.requestHeaders),\n },\n fetch,\n method,\n fetchOptions,\n middleware: requestMiddleware,\n });\n if (responseMiddleware) {\n await responseMiddleware(response, {\n operationName: analyzedDocument.operationName,\n variables: requestOptions.variables,\n url: this.url,\n });\n }\n if (response instanceof Error) {\n throw response;\n }\n return response.data;\n }\n async batchRequests(documentsOrOptions, requestHeaders) {\n const batchRequestOptions = parseBatchRequestArgs(documentsOrOptions, requestHeaders);\n const { headers, excludeOperationName, ...fetchOptions } = this.requestConfig;\n if (batchRequestOptions.signal !== undefined) {\n fetchOptions.signal = batchRequestOptions.signal;\n }\n const analyzedDocuments = batchRequestOptions.documents.map(({ document }) => analyzeDocument(document, excludeOperationName));\n const expressions = analyzedDocuments.map(({ expression }) => expression);\n const hasMutations = analyzedDocuments.some(({ isMutation }) => isMutation);\n const variables = batchRequestOptions.documents.map(({ variables }) => variables);\n const response = await runRequest({\n url: this.url,\n request: {\n _tag: `Batch`,\n operationName: undefined,\n query: expressions,\n hasMutations,\n variables,\n },\n headers: {\n ...HeadersInitToPlainObject(callOrIdentity(headers)),\n ...HeadersInitToPlainObject(batchRequestOptions.requestHeaders),\n },\n fetch: this.requestConfig.fetch ?? globalThis.fetch,\n method: this.requestConfig.method || `POST`,\n fetchOptions,\n middleware: this.requestConfig.requestMiddleware,\n });\n if (this.requestConfig.responseMiddleware) {\n await this.requestConfig.responseMiddleware(response, {\n operationName: undefined,\n variables,\n url: this.url,\n });\n }\n if (response instanceof Error) {\n throw response;\n }\n return response.data;\n }\n setHeaders(headers) {\n this.requestConfig.headers = headers;\n return this;\n }\n /**\n * Attach a header to the client. All subsequent requests will have this header.\n */\n setHeader(key, value) {\n const { headers } = this.requestConfig;\n if (headers) {\n // todo what if headers is in nested array form... ?\n // @ts-expect-error todo\n headers[key] = value;\n }\n else {\n this.requestConfig.headers = { [key]: value };\n }\n return this;\n }\n /**\n * Change the client endpoint. All subsequent requests will send to this endpoint.\n */\n setEndpoint(value) {\n this.url = value;\n return this;\n }\n}\n//# sourceMappingURL=GraphQLClient.js.map","import { GraphQLClient } from '../classes/GraphQLClient.js';\n// dprint-ignore\n// eslint-disable-next-line\nexport async function request(urlOrOptions, document, ...variablesAndRequestHeaders) {\n const requestOptions = parseRequestExtendedArgs(urlOrOptions, document, ...variablesAndRequestHeaders);\n const client = new GraphQLClient(requestOptions.url);\n return client.request({\n ...requestOptions,\n });\n}\nexport const parseRequestArgs = (documentOrOptions, variables, requestHeaders) => {\n return documentOrOptions.document\n ? documentOrOptions\n : {\n document: documentOrOptions,\n variables: variables,\n requestHeaders: requestHeaders,\n signal: undefined,\n };\n};\nexport const parseRequestExtendedArgs = (urlOrOptions, document, ...variablesAndRequestHeaders) => {\n const [variables, requestHeaders] = variablesAndRequestHeaders;\n return typeof urlOrOptions === `string`\n ? {\n url: urlOrOptions,\n document: document,\n variables,\n requestHeaders,\n signal: undefined,\n }\n : urlOrOptions;\n};\n//# sourceMappingURL=request.js.map","import { GraphQLClient } from \"graphql-request\";\nimport { gql } from \"graphql-tag\";\n//#region src/graphql/gen/schema.ts\nlet DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {\n\tDocumentChangeType[\"ChildAdded\"] = \"CHILD_ADDED\";\n\tDocumentChangeType[\"ChildRemoved\"] = \"CHILD_REMOVED\";\n\tDocumentChangeType[\"Created\"] = \"CREATED\";\n\tDocumentChangeType[\"Deleted\"] = \"DELETED\";\n\tDocumentChangeType[\"ParentAdded\"] = \"PARENT_ADDED\";\n\tDocumentChangeType[\"ParentRemoved\"] = \"PARENT_REMOVED\";\n\tDocumentChangeType[\"Updated\"] = \"UPDATED\";\n\treturn DocumentChangeType;\n}({});\nlet PropagationMode = /* @__PURE__ */ function(PropagationMode) {\n\tPropagationMode[\"Cascade\"] = \"CASCADE\";\n\tPropagationMode[\"Orphan\"] = \"ORPHAN\";\n\treturn PropagationMode;\n}({});\nconst 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`;\nconst 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`;\nconst 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`;\nconst 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 deniedReason\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\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`;\nconst GetDocumentOutgoingRelationshipsDocument = gql`\n query GetDocumentOutgoingRelationships(\n $sourceIdentifier: String!\n $relationshipType: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentOutgoingRelationships(\n sourceIdentifier: $sourceIdentifier\n relationshipType: $relationshipType\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`;\nconst GetDocumentIncomingRelationshipsDocument = gql`\n query GetDocumentIncomingRelationships(\n $targetIdentifier: String!\n $relationshipType: String!\n $view: ViewFilterInput\n $paging: PagingInput\n ) {\n documentIncomingRelationships(\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\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`;\nconst 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`;\nconst 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 deniedReason\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\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`;\nconst 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`;\nconst EvaluateActionsDocument = gql`\n query EvaluateActions(\n $documentIdentifier: String!\n $branch: String\n $candidates: [ActionCandidateInput!]!\n ) {\n evaluateActions(\n documentIdentifier: $documentIdentifier\n branch: $branch\n candidates: $candidates\n ) {\n evaluations {\n decision\n reason\n }\n allAllowed\n anyAllowed\n allDenied\n anyDenied\n }\n }\n`;\nconst CreateDocumentDocument = gql`\n mutation CreateDocument($document: JSONObject!, $parentIdentifier: String) {\n createDocument(document: $document, parentIdentifier: $parentIdentifier) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst 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`;\nconst MutateDocumentDocument = gql`\n mutation MutateDocument(\n $documentIdentifier: String!\n $actions: [ActionInput!]!\n $branch: String\n ) {\n mutateDocument: execute(\n documentIdentifier: $documentIdentifier\n actions: $actions\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst MutateDocumentAsyncDocument = gql`\n mutation MutateDocumentAsync(\n $documentIdentifier: String!\n $actions: [ActionInput!]!\n $branch: String\n ) {\n mutateDocumentAsync: executeAsync(\n documentIdentifier: $documentIdentifier\n actions: $actions\n branch: $branch\n ) {\n id\n status\n result\n error\n createdAt\n completedAt\n }\n }\n`;\nconst 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`;\nconst SetPreferredEditorDocument = gql`\n mutation SetPreferredEditor(\n $documentIdentifier: String!\n $preferredEditor: String\n $branch: String\n ) {\n setPreferredEditor(\n documentIdentifier: $documentIdentifier\n preferredEditor: $preferredEditor\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst AddRelationshipDocument = gql`\n mutation AddRelationship(\n $sourceIdentifier: String!\n $targetIdentifier: String!\n $relationshipType: String!\n $branch: String\n ) {\n addRelationship(\n sourceIdentifier: $sourceIdentifier\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst RemoveRelationshipDocument = gql`\n mutation RemoveRelationship(\n $sourceIdentifier: String!\n $targetIdentifier: String!\n $relationshipType: String!\n $branch: String\n ) {\n removeRelationship(\n sourceIdentifier: $sourceIdentifier\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n branch: $branch\n ) {\n ...PHDocumentFields\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst MoveRelationshipDocument = gql`\n mutation MoveRelationship(\n $sourceParentIdentifier: String!\n $targetParentIdentifier: String!\n $targetIdentifier: String!\n $relationshipType: String!\n $branch: String\n ) {\n moveRelationship(\n sourceParentIdentifier: $sourceParentIdentifier\n targetParentIdentifier: $targetParentIdentifier\n targetIdentifier: $targetIdentifier\n relationshipType: $relationshipType\n branch: $branch\n ) {\n source {\n ...PHDocumentFields\n }\n target {\n ...PHDocumentFields\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n`;\nconst DeleteDocumentDocument = gql`\n mutation DeleteDocument($identifier: String!, $propagate: PropagationMode) {\n deleteDocument(identifier: $identifier, propagate: $propagate)\n }\n`;\nconst DeleteDocumentsDocument = gql`\n mutation DeleteDocuments(\n $identifiers: [String!]!\n $propagate: PropagationMode\n ) {\n deleteDocuments(identifiers: $identifiers, propagate: $propagate)\n }\n`;\nconst 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`;\nconst JobChangesDocument = gql`\n subscription JobChanges($jobId: String!) {\n jobChanges(jobId: $jobId) {\n jobId\n status\n result\n error\n }\n }\n`;\nconst 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 deniedReason\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\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 errorType\n }\n hasMore\n }\n }\n`;\nconst TouchChannelDocument = gql`\n mutation TouchChannel($input: TouchChannelInput!) {\n touchChannel(input: $input) {\n success\n ackOrdinal\n }\n }\n`;\nconst PushSyncEnvelopesDocument = gql`\n mutation PushSyncEnvelopes($envelopes: [SyncEnvelopeInput!]!) {\n pushSyncEnvelopes(envelopes: $envelopes)\n }\n`;\nconst defaultWrapper = (action, _operationName, _operationType, _variables) => action();\nfunction getSdk(client, withWrapper = defaultWrapper) {\n\treturn {\n\t\tGetDocumentModels(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentModelsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentModels\", \"query\", variables);\n\t\t},\n\t\tGetDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocument\", \"query\", variables);\n\t\t},\n\t\tGetDocumentWithOperations(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentWithOperationsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentWithOperations\", \"query\", variables);\n\t\t},\n\t\tGetDocumentOutgoingRelationships(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentOutgoingRelationshipsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentOutgoingRelationships\", \"query\", variables);\n\t\t},\n\t\tGetDocumentIncomingRelationships(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentIncomingRelationshipsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentIncomingRelationships\", \"query\", variables);\n\t\t},\n\t\tFindDocuments(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: FindDocumentsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"FindDocuments\", \"query\", variables);\n\t\t},\n\t\tGetDocumentOperations(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetDocumentOperationsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetDocumentOperations\", \"query\", variables);\n\t\t},\n\t\tGetJobStatus(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: GetJobStatusDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"GetJobStatus\", \"query\", variables);\n\t\t},\n\t\tEvaluateActions(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: EvaluateActionsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"EvaluateActions\", \"query\", variables);\n\t\t},\n\t\tCreateDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: CreateDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"CreateDocument\", \"mutation\", variables);\n\t\t},\n\t\tCreateEmptyDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: CreateEmptyDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"CreateEmptyDocument\", \"mutation\", variables);\n\t\t},\n\t\tMutateDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: MutateDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"MutateDocument\", \"mutation\", variables);\n\t\t},\n\t\tMutateDocumentAsync(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: MutateDocumentAsyncDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"MutateDocumentAsync\", \"mutation\", variables);\n\t\t},\n\t\tRenameDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: RenameDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"RenameDocument\", \"mutation\", variables);\n\t\t},\n\t\tSetPreferredEditor(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: SetPreferredEditorDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"SetPreferredEditor\", \"mutation\", variables);\n\t\t},\n\t\tAddRelationship(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: AddRelationshipDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"AddRelationship\", \"mutation\", variables);\n\t\t},\n\t\tRemoveRelationship(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: RemoveRelationshipDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"RemoveRelationship\", \"mutation\", variables);\n\t\t},\n\t\tMoveRelationship(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: MoveRelationshipDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"MoveRelationship\", \"mutation\", variables);\n\t\t},\n\t\tDeleteDocument(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: DeleteDocumentDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"DeleteDocument\", \"mutation\", variables);\n\t\t},\n\t\tDeleteDocuments(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: DeleteDocumentsDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"DeleteDocuments\", \"mutation\", variables);\n\t\t},\n\t\tDocumentChanges(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: DocumentChangesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"DocumentChanges\", \"subscription\", variables);\n\t\t},\n\t\tJobChanges(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: JobChangesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"JobChanges\", \"subscription\", variables);\n\t\t},\n\t\tPollSyncEnvelopes(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: PollSyncEnvelopesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"PollSyncEnvelopes\", \"query\", variables);\n\t\t},\n\t\tTouchChannel(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: TouchChannelDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"TouchChannel\", \"mutation\", variables);\n\t\t},\n\t\tPushSyncEnvelopes(variables, requestHeaders, signal) {\n\t\t\treturn withWrapper((wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument: PushSyncEnvelopesDocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), \"PushSyncEnvelopes\", \"mutation\", variables);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/graphql/batch-queries.ts\n/** Get the source string from a GraphQL document (string or DocumentNode). */\nfunction getDocumentSource(doc) {\n\treturn typeof doc === \"string\" ? doc : doc.loc?.source.body ?? \"\";\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(doc, fieldName, fallback) {\n\tconst source = getDocumentSource(doc);\n\treturn new RegExp(`${fieldName}\\\\([^)]*\\\\)\\\\s*(\\\\{[\\\\s\\\\S]*\\\\})\\\\s*\\\\}`).exec(source)?.[1] ?? fallback;\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(doc, fallbackBody) {\n\tconst source = getDocumentSource(doc);\n\tconst queryMatch = /^[^{]*\\{([\\s\\S]*?)\\}\\s*(fragment[\\s\\S]*)?$/.exec(source);\n\treturn {\n\t\tbody: queryMatch?.[1]?.trim() ?? fallbackBody,\n\t\tfragments: queryMatch?.[2]?.trim() ?? \"\"\n\t};\n}\nconst operationsSelectionSet = extractSelectionSet(GetDocumentOperationsDocument, \"documentOperations\", \"{ items { index } }\");\nconst documentParts = extractQueryParts(GetDocumentDocument, \"document(identifier: $identifier) { document { id name documentType state revisionsList { scope revision } createdAtUtcIso lastModifiedAtUtcIso } childIds }\");\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*/\nfunction buildBatchOperationsQuery(filters, pagings) {\n\tconst query = `query BatchGetDocumentOperations(${filters.flatMap((_, i) => [`$filter_${i}: OperationsFilterInput!`, `$paging_${i}: PagingInput`]).join(\", \")}) {\n ${filters.map((_, i) => `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`).join(\"\\n \")}\n }`;\n\tconst variables = {};\n\tfor (let i = 0; i < filters.length; i++) {\n\t\tvariables[`filter_${i}`] = filters[i];\n\t\tvariables[`paging_${i}`] = pagings[i] ?? null;\n\t}\n\treturn {\n\t\tquery,\n\t\tvariables\n\t};\n}\n/**\n* Build a single GraphQL query that fetches a document AND\n* documentOperations for multiple filters, all in one HTTP request.\n*/\nfunction buildBatchDocumentWithOperationsQuery(identifier, view, filters, pagings) {\n\tconst docVarDefs = \"$identifier: String!, $view: ViewFilterInput\";\n\tconst opsVarDefs = filters.flatMap((_, i) => [`$filter_${i}: OperationsFilterInput!`, `$paging_${i}: PagingInput`]).join(\", \");\n\tconst opsFields = filters.map((_, i) => `scope_${i}: documentOperations(filter: $filter_${i}, paging: $paging_${i}) ${operationsSelectionSet}`).join(\"\\n \");\n\tconst query = `query BatchGetDocumentWithOperations(${docVarDefs}, ${opsVarDefs}) {\n ${documentParts.body}\n ${opsFields}\n }\n ${documentParts.fragments}`;\n\tconst variables = {\n\t\tidentifier,\n\t\tview: view ?? null\n\t};\n\tfor (let i = 0; i < filters.length; i++) {\n\t\tvariables[`filter_${i}`] = filters[i];\n\t\tvariables[`paging_${i}`] = pagings[i] ?? null;\n\t}\n\treturn {\n\t\tquery,\n\t\tvariables\n\t};\n}\n//#endregion\n//#region src/graphql/client.ts\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*/\nfunction createClient(urlOrGQLClient, middleware) {\n\tconst client = typeof urlOrGQLClient === \"string\" ? new GraphQLClient(urlOrGQLClient) : urlOrGQLClient;\n\tconst runWithMiddleware = async (operationName, run, operationType = \"query\", variables) => {\n\t\tif (!middleware) return run();\n\t\treturn middleware(run, operationName, operationType, variables);\n\t};\n\treturn {\n\t\t...getSdk(client, middleware),\n\t\tasync RunDocument(options) {\n\t\t\tconst { document, variables, signal } = options;\n\t\t\treturn runWithMiddleware(options.operationName, (wrappedRequestHeaders) => client.request({\n\t\t\t\tdocument,\n\t\t\t\tvariables,\n\t\t\t\trequestHeaders: {\n\t\t\t\t\t...options.requestHeaders,\n\t\t\t\t\t...wrappedRequestHeaders\n\t\t\t\t},\n\t\t\t\tsignal\n\t\t\t}), options.operationType, variables);\n\t\t},\n\t\tasync BatchGetDocumentOperations(filters, pagings) {\n\t\t\tconst { query, variables } = buildBatchOperationsQuery(filters, pagings);\n\t\t\tconst data = await runWithMiddleware(\"BatchGetDocumentOperations\", (requestHeaders) => client.request(query, variables, requestHeaders));\n\t\t\treturn filters.map((_, i) => data[`scope_${i}`]);\n\t\t},\n\t\tasync BatchGetDocumentWithOperations(identifier, view, filters, pagings) {\n\t\t\tconst { query, variables } = buildBatchDocumentWithOperationsQuery(identifier, view, filters, pagings);\n\t\t\tconst data = await runWithMiddleware(\"BatchGetDocumentWithOperations\", (requestHeaders) => client.request(query, variables, requestHeaders));\n\t\t\treturn {\n\t\t\t\tdocument: data.document ?? null,\n\t\t\t\toperations: filters.map((_, i) => data[`scope_${i}`])\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\nexport { PhDocumentFieldsFragmentDoc as a, GetDocumentWithOperationsDocument as i, DocumentChangeType as n, PropagationMode as o, DocumentChangesDocument as r, createClient as t };\n\n//# sourceMappingURL=client-D66jVnot.js.map","import { t as makePHEventFunctions } from \"./make-ph-event-functions-DBq3iWYn.js\";\nimport { createContext, useContext, useEffect, useState, useSyncExternalStore } from \"react\";\nimport { jsx } from \"react/jsx-runtime\";\n//#region src/hooks/loading.ts\nconst { useValue: useLoading, setValue: setLoading, addEventHandler: addLoadingEventHandler } = makePHEventFunctions(\"loading\");\nconst loading = null;\n//#endregion\n//#region src/renown/initial-user.tsx\nconst RENOWN_INITIAL_UNKNOWN = { state: \"unknown\" };\nconst RENOWN_INITIAL_ANONYMOUS = { state: \"anonymous\" };\nconst RenownInitialUserContext = createContext(RENOWN_INITIAL_UNKNOWN);\nfunction RenownInitialUserProvider({ initialAuth, initialUser, children }) {\n\tconst value = initialAuth ?? (initialUser ? {\n\t\tstate: \"authenticated\",\n\t\tuser: initialUser\n\t} : RENOWN_INITIAL_UNKNOWN);\n\treturn /* @__PURE__ */ jsx(RenownInitialUserContext.Provider, {\n\t\tvalue,\n\t\tchildren\n\t});\n}\n/** First-render auth as a three-state value; use this to skip a spinner when anonymous. */\nfunction useRenownInitialAuth() {\n\treturn useContext(RenownInitialUserContext);\n}\nfunction useRenownInitialUser() {\n\tconst initial = useRenownInitialAuth();\n\treturn initial.state === \"authenticated\" ? initial.user : void 0;\n}\n//#endregion\n//#region src/hooks/renown.ts\nconst renownEventFunctions = makePHEventFunctions(\"renown\");\n/** Adds an event handler for the renown instance */\nconst addRenownEventHandler = renownEventFunctions.addEventHandler;\n/** Returns the renown instance */\nconst useRenown = renownEventFunctions.useValue;\n/** Sets the renown instance */\nconst setRenown = renownEventFunctions.setValue;\n/** Returns the DID from the renown instance */\nfunction useDid() {\n\treturn useRenown()?.did;\n}\nfunction jsonEqual(a, b) {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || !a || !b) return false;\n\tif (Array.isArray(a) !== Array.isArray(b)) return false;\n\tconst ra = a;\n\tconst rb = b;\n\tconst keys = Object.keys(ra).filter((k) => ra[k] !== void 0);\n\tif (keys.length !== Object.keys(rb).filter((k) => rb[k] !== void 0).length) return false;\n\treturn keys.every((k) => jsonEqual(ra[k], rb[k]));\n}\nfunction sameUser(a, b) {\n\treturn jsonEqual(a, b);\n}\nfunction resolveInstanceUser(instance, seed) {\n\tconst restored = instance.user;\n\tif (restored) return sameUser(seed, restored) ? seed : restored;\n\treturn instance.status === \"initial\" ? void 0 : seed;\n}\n/** Returns the current user from the renown instance, subscribing to user events */\nfunction useUser() {\n\tconst renown = useRenown();\n\tconst initialUser = useRenownInitialUser();\n\tconst instance = renown ? renown : void 0;\n\tconst [tracked, setTracked] = useState(() => ({\n\t\tinstance,\n\t\tuser: instance ? resolveInstanceUser(instance, initialUser) : initialUser\n\t}));\n\tconst current = tracked.instance === instance ? tracked : {\n\t\tinstance,\n\t\tuser: instance ? resolveInstanceUser(instance, tracked.user ?? initialUser) : tracked.user\n\t};\n\tuseEffect(() => {\n\t\tif (current !== tracked) setTracked(current);\n\t}, [current, tracked]);\n\tuseEffect(() => {\n\t\tif (!instance) return;\n\t\treturn instance.on(\"user\", (user) => setTracked((prev) => ({\n\t\t\tinstance,\n\t\t\tuser: sameUser(prev.user, user) ? prev.user : user\n\t\t})));\n\t}, [instance]);\n\treturn instance ? current.user : initialUser ?? current.user;\n}\n/** Returns the login status, subscribing to renown status events */\nfunction useLoginStatus() {\n\tconst renown = useRenown();\n\treturn useSyncExternalStore((cb) => {\n\t\tif (!renown) return () => {};\n\t\treturn renown.on(\"status\", cb);\n\t}, () => renown === null ? \"loading\" : renown?.status, () => void 0);\n}\n//#endregion\nexport { useRenown as a, RENOWN_INITIAL_UNKNOWN as c, useRenownInitialUser as d, addLoadingEventHandler as f, useLoading as h, useLoginStatus as i, RenownInitialUserProvider as l, setLoading as m, setRenown as n, useUser as o, loading as p, useDid as r, RENOWN_INITIAL_ANONYMOUS as s, addRenownEventHandler as t, useRenownInitialAuth as u };\n\n//# sourceMappingURL=renown-BHxwP7xU.js.map","function e(e,t,n){let r=n=>e(n,...t);return n===void 0?r:Object.assign(r,{lazy:n,lazyArgs:t})}export{e as t};\n//# sourceMappingURL=lazyDataLastImpl-DtF3cihj.js.map","import{t as e}from\"./lazyDataLastImpl-DtF3cihj.js\";function t(t,n,r){let i=t.length-n.length;if(i===0)return t(...n);if(i===1)return e(t,n,r);throw Error(`Wrong number of arguments`)}export{t as purry};\n//# sourceMappingURL=purry.js.map","import{purry as e}from\"./purry.js\";function t(...t){return e(n,t)}const n=(e,t)=>t.every(t=>t(e));export{t as allPass};\n//# sourceMappingURL=allPass.js.map","function e(e,t,n){return e(n[0])?e=>t(e,...n):t(...n)}function t(...t){return e(r,n,t)}function n(e,...t){for(let n of t){if(typeof n==`function`)return n(e);let[t,r]=n;if(t(e))return r(e)}throw Error(`conditional: data failed for all cases`)}function r(e){if(!Array.isArray(e))return!1;let[t,n,...r]=e;return typeof t==`function`&&t.length<=1&&typeof n==`function`&&n.length<=1&&r.length===0}export{t};\n//# sourceMappingURL=conditional-CTEJD5TX.js.map","function e(e){return()=>e}export{e as constant};\n//# sourceMappingURL=constant.js.map","import{purry as e}from\"./purry.js\";function t(...t){return e(n,t)}const n=(e,t)=>e.length>=t;export{t as hasAtLeast};\n//# sourceMappingURL=hasAtLeast.js.map","const e=Symbol(`funnel/voidReducer`),t=()=>e;function n(n,{triggerAt:r=`end`,minQuietPeriodMs:i,maxBurstDurationMs:a,minGapMs:o,reducer:s=t}){let c,l,u,d,f=()=>{let t=u;t!==void 0&&(u=void 0,t===e?n():n(t),o!==void 0&&(l=setTimeout(p,o)))},p=()=>{clearTimeout(l),l=void 0,c===void 0&&f()},m=()=>{clearTimeout(c),c=void 0,d=void 0,l===void 0&&f()};return{call:(...e)=>{let t=c===void 0&&l===void 0;if((r!==`start`||t)&&(u=s(u,...e)),!(c===void 0&&!t)){if(i!==void 0||a!==void 0||o===void 0){clearTimeout(c);let e=Date.now();d??=e;let t=a===void 0?i??0:Math.min(i??a,Math.max(0,a-(e-d)));c=setTimeout(m,t)}r!==`end`&&t&&f()}},cancel:()=>{clearTimeout(c),c=void 0,d=void 0,clearTimeout(l),l=void 0,u=void 0},flush:()=>{m(),p()},get isIdle(){return c===void 0&&l===void 0}}}export{n as funnel};\n//# sourceMappingURL=funnel.js.map","function e(e){return e!==void 0}export{e as isDefined};\n//# sourceMappingURL=isDefined.js.map","function e(e){return t=>!e(t)}export{e as isNot};\n//# sourceMappingURL=isNot.js.map","import{purry as e}from\"./purry.js\";function t(...t){return e(n,t)}const n=(e,t)=>e===t||Object.is(e,t);export{t as isStrictEqual};\n//# sourceMappingURL=isStrictEqual.js.map","function e(e){return typeof e==`string`}export{e as isString};\n//# sourceMappingURL=isString.js.map","function e(e){return!!e}export{e as isTruthy};\n//# sourceMappingURL=isTruthy.js.map","function e(e){let t=!1,n;return()=>(t||=(n=e(),!0),n)}export{e as once};\n//# sourceMappingURL=once.js.map","function extendedTypeof(val) {\n if (val === null) {\n return \"null\";\n }\n if (Array.isArray(val)) {\n return \"array\";\n }\n return typeof val;\n}\nfunction isObject(val) {\n return extendedTypeof(val) === \"object\";\n}\nfunction isAsyncIterable(val) {\n return typeof Object(val)[Symbol.asyncIterator] === \"function\";\n}\nfunction isAsyncGenerator(val) {\n return isObject(val) && typeof Object(val)[Symbol.asyncIterator] === \"function\" && typeof val.return === \"function\";\n}\nfunction areGraphQLFormattedErrors(obj) {\n return Array.isArray(obj) && // must be at least one error\n obj.length > 0 && // error has at least a message\n obj.every((ob) => \"message\" in ob);\n}\nfunction limitCloseReason(reason, whenTooLong) {\n return reason.length < 124 ? reason : whenTooLong;\n}\n\nconst GRAPHQL_TRANSPORT_WS_PROTOCOL = \"graphql-transport-ws\";\nconst DEPRECATED_GRAPHQL_WS_PROTOCOL = \"graphql-ws\";\nvar CloseCode = /* @__PURE__ */ ((CloseCode2) => {\n CloseCode2[CloseCode2[\"InternalServerError\"] = 4500] = \"InternalServerError\";\n CloseCode2[CloseCode2[\"InternalClientError\"] = 4005] = \"InternalClientError\";\n CloseCode2[CloseCode2[\"BadRequest\"] = 4400] = \"BadRequest\";\n CloseCode2[CloseCode2[\"BadResponse\"] = 4004] = \"BadResponse\";\n CloseCode2[CloseCode2[\"Unauthorized\"] = 4401] = \"Unauthorized\";\n CloseCode2[CloseCode2[\"Forbidden\"] = 4403] = \"Forbidden\";\n CloseCode2[CloseCode2[\"SubprotocolNotAcceptable\"] = 4406] = \"SubprotocolNotAcceptable\";\n CloseCode2[CloseCode2[\"ConnectionInitialisationTimeout\"] = 4408] = \"ConnectionInitialisationTimeout\";\n CloseCode2[CloseCode2[\"ConnectionAcknowledgementTimeout\"] = 4504] = \"ConnectionAcknowledgementTimeout\";\n CloseCode2[CloseCode2[\"SubscriberAlreadyExists\"] = 4409] = \"SubscriberAlreadyExists\";\n CloseCode2[CloseCode2[\"TooManyInitialisationRequests\"] = 4429] = \"TooManyInitialisationRequests\";\n return CloseCode2;\n})(CloseCode || {});\nvar MessageType = /* @__PURE__ */ ((MessageType2) => {\n MessageType2[\"ConnectionInit\"] = \"connection_init\";\n MessageType2[\"ConnectionAck\"] = \"connection_ack\";\n MessageType2[\"Ping\"] = \"ping\";\n MessageType2[\"Pong\"] = \"pong\";\n MessageType2[\"Subscribe\"] = \"subscribe\";\n MessageType2[\"Next\"] = \"next\";\n MessageType2[\"Error\"] = \"error\";\n MessageType2[\"Complete\"] = \"complete\";\n return MessageType2;\n})(MessageType || {});\nfunction validateMessage(val) {\n if (!isObject(val)) {\n throw new Error(\n `Message is expected to be an object, but got ${extendedTypeof(val)}`\n );\n }\n if (!val.type) {\n throw new Error(`Message is missing the 'type' property`);\n }\n if (typeof val.type !== \"string\") {\n throw new Error(\n `Message is expects the 'type' property to be a string, but got ${extendedTypeof(\n val.type\n )}`\n );\n }\n switch (val.type) {\n case \"connection_init\" /* ConnectionInit */:\n case \"connection_ack\" /* ConnectionAck */:\n case \"ping\" /* Ping */:\n case \"pong\" /* Pong */: {\n if (val.payload != null && !isObject(val.payload)) {\n throw new Error(\n `\"${val.type}\" message expects the 'payload' property to be an object or nullish or missing, but got \"${val.payload}\"`\n );\n }\n break;\n }\n case \"subscribe\" /* Subscribe */: {\n if (typeof val.id !== \"string\") {\n throw new Error(\n `\"${val.type}\" message expects the 'id' property to be a string, but got ${extendedTypeof(\n val.id\n )}`\n );\n }\n if (!val.id) {\n throw new Error(\n `\"${val.type}\" message requires a non-empty 'id' property`\n );\n }\n if (!isObject(val.payload)) {\n throw new Error(\n `\"${val.type}\" message expects the 'payload' property to be an object, but got ${extendedTypeof(\n val.payload\n )}`\n );\n }\n if (typeof val.payload.query !== \"string\") {\n throw new Error(\n `\"${val.type}\" message payload expects the 'query' property to be a string, but got ${extendedTypeof(\n val.payload.query\n )}`\n );\n }\n if (val.payload.variables != null && !isObject(val.payload.variables)) {\n throw new Error(\n `\"${val.type}\" message payload expects the 'variables' property to be a an object or nullish or missing, but got ${extendedTypeof(\n val.payload.variables\n )}`\n );\n }\n if (val.payload.operationName != null && extendedTypeof(val.payload.operationName) !== \"string\") {\n throw new Error(\n `\"${val.type}\" message payload expects the 'operationName' property to be a string or nullish or missing, but got ${extendedTypeof(\n val.payload.operationName\n )}`\n );\n }\n if (val.payload.extensions != null && !isObject(val.payload.extensions)) {\n throw new Error(\n `\"${val.type}\" message payload expects the 'extensions' property to be a an object or nullish or missing, but got ${extendedTypeof(\n val.payload.extensions\n )}`\n );\n }\n break;\n }\n case \"next\" /* Next */: {\n if (typeof val.id !== \"string\") {\n throw new Error(\n `\"${val.type}\" message expects the 'id' property to be a string, but got ${extendedTypeof(\n val.id\n )}`\n );\n }\n if (!val.id) {\n throw new Error(\n `\"${val.type}\" message requires a non-empty 'id' property`\n );\n }\n if (!isObject(val.payload)) {\n throw new Error(\n `\"${val.type}\" message expects the 'payload' property to be an object, but got ${extendedTypeof(\n val.payload\n )}`\n );\n }\n break;\n }\n case \"error\" /* Error */: {\n if (typeof val.id !== \"string\") {\n throw new Error(\n `\"${val.type}\" message expects the 'id' property to be a string, but got ${extendedTypeof(\n val.id\n )}`\n );\n }\n if (!val.id) {\n throw new Error(\n `\"${val.type}\" message requires a non-empty 'id' property`\n );\n }\n if (!areGraphQLFormattedErrors(val.payload)) {\n throw new Error(\n `\"${val.type}\" message expects the 'payload' property to be an array of GraphQL errors, but got ${JSON.stringify(\n val.payload\n )}`\n );\n }\n break;\n }\n case \"complete\" /* Complete */: {\n if (typeof val.id !== \"string\") {\n throw new Error(\n `\"${val.type}\" message expects the 'id' property to be a string, but got ${extendedTypeof(\n val.id\n )}`\n );\n }\n if (!val.id) {\n throw new Error(\n `\"${val.type}\" message requires a non-empty 'id' property`\n );\n }\n break;\n }\n default:\n throw new Error(`Invalid message 'type' property \"${val.type}\"`);\n }\n return val;\n}\nfunction parseMessage(data, reviver) {\n return validateMessage(\n typeof data === \"string\" ? JSON.parse(data, reviver) : data\n );\n}\nfunction stringifyMessage(msg, replacer) {\n validateMessage(msg);\n return JSON.stringify(msg, replacer);\n}\n\nexport { CloseCode as C, DEPRECATED_GRAPHQL_WS_PROTOCOL as D, GRAPHQL_TRANSPORT_WS_PROTOCOL as G, MessageType as M, isAsyncGenerator as a, isAsyncIterable as b, isObject as i, limitCloseReason as l, parseMessage as p, stringifyMessage as s, validateMessage as v };\n","import { i as isObject, G as GRAPHQL_TRANSPORT_WS_PROTOCOL, s as stringifyMessage, M as MessageType, C as CloseCode, l as limitCloseReason, p as parseMessage } from './common-CGW11Fyb.js';\nexport { D as DEPRECATED_GRAPHQL_WS_PROTOCOL, v as validateMessage } from './common-CGW11Fyb.js';\n\nfunction createClient(options) {\n const {\n url,\n connectionParams,\n lazy = true,\n onNonLazyError = console.error,\n lazyCloseTimeout: lazyCloseTimeoutMs = 0,\n keepAlive = 0,\n disablePong,\n connectionAckWaitTimeout = 0,\n retryAttempts = 5,\n retryWait = async function randomisedExponentialBackoff(retries2) {\n const retryDelaySeconds = Math.pow(2, retries2);\n await new Promise(\n (resolve) => setTimeout(\n resolve,\n retryDelaySeconds * 1e3 + // add random timeout from 300ms to 3s\n Math.floor(Math.random() * (3e3 - 300) + 300)\n )\n );\n },\n shouldRetry = isLikeCloseEvent,\n on,\n webSocketImpl,\n /**\n * Generates a v4 UUID to be used as the ID using `Math`\n * as the random number generator. Supply your own generator\n * in case you need more uniqueness.\n *\n * Reference: https://gist.github.com/jed/982883\n */\n generateID = function generateUUID() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = Math.random() * 16 | 0, v = c == \"x\" ? r : r & 3 | 8;\n return v.toString(16);\n });\n },\n jsonMessageReplacer: replacer,\n jsonMessageReviver: reviver\n } = options;\n let ws;\n if (webSocketImpl) {\n if (!isWebSocket(webSocketImpl)) {\n throw new Error(\"Invalid WebSocket implementation provided\");\n }\n ws = webSocketImpl;\n } else if (typeof WebSocket !== \"undefined\") {\n ws = WebSocket;\n } else if (typeof global !== \"undefined\") {\n ws = global.WebSocket || // @ts-expect-error: Support more browsers\n global.MozWebSocket;\n } else if (typeof window !== \"undefined\") {\n ws = window.WebSocket || // @ts-expect-error: Support more browsers\n window.MozWebSocket;\n }\n if (!ws)\n throw new Error(\n \"WebSocket implementation missing; on Node you can `import WebSocket from 'ws';` and pass `webSocketImpl: WebSocket` to `createClient`\"\n );\n const WebSocketImpl = ws;\n const emitter = (() => {\n const message = /* @__PURE__ */ (() => {\n const listeners2 = {};\n return {\n on(id, listener) {\n listeners2[id] = listener;\n return () => {\n delete listeners2[id];\n };\n },\n emit(message2) {\n if (\"id\" in message2) listeners2[message2.id]?.(message2);\n }\n };\n })();\n const listeners = {\n connecting: on?.connecting ? [on.connecting] : [],\n opened: on?.opened ? [on.opened] : [],\n connected: on?.connected ? [on.connected] : [],\n ping: on?.ping ? [on.ping] : [],\n pong: on?.pong ? [on.pong] : [],\n message: on?.message ? [message.emit, on.message] : [message.emit],\n closed: on?.closed ? [on.closed] : [],\n error: on?.error ? [on.error] : []\n };\n return {\n onMessage: message.on,\n on(event, listener) {\n const l = listeners[event];\n l.push(listener);\n return () => {\n l.splice(l.indexOf(listener), 1);\n };\n },\n emit(event, ...args) {\n for (const listener of [...listeners[event]]) {\n listener(...args);\n }\n }\n };\n })();\n function errorOrClosed(cb) {\n const listening = [\n // errors are fatal and more critical than close events, throw them first\n emitter.on(\"error\", (err) => {\n listening.forEach((unlisten) => unlisten());\n cb(err);\n }),\n // closes can be graceful and not fatal, throw them second (if error didnt throw)\n emitter.on(\"closed\", (event) => {\n listening.forEach((unlisten) => unlisten());\n cb(event);\n })\n ];\n }\n let connecting, locks = 0, lazyCloseTimeout, retrying = false, retries = 0, disposed = false;\n async function connect() {\n clearTimeout(lazyCloseTimeout);\n const [socket, throwOnClose] = await (connecting ?? (connecting = new Promise(\n (connected, denied) => (async () => {\n if (retrying) {\n await retryWait(retries);\n if (!locks) {\n connecting = void 0;\n return denied({ code: 1e3, reason: \"All Subscriptions Gone\" });\n }\n retries++;\n }\n emitter.emit(\"connecting\", retrying);\n const socket2 = new WebSocketImpl(\n typeof url === \"function\" ? await url() : url,\n GRAPHQL_TRANSPORT_WS_PROTOCOL\n );\n let connectionAckTimeout, queuedPing;\n function enqueuePing() {\n if (isFinite(keepAlive) && keepAlive > 0) {\n clearTimeout(queuedPing);\n queuedPing = setTimeout(() => {\n if (socket2.readyState === WebSocketImpl.OPEN) {\n socket2.send(stringifyMessage({ type: MessageType.Ping }));\n emitter.emit(\"ping\", false, void 0);\n }\n }, keepAlive);\n }\n }\n errorOrClosed((errOrEvent) => {\n connecting = void 0;\n clearTimeout(connectionAckTimeout);\n clearTimeout(queuedPing);\n denied(errOrEvent);\n if (errOrEvent instanceof TerminatedCloseEvent) {\n socket2.close(4499, \"Terminated\");\n socket2.onerror = null;\n socket2.onclose = null;\n }\n });\n socket2.onerror = (err) => emitter.emit(\"error\", err);\n socket2.onclose = (event) => emitter.emit(\"closed\", event);\n socket2.onopen = async () => {\n try {\n emitter.emit(\"opened\", socket2);\n const payload = typeof connectionParams === \"function\" ? await connectionParams() : connectionParams;\n if (socket2.readyState !== WebSocketImpl.OPEN) return;\n socket2.send(\n stringifyMessage(\n payload ? {\n type: MessageType.ConnectionInit,\n payload\n } : {\n type: MessageType.ConnectionInit\n // payload is completely absent if not provided\n },\n replacer\n )\n );\n if (isFinite(connectionAckWaitTimeout) && connectionAckWaitTimeout > 0) {\n connectionAckTimeout = setTimeout(() => {\n socket2.close(\n CloseCode.ConnectionAcknowledgementTimeout,\n \"Connection acknowledgement timeout\"\n );\n }, connectionAckWaitTimeout);\n }\n enqueuePing();\n } catch (err) {\n emitter.emit(\"error\", err);\n socket2.close(\n CloseCode.InternalClientError,\n limitCloseReason(\n err instanceof Error ? err.message : String(err),\n \"Internal client error\"\n )\n );\n }\n };\n let acknowledged = false;\n socket2.onmessage = ({ data }) => {\n try {\n const message = parseMessage(data, reviver);\n emitter.emit(\"message\", message);\n if (message.type === \"ping\" || message.type === \"pong\") {\n emitter.emit(message.type, true, message.payload);\n if (message.type === \"pong\") {\n enqueuePing();\n } else if (!disablePong) {\n socket2.send(\n stringifyMessage(\n message.payload ? {\n type: MessageType.Pong,\n payload: message.payload\n } : {\n type: MessageType.Pong\n // payload is completely absent if not provided\n }\n )\n );\n emitter.emit(\"pong\", false, message.payload);\n }\n return;\n }\n if (acknowledged) return;\n if (message.type !== MessageType.ConnectionAck)\n throw new Error(\n `First message cannot be of type ${message.type}`\n );\n clearTimeout(connectionAckTimeout);\n acknowledged = true;\n emitter.emit(\"connected\", socket2, message.payload, retrying);\n retrying = false;\n retries = 0;\n connected([\n socket2,\n new Promise((_, reject) => errorOrClosed(reject))\n ]);\n } catch (err) {\n socket2.onmessage = null;\n emitter.emit(\"error\", err);\n socket2.close(\n CloseCode.BadResponse,\n limitCloseReason(\n err instanceof Error ? err.message : String(err),\n \"Bad response\"\n )\n );\n }\n };\n })()\n )));\n if (socket.readyState === WebSocketImpl.CLOSING) await throwOnClose;\n let release = () => {\n };\n const released = new Promise((resolve) => release = resolve);\n return [\n socket,\n release,\n Promise.race([\n // wait for\n released.then(() => {\n if (!locks) {\n const complete = () => socket.close(1e3, \"Normal Closure\");\n if (isFinite(lazyCloseTimeoutMs) && lazyCloseTimeoutMs > 0) {\n lazyCloseTimeout = setTimeout(() => {\n if (socket.readyState === WebSocketImpl.OPEN) complete();\n }, lazyCloseTimeoutMs);\n } else {\n complete();\n }\n }\n }),\n // or\n throwOnClose\n ])\n ];\n }\n function shouldRetryConnectOrThrow(errOrCloseEvent) {\n if (isLikeCloseEvent(errOrCloseEvent) && (isFatalInternalCloseCode(errOrCloseEvent.code) || [\n CloseCode.InternalServerError,\n CloseCode.InternalClientError,\n CloseCode.BadRequest,\n CloseCode.BadResponse,\n CloseCode.Unauthorized,\n // CloseCode.Forbidden, might grant access out after retry\n CloseCode.SubprotocolNotAcceptable,\n // CloseCode.ConnectionInitialisationTimeout, might not time out after retry\n // CloseCode.ConnectionAcknowledgementTimeout, might not time out after retry\n CloseCode.SubscriberAlreadyExists,\n CloseCode.TooManyInitialisationRequests\n // 4499, // Terminated, probably because the socket froze, we want to retry\n ].includes(errOrCloseEvent.code)))\n throw errOrCloseEvent;\n if (disposed) return false;\n if (isLikeCloseEvent(errOrCloseEvent) && errOrCloseEvent.code === 1e3)\n return locks > 0;\n if (!retryAttempts || retries >= retryAttempts) throw errOrCloseEvent;\n if (!shouldRetry(errOrCloseEvent)) throw errOrCloseEvent;\n return retrying = true;\n }\n if (!lazy) {\n (async () => {\n locks++;\n for (; ; ) {\n try {\n const [, , throwOnClose] = await connect();\n await throwOnClose;\n } catch (errOrCloseEvent) {\n try {\n if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return;\n } catch (errOrCloseEvent2) {\n return onNonLazyError?.(errOrCloseEvent2);\n }\n }\n }\n })();\n }\n function subscribe(payload, sink) {\n const id = generateID(payload);\n let done = false, errored = false, releaser = () => {\n locks--;\n done = true;\n };\n (async () => {\n locks++;\n for (; ; ) {\n try {\n const [socket, release, waitForReleaseOrThrowOnClose] = await connect();\n if (done) return release();\n const unlisten = emitter.onMessage(id, (message) => {\n switch (message.type) {\n case MessageType.Next: {\n sink.next(message.payload);\n return;\n }\n case MessageType.Error: {\n errored = true, done = true;\n sink.error(message.payload);\n releaser();\n return;\n }\n case MessageType.Complete: {\n done = true;\n releaser();\n return;\n }\n }\n });\n socket.send(\n stringifyMessage(\n {\n id,\n type: MessageType.Subscribe,\n payload\n },\n replacer\n )\n );\n releaser = () => {\n if (!done && socket.readyState === WebSocketImpl.OPEN)\n socket.send(\n stringifyMessage(\n {\n id,\n type: MessageType.Complete\n },\n replacer\n )\n );\n locks--;\n done = true;\n release();\n };\n await waitForReleaseOrThrowOnClose.finally(unlisten);\n return;\n } catch (errOrCloseEvent) {\n if (!shouldRetryConnectOrThrow(errOrCloseEvent)) return;\n }\n }\n })().then(() => {\n if (!errored) sink.complete();\n }).catch((err) => {\n sink.error(err);\n });\n return () => {\n if (!done) releaser();\n };\n }\n return {\n on: emitter.on,\n subscribe,\n iterate(request) {\n const pending = [];\n const deferred = {\n done: false,\n error: null,\n resolve: () => {\n }\n };\n const dispose = subscribe(request, {\n next(val) {\n pending.push(val);\n deferred.resolve();\n },\n error(err) {\n deferred.done = true;\n deferred.error = err;\n deferred.resolve();\n },\n complete() {\n deferred.done = true;\n deferred.resolve();\n }\n });\n const iterator = async function* iterator2() {\n for (; ; ) {\n if (!pending.length) {\n await new Promise((resolve) => deferred.resolve = resolve);\n }\n while (pending.length) {\n yield pending.shift();\n }\n if (deferred.error) {\n throw deferred.error;\n }\n if (deferred.done) {\n return;\n }\n }\n }();\n iterator.throw = async (err) => {\n if (!deferred.done) {\n deferred.done = true;\n deferred.error = err;\n deferred.resolve();\n }\n return { done: true, value: void 0 };\n };\n iterator.return = async () => {\n dispose();\n return { done: true, value: void 0 };\n };\n return iterator;\n },\n async dispose() {\n disposed = true;\n if (connecting) {\n const [socket] = await connecting;\n socket.close(1e3, \"Normal Closure\");\n }\n },\n terminate() {\n if (connecting) {\n emitter.emit(\"closed\", new TerminatedCloseEvent());\n }\n }\n };\n}\nclass TerminatedCloseEvent extends Error {\n name = \"TerminatedCloseEvent\";\n message = \"4499: Terminated\";\n code = 4499;\n reason = \"Terminated\";\n wasClean = false;\n}\nfunction isLikeCloseEvent(val) {\n return isObject(val) && \"code\" in val && \"reason\" in val;\n}\nfunction isFatalInternalCloseCode(code) {\n if ([\n 1e3,\n // Normal Closure is not an erroneous close code\n 1001,\n // Going Away\n 1006,\n // Abnormal Closure\n 1005,\n // No Status Received\n 1012,\n // Service Restart\n 1013,\n // Try Again Later\n 1014\n // Bad Gateway\n ].includes(code))\n return false;\n return code >= 1e3 && code <= 1999;\n}\nfunction isWebSocket(val) {\n return typeof val === \"function\" && \"constructor\" in val && \"CLOSED\" in val && \"CLOSING\" in val && \"CONNECTING\" in val && \"OPEN\" in val;\n}\n\nexport { CloseCode, GRAPHQL_TRANSPORT_WS_PROTOCOL, MessageType, TerminatedCloseEvent, createClient, parseMessage, stringifyMessage };\n","import { S as uploadOperations, a as setDocumentCache, b as queueActions, g as DOCUMENT_CHANGE_TYPE, i as addDocumentCacheEventHandler, p as DocumentCache, x as queueOperations } from \"./document-by-id-B4FIzG1w.js\";\nimport { C as addResetSelectedNodeEventHandler, D as addDrivesEventHandler, G as UnsupportedDocumentTypeError, H as DocumentModelNotFoundError, K as ambientRenownTokenProvider, T as addSetSelectedNodeOnPopStateEventHandler, _ as addSetSelectedDriveOnPopStateEventHandler, g as addSelectedDriveIdEventHandler, i as setVetraPackageManager, q as makeAuthMiddleware, r as addVetraPackageManagerEventHandler, w as addSelectedNodeIdEventHandler, x as useSelectedDriveId } from \"./document-model-modules-bTP87nyr.js\";\nimport { t as makePHEventFunctions } from \"./make-ph-event-functions-DBq3iWYn.js\";\nimport { a as PhDocumentFieldsFragmentDoc, n as DocumentChangeType, o as PropagationMode, r as DocumentChangesDocument, t as createClient$1 } from \"./client-D66jVnot.js\";\nimport { f as addLoadingEventHandler, t as addRenownEventHandler } from \"./renown-BHxwP7xU.js\";\nimport { logger } from \"document-model\";\nimport { UnsupportedDocumentModelVersionError, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, createPresignedHeader, createZip, deserializeSignature, documentModelDocumentType, generateId, hashDocumentStateForScope, normalizeDocumentModelVersion, replayDocumentVersioned, setName, setPreferredEditor, toTransportAction } from \"@powerhousedao/shared/document-model\";\nimport { addFolder, copyNode, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from \"@powerhousedao/shared/document-drive\";\nimport { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from \"remeda\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { GraphQLClient } from \"graphql-request\";\nimport { gql } from \"graphql-tag\";\nimport { Kind, print } from \"graphql\";\nimport { createClient } from \"graphql-ws/client\";\nimport { Fragment, jsx } from \"react/jsx-runtime\";\n//#region src/hooks/modals.ts\nconst modalEventFunctions = makePHEventFunctions(\"modal\");\n/** Returns the current modal */\nconst usePHModal = modalEventFunctions.useValue;\n/** Sets the current modal */\nconst setPHModal = modalEventFunctions.setValue;\n/** Adds an event handler for the modal */\nconst addModalEventHandler = modalEventFunctions.addEventHandler;\n/** Shows a modal */\nfunction showPHModal(modal) {\n\tsetPHModal(modal);\n}\n/** Closes the current modal */\nfunction closePHModal() {\n\tsetPHModal(void 0);\n}\n/** Shows the create document modal */\nfunction showCreateDocumentModal(documentType, documentModelVersion) {\n\tsetPHModal({\n\t\ttype: \"createDocument\",\n\t\tdocumentType,\n\t\t...documentModelVersion !== void 0 && { documentModelVersion }\n\t});\n}\n/** Shows the delete node modal */\nfunction showDeleteNodeModal(nodeOrId) {\n\tsetPHModal({\n\t\ttype: \"deleteItem\",\n\t\tid: typeof nodeOrId === \"string\" ? nodeOrId : nodeOrId.id\n\t});\n}\n//#endregion\n//#region src/utils/documents.ts\nfunction isDocumentTypeSupported(documentType, supportedDocuments) {\n\tif (!supportedDocuments?.length) return true;\n\treturn supportedDocuments.some((pattern) => {\n\t\tif (pattern.endsWith(\"/*\")) {\n\t\t\tconst prefix = pattern.slice(0, -2);\n\t\t\treturn documentType.startsWith(prefix + \"/\");\n\t\t}\n\t\tif (pattern.endsWith(\"*\") && !pattern.endsWith(\"/*\")) {\n\t\t\tconst prefix = pattern.slice(0, -1);\n\t\t\treturn documentType.startsWith(prefix);\n\t\t}\n\t\treturn pattern === documentType;\n\t});\n}\n//#endregion\n//#region src/utils/user.ts\nfunction getUserPermissions() {\n\tconst user = window.ph?.renown?.user;\n\tconst allowList = window.ph?.allowList;\n\tif (!allowList) return {\n\t\tisAllowedToCreateDocuments: true,\n\t\tisAllowedToEditDocuments: true\n\t};\n\treturn {\n\t\tisAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n\t\tisAllowedToEditDocuments: allowList.includes(user?.address ?? \"\")\n\t};\n}\n//#endregion\n//#region src/actions/document.ts\nconst NON_DOMAIN_SCOPES = new Set([\"auth\", \"document\"]);\n/** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */\nasync function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {\n\tconst drive = await reactorClient.get(driveId);\n\tconst nodeById = drive.state.global.nodes.find((node) => node.id === document.header.id);\n\tif (nodeById && nodeById.parentFolder === (parentFolder ?? null)) return {\n\t\tisDuplicate: true,\n\t\tduplicateType: \"id\",\n\t\tnodeId: nodeById.id\n\t};\n\tconst nodeByNameAndType = drive.state.global.nodes.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType && node.parentFolder === (parentFolder ?? null));\n\tif (nodeByNameAndType) return {\n\t\tisDuplicate: true,\n\t\tduplicateType: \"name\",\n\t\tnodeId: nodeByNameAndType.id\n\t};\n\treturn { isDuplicate: false };\n}\nfunction getDocumentTypeIcon(document) {\n\tswitch (document.header.documentType) {\n\t\tcase \"powerhouse/document-model\": return \"document-model\";\n\t\tcase \"powerhouse/app\": return \"app\";\n\t\tcase \"powerhouse/document-editor\": return \"editor\";\n\t\tcase \"powerhouse/subgraph\": return \"subgraph\";\n\t\tcase \"powerhouse/package\": return \"package\";\n\t\tcase \"powerhouse/processor\": {\n\t\t\tconst processorType = document.state.global?.type;\n\t\t\tif (processorType === \"analytics\") return \"analytics-processor\";\n\t\t\tif (processorType === \"relational\") return \"relational-processor\";\n\t\t\tif (processorType === \"codegen\") return \"codegen-processor\";\n\t\t\treturn;\n\t\t}\n\t\tdefault: return;\n\t}\n}\nasync function downloadFile(document, fileName) {\n\ttry {\n\t\tconst data = await createZip(document);\n\t\tconst blob = new Blob([new Uint8Array(data)], { type: \"application/zip\" });\n\t\tconst link = window.document.createElement(\"a\");\n\t\tlink.style.display = \"none\";\n\t\tlink.href = URL.createObjectURL(blob);\n\t\tlink.download = fileName;\n\t\twindow.document.body.appendChild(link);\n\t\tlink.click();\n\t\twindow.document.body.removeChild(link);\n\t} catch (e) {\n\t\tlogger.error(e instanceof Error ? e.message : String(e));\n\t}\n}\nasync function getDocumentExtension(document) {\n\tconst documentType = document.header.documentType;\n\tlet rawExtension;\n\tif (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;\n\telse {\n\t\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\t\tif (reactorClient) {\n\t\t\tconst { results: documentModelModules } = await reactorClient.getDocumentModelModules();\n\t\t\trawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;\n\t\t}\n\t}\n\treturn (rawExtension ?? \"\").replace(/^\\.+|\\.+$/g, \"\");\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*/\nasync function fetchDocumentOperations(reactorClient, document, pageSize = 100) {\n\tconst scopes = Object.keys(document.state);\n\tconst operations = {};\n\tfor (const scope of scopes) operations[scope] = [];\n\tlet cursor = \"\";\n\tdo {\n\t\tconst page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {\n\t\t\tcursor,\n\t\t\tlimit: pageSize\n\t\t});\n\t\tfor (const op of page.results) {\n\t\t\tconst scope = op.action.scope ?? \"global\";\n\t\t\tif (operations[scope]) operations[scope].push(op);\n\t\t}\n\t\tcursor = page.nextCursor ?? \"\";\n\t} while (cursor);\n\treturn operations;\n}\nfunction extractInitialState(documentScopeOps) {\n\tconst upgradeOp = documentScopeOps.find((op) => op.action.type === \"UPGRADE_DOCUMENT\");\n\tif (!upgradeOp) throw new Error(\"No UPGRADE_DOCUMENT operation found — document is invalid\");\n\tconst input = upgradeOp.action.input;\n\tconst initialState = input.initialState ?? input.state;\n\tif (!initialState) throw new Error(\"UPGRADE_DOCUMENT operation has no initialState — document is invalid\");\n\treturn initialState;\n}\nfunction filterDomainOperations(operations) {\n\treturn Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));\n}\nfunction countOperations(operations) {\n\tlet total = 0;\n\tfor (const ops of Object.values(operations)) total += ops?.length ?? 0;\n\treturn total;\n}\n/**\n* Split an imported document's domain operations at its mid-history upgrade\n* boundaries, so the caller can re-dispatch each upgrade between segments.\n*\n* The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation\n* path and must not be repeated. A later upgrade must be: it is where the\n* reducer version changes, and dropping it replays everything after it through\n* the module the document was created with.\n*/\nfunction splitAtUpgradeBoundaries(operations) {\n\tconst upgrades = (operations.document ?? []).filter((op) => op.action.type === \"UPGRADE_DOCUMENT\").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);\n\tconst domain = filterDomainOperations(operations);\n\tif (upgrades.length === 0) return [{ operations: domain }];\n\tconst segments = [];\n\tconst consumed = /* @__PURE__ */ new Map();\n\tconst take = (until) => {\n\t\tconst slice = {};\n\t\tfor (const [scope, ops] of Object.entries(domain)) {\n\t\t\tif (!ops) continue;\n\t\t\tconst from = consumed.get(scope) ?? 0;\n\t\t\tconst stop = Math.max(from, until(scope, ops));\n\t\t\tconst chunk = ops.slice(from, stop);\n\t\t\tif (chunk.length > 0) slice[scope] = chunk;\n\t\t\tconsumed.set(scope, stop);\n\t\t}\n\t\treturn slice;\n\t};\n\tfor (const upgrade of upgrades) {\n\t\tconst input = upgrade.action.input;\n\t\tconst slice = take((scope, ops) => boundary(upgrade, scope, ops));\n\t\tsegments.push({\n\t\t\toperations: slice,\n\t\t\tupgradeTo: input.toVersion\n\t\t});\n\t}\n\tconst tail = take((_scope, ops) => ops.length);\n\tif (countOperations(tail) > 0) segments.push({ operations: tail });\n\treturn segments;\n}\n/**\n* How many of a scope's operations precede an upgrade. Must stay identical to\n* the boundary computation in `replayDocumentVersioned` — snapshots compare\n* against operation indices, not array positions, and the timestamp fallback\n* excludes the upgrade's own instant.\n*/\nfunction boundary(upgrade, scope, ops) {\n\tconst snapshot = upgrade.action.input.revision;\n\tif (snapshot !== void 0) {\n\t\tconst revision = snapshot[scope] ?? 0;\n\t\tlet count = 0;\n\t\tfor (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;\n\t\treturn count;\n\t}\n\tfor (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;\n\treturn ops.length;\n}\nasync function exportFile(document, suggestedName) {\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst operations = await fetchDocumentOperations(reactorClient, document);\n\tconst initialState = extractInitialState(operations[\"document\"] ?? []);\n\tconst documentWithOps = {\n\t\t...document,\n\t\toperations,\n\t\tinitialState\n\t};\n\tconst extension = await getDocumentExtension(documentWithOps);\n\tconst baseName = suggestedName || documentWithOps.header.name || \"Untitled\";\n\tconst name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;\n\tif (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);\n\ttry {\n\t\tconst fileHandle = await window.showSaveFilePicker({ suggestedName: name });\n\t\tawait baseSaveToFileHandle(documentWithOps, fileHandle);\n\t\treturn fileHandle;\n\t} catch (e) {\n\t\tif (!(e instanceof DOMException && e.name === \"AbortError\")) throw e;\n\t}\n}\n/**\n* Loads a document file and replays it with version-aware reducers from the registry.\n* Falls back to single-version legacy replay when no upgrade manifest is registered for\n* the document type.\n*/\nasync function loadFile(path) {\n\tconst baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst documentType = baseDocument.header.documentType;\n\tconst { results: documentModelModules } = await reactorClient.getDocumentModelModules();\n\tconst modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);\n\tif (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);\n\tconst reducers = {};\n\tfor (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tlet upgradeManifest;\n\tif (registry) try {\n\t\tupgradeManifest = registry.getUpgradeManifest(documentType);\n\t} catch {}\n\treturn baseLoadFromInputVersioned(path, {\n\t\treducers,\n\t\tupgradeManifest\n\t});\n}\nasync function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create documents\");\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tlet documentModelModule;\n\tif (documentModelVersion !== void 0) {\n\t\tconst { results: documentModelModules } = await reactorClient.getDocumentModelModules();\n\t\tconst module = documentModelModules.find((m) => m.documentModel.global.id === documentType && (m.version ?? 1) === documentModelVersion);\n\t\tif (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);\n\t\tdocumentModelModule = module;\n\t} else documentModelModule = await reactorClient.getDocumentModelModule(documentType);\n\tconst newDocument = document ?? documentModelModule.utils.createDocument();\n\tif (!document) newDocument.state.document.version = documentModelModule.version ?? 1;\n\tnewDocument.header.name = name;\n\tif (preferredEditor) newDocument.header.meta = {\n\t\t...newDocument.header.meta,\n\t\tpreferredEditor\n\t};\n\tlet newDoc;\n\ttry {\n\t\tnewDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);\n\t} catch (e) {\n\t\tlogger.error(\"Error adding document: @error\", e);\n\t\tthrow new Error(\"There was an error adding document\", { cause: e });\n\t}\n\treturn {\n\t\tid: newDoc.header.id,\n\t\tname: newDoc.header.name,\n\t\tdocumentType,\n\t\tparentFolder: parentFolder ?? null,\n\t\tkind: \"file\"\n\t};\n}\n/**\n* How many ids an import will try before giving up. The check before the create\n* catches an id that is already taken; this bound covers the window between the\n* two, where a create can still lose to a claim made in the meantime.\n*/\nconst IMPORT_ID_ATTEMPTS = 3;\n/** True when this error, or anything it wraps, is a taken document id. */\nfunction isDocumentAlreadyExists(error) {\n\tlet current = error;\n\twhile (current instanceof Error) {\n\t\tif (current.name === \"DocumentAlreadyExistsError\") return true;\n\t\tcurrent = current.cause;\n\t}\n\treturn false;\n}\n/**\n* Creates the imported document under an id that is free, retrying on a\n* collision.\n*\n* The check cannot stand on its own: it answers for the moment it ran, and the\n* create that follows can still land on an id claimed in between. The store\n* rejects that create as DocumentAlreadyExistsError, which is not retryable\n* under the same id and is resolved by minting another one. A create that\n* fails leaves the drive untouched, so a retry has nothing to clean up.\n*/\nasync function createImportedDocument(reactor, document, driveId, name, parentFolder) {\n\tlet documentId = await reactor.isDocumentIdTaken(document.header.id) ? generateId() : document.header.id;\n\tfor (let attempt = 1;; attempt++) {\n\t\tconst header = createPresignedHeader(documentId, document.header.documentType);\n\t\theader.lastModifiedAtUtcIso = document.header.createdAtUtcIso;\n\t\theader.meta = document.header.meta;\n\t\theader.name = name || document.header.name;\n\t\tconst initialDocument = {\n\t\t\t...document,\n\t\t\theader,\n\t\t\tstate: document.initialState,\n\t\t\toperations: Object.keys(document.operations).reduce((acc, key) => {\n\t\t\t\tacc[key] = [];\n\t\t\t\treturn acc;\n\t\t\t}, {})\n\t\t};\n\t\ttry {\n\t\t\tconst fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);\n\t\t\tif (!fileNode) throw new Error(\"There was an error adding file\");\n\t\t\treturn {\n\t\t\t\tdocumentId,\n\t\t\t\tfileNode\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;\n\t\t\tlogger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);\n\t\t\tdocumentId = generateId();\n\t\t}\n\t}\n}\nasync function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {\n\tlogger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);\n\tconst reactor = window.ph?.reactorClientModule?.client;\n\tif (!reactor) {\n\t\tonProgress?.({\n\t\t\tstage: \"failed\",\n\t\t\tprogress: 100,\n\t\t\terror: \"ReactorClient not initialized\"\n\t\t});\n\t\tthrow new Error(\"ReactorClient not initialized\");\n\t}\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create files\");\n\ttry {\n\t\tonProgress?.({\n\t\t\tstage: \"loading\",\n\t\t\tprogress: 0\n\t\t});\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await loadFile(file);\n\t\t} catch (loadError) {\n\t\t\tif (UnsupportedDocumentModelVersionError.isError(loadError)) {\n\t\t\t\tshowPHModal({\n\t\t\t\t\ttype: \"documentVersionUnsupported\",\n\t\t\t\t\tdocumentType: loadError.documentType,\n\t\t\t\t\trequiredVersion: loadError.requiredVersion,\n\t\t\t\t\tavailableVersions: loadError.availableVersions\n\t\t\t\t});\n\t\t\t\tonProgress?.({\n\t\t\t\t\tstage: \"failed\",\n\t\t\t\t\tprogress: 100,\n\t\t\t\t\terror: loadError.message\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst discoveryService = window.ph?.packageDiscoveryService;\n\t\t\tif (discoveryService && DocumentModelNotFoundError.isError(loadError)) {\n\t\t\t\tretryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {\n\t\t\t\t\tlogger.error(\"Import retry after discovery failed: @error\", retryError);\n\t\t\t\t\tonProgress?.({\n\t\t\t\t\t\tstage: \"failed\",\n\t\t\t\t\t\tprogress: 100,\n\t\t\t\t\t\terror: retryError instanceof Error ? retryError.message : String(retryError)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow loadError;\n\t\t}\n\t\tconst duplicateCheck = await isDocumentInLocation(reactor, document, driveId, parentFolder);\n\t\tif (duplicateCheck.isDuplicate && !resolveConflict) {\n\t\t\tonProgress?.({\n\t\t\t\tstage: \"conflict\",\n\t\t\t\tprogress: 0,\n\t\t\t\tduplicateType: duplicateCheck.duplicateType\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst documentType = getDocumentTypeIcon(document);\n\t\tif (documentType) onProgress?.({\n\t\t\tstage: \"loading\",\n\t\t\tprogress: 10,\n\t\t\tdocumentType\n\t\t});\n\t\telse onProgress?.({\n\t\t\tstage: \"loading\",\n\t\t\tprogress: 10\n\t\t});\n\t\tif (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {\n\t\t\tonProgress?.({\n\t\t\t\tstage: \"unsupported-document-type\",\n\t\t\t\tprogress: 100,\n\t\t\t\terror: `Document type ${document.header.documentType} is not supported`\n\t\t\t});\n\t\t\tthrow new UnsupportedDocumentTypeError(document.header.documentType);\n\t\t}\n\t\tawait reactor.getDocumentModelModule(document.header.documentType);\n\t\tonProgress?.({\n\t\t\tstage: \"initializing\",\n\t\t\tprogress: 10\n\t\t});\n\t\tconst created = await createImportedDocument(reactor, document, driveId, name, parentFolder);\n\t\tconst documentId = created.documentId;\n\t\tconst fileNode = created.fileNode;\n\t\tonProgress?.({\n\t\t\tstage: \"initializing\",\n\t\t\tprogress: 20\n\t\t});\n\t\tawait reactor.get(documentId);\n\t\tconsole.log(\"Document created, starting upload of operations\");\n\t\tconst segments = splitAtUpgradeBoundaries(document.operations);\n\t\tconst totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);\n\t\tlet uploadedBefore = 0;\n\t\tfor (const segment of segments) {\n\t\t\tawait uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {\n\t\t\t\tif (uploadProgress.uploadedOperations === void 0) return;\n\t\t\t\tconst uploaded = uploadedBefore + uploadProgress.uploadedOperations;\n\t\t\t\tconst uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;\n\t\t\t\tonProgress?.({\n\t\t\t\t\tstage: \"uploading\",\n\t\t\t\t\tprogress: 20 + Math.round(uploadPercent * 80),\n\t\t\t\t\ttotalOperations,\n\t\t\t\t\tuploadedOperations: uploaded\n\t\t\t\t});\n\t\t\t} });\n\t\t\tuploadedBefore += countOperations(segment.operations);\n\t\t\tif (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);\n\t\t}\n\t\tonProgress?.({\n\t\t\tstage: \"complete\",\n\t\t\tprogress: 100,\n\t\t\tfileNode\n\t\t});\n\t\treturn fileNode;\n\t} catch (error) {\n\t\tif (!UnsupportedDocumentTypeError.isError(error)) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tonProgress?.({\n\t\t\t\tstage: \"failed\",\n\t\t\t\tprogress: 100,\n\t\t\t\terror: errorMessage\n\t\t\t});\n\t\t}\n\t\tthrow error;\n\t}\n}\nasync function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {\n\tif (!discoveryService) return;\n\ttry {\n\t\tawait discoveryService.load(documentType);\n\t} catch {\n\t\tonProgress?.({\n\t\t\tstage: \"unsupported-document-type\",\n\t\t\tprogress: 100,\n\t\t\terror: `Document type ${documentType} is not supported`\n\t\t});\n\t\treturn;\n\t}\n\tawait addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);\n}\nasync function addFolder$1(driveId, name, parentFolder) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create folders\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tawait reactorClient.get(driveId);\n\tconst folderId = generateId();\n\tconst node = (await reactorClient.execute(driveId, \"main\", [addFolder({\n\t\tid: folderId,\n\t\tname,\n\t\tparentFolder\n\t})])).state.global.nodes.find((node) => node.id === folderId);\n\tif (!node || !isFolderNode(node)) throw new Error(\"There was an error adding folder\");\n\treturn node;\n}\nasync function deleteNode(driveId, nodeId) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to delete documents\");\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tawait reactorClient.drives.removeNode(driveId, nodeId);\n}\nasync function renameNode(driveId, nodeId, name) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to rename documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tif ((await reactorClient.execute(nodeId, \"main\", [setName({ name })])).header.name !== name) throw new Error(\"There was an error renaming the node\");\n\tconst node = (await reactorClient.execute(driveId, \"main\", [updateNode({\n\t\tid: nodeId,\n\t\tname\n\t})])).state.global.nodes.find((n) => n.id === nodeId);\n\tif (!node) throw new Error(\"There was an error renaming node in the drive\");\n\treturn node;\n}\nasync function renameDriveNode(driveId, nodeId, name) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to rename documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tif ((await reactorClient.execute(nodeId, \"main\", [setName({ name })])).header.name !== name) throw new Error(\"There was an error renaming the node\");\n\tawait reactorClient.execute(driveId, \"main\", [updateNode({\n\t\tid: nodeId,\n\t\tname\n\t})]);\n\treturn (await reactorClient.get(driveId)).state.global.nodes.find((n) => n.id === nodeId);\n}\nasync function setPreferredEditorOnNode(nodeId, preferredEditor) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to modify documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn reactorClient.execute(nodeId, \"main\", [setPreferredEditor(preferredEditor)]);\n}\nasync function moveNodeById(args) {\n\tconst { driveId, srcId, targetId } = args;\n\tif (!driveId || !srcId) return;\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to move documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));\n\tif (isStrictEqual(targetParentFolder, srcId)) return;\n\treturn await reactorClient.execute(driveId, \"main\", [moveNode({\n\t\tsrcFolder: srcId,\n\t\ttargetParentFolder\n\t})]);\n}\nasync function moveNode$1(driveId, src, target) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to move documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(driveId, \"main\", [moveNode({\n\t\tsrcFolder: src.id,\n\t\ttargetParentFolder: target?.id\n\t})]);\n}\n/**\n* Duplicates a document under a new id using version-aware replay.\n* Falls back gracefully when no upgrade manifest is registered for the document type.\n*/\nasync function _duplicateDocument(reactor, document, newId = generateId()) {\n\tconst documentType = document.header.documentType;\n\tconst { results: allModules } = await reactor.getDocumentModelModules();\n\tconst modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);\n\tconst reducers = {};\n\tfor (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;\n\tif (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);\n\tconst registry = window.ph?.reactorClientModule?.reactorModule?.documentModelRegistry;\n\tlet upgradeManifest;\n\tif (registry) try {\n\t\tupgradeManifest = registry.getUpgradeManifest(documentType);\n\t} catch {}\n\tconst config = {\n\t\treducers,\n\t\tupgradeManifest\n\t};\n\tconst header = createPresignedHeader(newId, documentType);\n\tconst duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);\n\tassertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);\n\treturn duplicated;\n}\nasync function copyNode$1(driveId, src, target) {\n\tconst reactor = window.ph?.reactorClientModule?.client;\n\tif (!reactor) return;\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to copy documents\");\n\tconst drive = await reactor.get(driveId);\n\tconst copyNodesInput = generateNodesCopy({\n\t\tsrcId: src.id,\n\t\ttargetParentFolder: target?.id,\n\t\ttargetName: src.name\n\t}, () => generateId(), drive.state.global.nodes);\n\tconst resolvedNamesMap = /* @__PURE__ */ new Map();\n\tfor (const copyNodeInput of copyNodesInput) {\n\t\tconst node = drive.state.global.nodes.find((n) => n.id === copyNodeInput.srcId);\n\t\tif (node) {\n\t\t\tconst resolvedName = handleTargetNameCollisions({\n\t\t\t\tnodes: drive.state.global.nodes,\n\t\t\t\tsrcName: copyNodeInput.targetName || node.name,\n\t\t\t\tsrcKind: isFileNode(node) ? \"file\" : \"folder\",\n\t\t\t\ttargetParentFolder: copyNodeInput.targetParentFolder || null\n\t\t\t});\n\t\t\tresolvedNamesMap.set(copyNodeInput.targetId, resolvedName);\n\t\t}\n\t}\n\tconst fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {\n\t\tconst node = drive.state.global.nodes.find((node) => node.id === copyNodeInput.srcId);\n\t\treturn node !== void 0 && isFileNode(node);\n\t});\n\tfor (const fileNodeToCopy of fileNodesToCopy) try {\n\t\tconst duplicatedDocument = await _duplicateDocument(reactor, await reactor.get(fileNodeToCopy.srcId), fileNodeToCopy.targetId);\n\t\tconst resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);\n\t\tif (resolvedName) duplicatedDocument.header.name = resolvedName;\n\t\tawait reactor.drives.addFile(driveId, duplicatedDocument, target?.id);\n\t} catch (e) {\n\t\tlogger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);\n\t}\n\treturn await queueActions(drive, copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput)));\n}\n/**\n* Upgrades a document to a newer document model version. Defaults to the\n* latest registered version for the document's type.\n*/\nasync function upgradeDocument(documentId, toVersion) {\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn reactorClient.upgradeDocument(documentId, toVersion);\n}\n//#endregion\n//#region src/remote-controller/utils.ts\n/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. \"SET_MODEL_NAME\" → \"setModelName\"). */\nfunction screamingSnakeToCamel(s) {\n\treturn s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());\n}\n/** Error thrown when a push conflict is detected with the \"reject\" strategy. */\nvar ConflictError = class extends Error {\n\tconstructor(conflict) {\n\t\tsuper(\"Push conflict: remote has new operations since last pull\");\n\t\tthis.conflict = conflict;\n\t\tthis.name = \"ConflictError\";\n\t}\n};\n/** Convert a remote operation to the local Operation type. */\nfunction remoteOperationToLocal(remote) {\n\treturn {\n\t\tid: remote.id ?? \"\",\n\t\tindex: remote.index,\n\t\tskip: remote.skip,\n\t\ttimestampUtcMs: remote.timestampUtcMs,\n\t\thash: remote.hash,\n\t\terror: remote.error ?? void 0,\n\t\tdeniedReason: remote.deniedReason ?? void 0,\n\t\taction: {\n\t\t\tid: remote.action.id,\n\t\t\ttype: remote.action.type,\n\t\t\ttimestampUtcMs: remote.action.timestampUtcMs,\n\t\t\tinput: remote.action.input,\n\t\t\tscope: remote.action.scope,\n\t\t\tcontext: remote.action.context?.signer ? { signer: {\n\t\t\t\tuser: remote.action.context.signer.user ?? {\n\t\t\t\t\taddress: \"\",\n\t\t\t\t\tnetworkId: \"\",\n\t\t\t\t\tchainId: 0\n\t\t\t\t},\n\t\t\t\tapp: remote.action.context.signer.app ?? {\n\t\t\t\t\tname: \"\",\n\t\t\t\t\tkey: \"\"\n\t\t\t\t},\n\t\t\t\tsignatures: remote.action.context.signer.signatures.map((s) => deserializeSignature(s))\n\t\t\t} } : void 0\n\t\t}\n\t};\n}\n/** Convert remote operations to local DocumentOperations format. */\nfunction convertRemoteOperations(operationsByScope) {\n\tconst operations = {};\n\tfor (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));\n\treturn operations;\n}\n/** Reconstruct a PHDocument from remote document data and operations. */\nfunction buildPulledDocument(remoteDoc, operations, initialDoc, branch) {\n\treturn {\n\t\theader: {\n\t\t\t...initialDoc.header,\n\t\t\tid: remoteDoc.id,\n\t\t\tname: remoteDoc.name,\n\t\t\tslug: remoteDoc.slug ?? \"\",\n\t\t\tdocumentType: remoteDoc.documentType,\n\t\t\tcreatedAtUtcIso: typeof remoteDoc.createdAtUtcIso === \"string\" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),\n\t\t\tlastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === \"string\" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),\n\t\t\trevision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),\n\t\t\tbranch\n\t\t},\n\t\tstate: remoteDoc.state,\n\t\tinitialState: initialDoc.initialState,\n\t\toperations,\n\t\tclipboard: []\n\t};\n}\n/** Extract revision map from a remote document's revisionsList. */\nfunction extractRevisionMap(revisionsList) {\n\treturn Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n/**\n* Check if any scope in currentRevision is ahead of knownRevision.\n* When `scopes` is provided, only those scopes are checked.\n*/\nfunction hasRevisionConflict(currentRevision, knownRevision, scopes) {\n\tfor (const scope in currentRevision) {\n\t\tif (scopes && !scopes.has(scope)) continue;\n\t\tif ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) return true;\n\t}\n\treturn false;\n}\n//#endregion\n//#region src/graphql-client/adapter.ts\n/**\n* Converts a `GetDocument` result into a `PHDocument`.\n*\n* Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope\n* revision map, which the write path needs to compute the `prevOpIndex` of a\n* signed action. `sig` is filled with the empty shape used by\n* `createPresignedHeader`: the creation signature is not fetchable over\n* GraphQL and is not part of the operation signing payload.\n*\n* The read path never fetches operation history, so `operations` is a map of\n* the document's known scopes to empty arrays.\n*\n* `branch` is the branch the document was read from. The GraphQL type does not\n* carry it, so it has to be passed back in by the caller; it defaults to the\n* server's own default branch.\n*/\nfunction phDocumentFromGetDocument(document, branch) {\n\tconst state = document.state;\n\treturn {\n\t\theader: phDocumentHeaderFromGetDocument(document, branch),\n\t\tstate,\n\t\tinitialState: state,\n\t\toperations: emptyOperationsForScopes(document.revisionsList),\n\t\tclipboard: []\n\t};\n}\n/**\n* Converts a mutation result into a `PHDocument`, carrying the operations the\n* mutation produced.\n*\n* `dispatchActions` reads per-action failures out of `operations[scope]`, so\n* unlike the read path this one must not return empty operation lists.\n*/\nfunction phDocumentFromMutation(document, operations, branch) {\n\tconst phDocument = phDocumentFromGetDocument(document, branch);\n\tconst operationsByScope = { ...phDocument.operations };\n\tfor (const remote of operations) {\n\t\tconst operation = remoteOperationToLocal(remote);\n\t\tconst scope = operation.action.scope;\n\t\tconst scopeOperations = operationsByScope[scope] ?? [];\n\t\tscopeOperations.push(operation);\n\t\toperationsByScope[scope] = scopeOperations;\n\t}\n\tphDocument.operations = operationsByScope;\n\treturn phDocument;\n}\n/** Turns a `revisionsList` selection into the header's per-scope revision map. */\nfunction revisionMapFromRevisionsList(revisionsList) {\n\treturn Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));\n}\n/** The branch the server reads and writes when none is asked for. */\nconst defaultBranch = \"main\";\nfunction phDocumentHeaderFromGetDocument(document, branch) {\n\treturn {\n\t\tid: document.id,\n\t\tsig: {\n\t\t\tpublicKey: {},\n\t\t\tnonce: \"\"\n\t\t},\n\t\tdocumentType: document.documentType,\n\t\tcreatedAtUtcIso: isoStringFromDateTime(document.createdAtUtcIso),\n\t\tslug: document.slug ?? \"\",\n\t\tname: document.name,\n\t\tbranch: branch ?? defaultBranch,\n\t\trevision: revisionMapFromRevisionsList(document.revisionsList),\n\t\tlastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso)\n\t};\n}\nfunction emptyOperationsForScopes(revisionsList) {\n\treturn Object.fromEntries(revisionsList.map((r) => [r.scope, []]));\n}\n/** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */\nfunction isoStringFromDateTime(value) {\n\treturn value instanceof Date ? value.toISOString() : value;\n}\n//#endregion\n//#region src/graphql-client/operations.ts\n/**\n* The operation selection of `GetDocumentOperations`, lifted into a fragment so\n* the write path can reuse `remoteOperationToLocal` on the items it selects.\n*/\nconst ReactorOperationFieldsFragmentDoc = gql`\n fragment ReactorOperationFields on ReactorOperation {\n index\n timestampUtcMs\n hash\n skip\n error\n deniedReason\n id\n action {\n id\n type\n timestampUtcMs\n input\n scope\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`;\n/**\n* `mutateDocument` plus the operations the mutation produced.\n*\n* The generated `MutateDocument` only selects the document fields, but\n* `dispatchActions` reads per-action failures out of `result.operations[scope]`\n* (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.\n*\n* The operations filter keeps the extra selection to the operations this call\n* could have appended rather than the whole history. All three of its fields\n* matter:\n* - `sinceRevision` is the lowest head revision across the targeted scopes, so\n* it is only a safe window when the selection is scope-limited as well;\n* - `scopes` limits the response to the scopes the pushed actions target,\n* without it the server walks every scope of the document\n* (`packages/reactor/src/core/reactor.ts` `getOperations`);\n* - `branch` selects the branch the operations are read from, and is the same\n* variable the mutation writes to. It used to be two - the write went through\n* a `view`, the filter took its own `branch` - and they had to be kept equal\n* by hand or the operations came from `main` while the actions were applied\n* elsewhere. One variable cannot disagree with itself.\n*/\nconst MutateDocumentWithOperationsDocument = gql`\n mutation MutateDocumentWithOperations(\n $documentIdentifier: String!\n $actions: [ActionInput!]!\n $sinceRevision: Int\n $scopes: [String!]\n $branch: String\n ) {\n mutateDocument: execute(\n documentIdentifier: $documentIdentifier\n actions: $actions\n branch: $branch\n ) {\n ...PHDocumentFields\n operations(\n filter: {\n sinceRevision: $sinceRevision\n scopes: $scopes\n branch: $branch\n }\n ) {\n items {\n ...ReactorOperationFields\n }\n }\n }\n }\n ${PhDocumentFieldsFragmentDoc}\n ${ReactorOperationFieldsFragmentDoc}\n`;\n//#endregion\n//#region src/graphql-client/signing.ts\n/**\n* Stamps an action with the head of the scope it targets.\n*\n* `prevOpHash` is the hash of the scope state the action is meant to apply to;\n* for a document at head that is the hash of the last operation in the scope,\n* which the read path cannot fetch, so it is recomputed from the state.\n* `prevOpIndex` is the index of that last operation: revisions count\n* operations and indices are zero based, so an empty scope stamps `-1`, which\n* matches what the remote controller records.\n*\n* `revision` overrides the scope revision the index is derived from. Only a\n* batch needs it - {@link prepareSignedActions} stamps action N at the revision\n* the N actions before it will have produced, which the document itself does\n* not know yet. `prevOpHash` always comes from the supplied document's state.\n*/\nfunction stampAction(action, document, revision = document.header.revision[action.scope] ?? 0) {\n\treturn {\n\t\t...action,\n\t\tcontext: {\n\t\t\t...action.context,\n\t\t\tprevOpHash: hashDocumentStateForScope(document, action.scope),\n\t\t\tprevOpIndex: revision - 1\n\t\t}\n\t};\n}\n/**\n* Signs a stamped action, preserving any signatures it already carries.\n*\n* The signer reads `context.prevOpHash` off the action, so this must run after\n* {@link stampAction}.\n*/\nasync function signStampedAction(action, signer, signal) {\n\tconst actionSigner = action.context?.signer;\n\tconst user = actionSigner?.user ?? signer.user;\n\tconst app = actionSigner?.app ?? signer.app;\n\tif (!user || !app) throw new Error(\"cannot sign an action: the signer has no user or app identity\");\n\tconst signature = await signer.signAction(action, signal);\n\treturn {\n\t\t...action,\n\t\tcontext: {\n\t\t\t...action.context,\n\t\t\tsigner: {\n\t\t\t\tuser,\n\t\t\t\tapp,\n\t\t\t\tsignatures: [...actionSigner?.signatures ?? [], signature]\n\t\t\t}\n\t\t}\n\t};\n}\n/**\n* Actions a snapshot batch cannot predict the next state for.\n*\n* `UNDO`, `REDO` and `PRUNE` rewrite history the light read path never fetched\n* (and the reducer appends no operation for them); `NOOP` is only ever produced\n* by an undo chain; the document-scope actions run through the reactor's\n* document-action handler rather than a document-model reducer\n* (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and\n* `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.\n*/\nconst unsupportedBatchActions = new Set([\n\t\"UNDO\",\n\t\"REDO\",\n\t\"PRUNE\",\n\t\"NOOP\",\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\"\n]);\n/**\n* The base-reducer protocol version to predict with when the snapshot's header\n* carries none.\n*\n* `baseReducer` reads `baseReducerVersion(document.header)` for every action and\n* throws when the header has no `protocolVersions` - and a header built by\n* {@link phDocumentFromGetDocument} never has one, because the GraphQL\n* `PHDocument` type does not expose it. The version only selects between the v1\n* and v2 UNDO/NOOP branches, and every action reaching the prediction loop is an\n* ordinary append-only one, so it cannot change the predicted state here; it is\n* passed purely so the lookup does not throw.\n*/\nconst predictionProtocolVersion = 2;\n/**\n* Stamps and signs a batch of actions against one document snapshot, so every\n* action carries the head its predecessor will leave behind.\n*\n* The server executes the array in order, each action against the state the one\n* before it produced. The snapshot the light client reads has correct state and\n* per-scope revisions but NO operation history (see `adapter.ts`), so the chain\n* is predicted here: reduce action N over the working document to get the state\n* action N+1 hashes, and carry a virtual revision alongside it. The revision has\n* to be tracked separately because the reducer derives operation indices from\n* the last stored operation, and with an empty history that counts from zero\n* rather than from the document's real revision.\n*\n* A single action needs no prediction and therefore no `module`, which keeps\n* today's callers working unchanged. Two or more require the document's exact\n* reducer, one shared scope (the reactor rejects mixed-scope jobs) and only\n* append-only actions. Anything else rejects: a batch that cannot be predicted\n* must fail before the mutation, never be downgraded to unsigned.\n*/\nasync function prepareSignedActions(actions, snapshot, signer, module, signal) {\n\tif (actions.length === 0) return [];\n\tif (actions.length === 1) return [await signStampedAction(stampAction(actions[0], snapshot), signer, signal)];\n\tconst scope = sharedScope(actions);\n\tassertSupportedBatch(actions);\n\tif (!module) throw new Error(`cannot sign ${actions.length} actions: no document model module for ${snapshot.header.documentType} was supplied, so the batch state cannot be predicted`);\n\tlet working = {\n\t\t...snapshot,\n\t\toperations: {\n\t\t\t...snapshot.operations,\n\t\t\t[scope]: [...snapshot.operations[scope] ?? []]\n\t\t}\n\t};\n\tlet revision = snapshot.header.revision[scope] ?? 0;\n\tconst signed = [];\n\tfor (const [index, action] of actions.entries()) {\n\t\tthrowIfAborted(signal, index);\n\t\tconst signedAction = await signStampedAction(stampAction(action, working, revision), signer, signal);\n\t\tsigned.push(signedAction);\n\t\tconst before = scopeOperationCount(working, scope);\n\t\tlet next;\n\t\ttry {\n\t\t\tnext = module.reducer(working, signedAction, void 0, { protocolVersion: working.header.protocolVersions?.[\"base-reducer\"] ?? predictionProtocolVersion });\n\t\t} catch (error) {\n\t\t\tthrow new Error(`cannot sign action ${index} (${action.type}): the ${snapshot.header.documentType} reducer rejected it, so the rest of the batch cannot be predicted`, { cause: error });\n\t\t}\n\t\tconst after = scopeOperationCount(next, scope);\n\t\tif (after !== before + 1) throw new Error(`cannot sign action ${index} (${action.type}): the reducer appended ${after - before} operations to ${scope}, expected exactly 1`);\n\t\tworking = next;\n\t\trevision += 1;\n\t}\n\treturn signed;\n}\n/**\n* How many operations a scope holds.\n*\n* The index signature types the array as always present, but a module's reducer\n* is arbitrary code: one that hands back a document without the scope should\n* produce the actionable error above, not a `TypeError` on `.length`.\n*/\nfunction scopeOperationCount(document, scope) {\n\treturn document.operations[scope]?.length ?? 0;\n}\n/** The one scope a reactor job may span (`getSharedActionScope`). */\nfunction sharedScope(actions) {\n\tconst scope = actions[0].scope;\n\tconst mixed = actions.find((action) => action.scope !== scope);\n\tif (mixed) throw new Error(`cannot sign a batch spanning scopes \"${scope}\" and \"${mixed.scope}\": every action in one request must share a scope`);\n\treturn scope;\n}\nfunction assertSupportedBatch(actions) {\n\tconst unsupported = actions.find((action) => unsupportedBatchActions.has(action.type));\n\tif (unsupported) throw new Error(`cannot sign a batch containing ${unsupported.type}: it needs operation history or an alternate executor path, so send it as a single action`);\n}\nfunction throwIfAborted(signal, index) {\n\tif (signal?.aborted) throw new Error(`signing aborted before action ${index}`, { cause: signal.reason });\n}\n//#endregion\n//#region src/graphql-client/static-package-manager.ts\n/**\n* A fixed set of packages presented through the `IPackageManager` interface,\n* so the package-derived hooks - `useDocumentModelModules`,\n* `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work\n* below `GraphQLReactorProvider` exactly as they do below Connect.\n*\n* Connect's package manager installs, updates and removes packages at runtime.\n* A light app instead declares its packages once, as code it imports itself\n* (every generated package root exports `manifest`, `documentModels`, `editors`\n* and `upgradeManifests` by name), so every mutating member throws and\n* `subscribe` never emits. For hand-picked modules without package artifacts,\n* {@link packageFromDocumentModels} wraps them in one synthetic package.\n*/\nvar StaticPackageManager = class {\n\tregistryUrl = null;\n\tpackages;\n\tconstructor(packages) {\n\t\tthis.packages = [...packages];\n\t}\n\t/**\n\t* Resolves a module by document type across all packages. Mirrors the\n\t* registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST\n\t* version wins, with `version ?? 1` as each module's default.\n\t*/\n\tload(documentType) {\n\t\tconst modules = this.packages.flatMap((pkg) => pkg.documentModels);\n\t\ttry {\n\t\t\treturn Promise.resolve(resolveDocumentModelModule(modules, documentType));\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\tsubscribe(_handler) {\n\t\treturn () => {};\n\t}\n\tgetPackageSource(_packageName) {\n\t\treturn null;\n\t}\n\tgetPackageVersion(_packageName) {}\n\tgetPackageSpec(_packageName) {}\n\tgetRegistryPackages() {\n\t\treturn [];\n\t}\n\taddPackage(_packageName) {\n\t\tthrow staticPackageManagerError(\"addPackage\");\n\t}\n\taddPackages(_packageNames) {\n\t\tthrow staticPackageManagerError(\"addPackages\");\n\t}\n\tremovePackage(_name) {\n\t\tthrow staticPackageManagerError(\"removePackage\");\n\t}\n\tupdateLocalPackage(_pkg, _version) {\n\t\tthrow staticPackageManagerError(\"updateLocalPackage\");\n\t}\n\taddLocalPackage(_name, _loadedPackage, _version) {\n\t\tthrow staticPackageManagerError(\"addLocalPackage\");\n\t}\n};\n/**\n* Resolves one document-model module out of a flat module list, with the same\n* rule the reactor registry uses (`IDocumentModelRegistry.getModule`, at\n* packages/reactor/src/registry/implementation.ts): with a `version`, only an\n* EXACT `version ?? 1` match resolves; without one, the LATEST version wins.\n*\n* Signing an existing document needs the exact rule. A document carries the\n* model version it was written with in `state.document.version`, and its\n* reducer is the only one whose operations that document's history can accept -\n* so \"latest\" is correct only when no version is asked for.\n*\n* Pure and dependency-free on purpose: this is reachable from the browser\n* entry, so it must not pull the reactor registry in as a value.\n*/\nfunction resolveDocumentModelModule(modules, documentType, version) {\n\tlet latestModule;\n\tlet latestVersion = -1;\n\tfor (const module of modules) {\n\t\tif (module.documentModel.global.id !== documentType) continue;\n\t\tconst moduleVersion = module.version ?? 1;\n\t\tif (version !== void 0 && moduleVersion === version) return module;\n\t\tif (moduleVersion > latestVersion) {\n\t\t\tlatestVersion = moduleVersion;\n\t\t\tlatestModule = module;\n\t\t}\n\t}\n\tif (version === void 0 && latestModule) return latestModule;\n\tthrow new Error(version === void 0 ? `Unknown document type: ${documentType}` : `Unknown document model version: ${documentType} v${version}` + (latestModule ? ` (available: ${availableVersions(modules, documentType).join(\", \")})` : \" (no module for this document type)\"));\n}\nfunction availableVersions(modules, documentType) {\n\treturn modules.filter((module) => module.documentModel.global.id === documentType).map((module) => module.version ?? 1).sort((a, b) => a - b);\n}\nfunction staticPackageManagerError(member) {\n\treturn /* @__PURE__ */ new Error(`${member} is not supported: StaticPackageManager holds a fixed set of packages`);\n}\n/**\n* Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that\n* assemble their model list from mixed sources instead of passing whole\n* packages. The manifest is fabricated - loose modules carry none - so prefer\n* the `packages` prop with the real package exports when you have them: a real\n* package also carries `editors`, which makes the editor hooks work.\n*/\nfunction packageFromDocumentModels(documentModels) {\n\treturn {\n\t\tmanifest: {\n\t\t\tname: \"graphql-reactor-provider\",\n\t\t\tdescription: \"Document models passed to GraphQLReactorProvider\"\n\t\t},\n\t\tdocumentModels,\n\t\teditors: []\n\t};\n}\n//#endregion\n//#region src/graphql-client/subgraph.ts\n/** What {@link describeGraphQLDocument} could not read off a document. */\nconst unnamedOperation = \"AnonymousOperation\";\nconst defaultOperationType = \"query\";\n/**\n* Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.\n*\n* Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so\n* `http://localhost:4001/graphql` plus `statements` is\n* `http://localhost:4001/graphql/statements`.\n*/\nfunction subgraphUrlFromGraphqlUrl(url, name) {\n\tconst trimmed = name.trim();\n\tif (trimmed === \"\") throw new Error(\"a subgraph name is required\");\n\treturn `${url.replace(/\\/+$/, \"\")}/${trimmed}`;\n}\n/**\n* Reads the operation name and type off a document, for the middleware.\n*\n* Nothing depends on getting this right - it is reported to the middleware, not\n* sent to the server - so an unreadable document falls back to an anonymous\n* query rather than throwing.\n*/\nfunction describeGraphQLDocument(document) {\n\tif (typeof document !== \"string\") {\n\t\tconst operation = document.definitions.find((definition) => definition.kind === Kind.OPERATION_DEFINITION);\n\t\tif (!operation || operation.kind !== Kind.OPERATION_DEFINITION) return {\n\t\t\toperationName: unnamedOperation,\n\t\t\toperationType: defaultOperationType\n\t\t};\n\t\treturn {\n\t\t\toperationName: operation.name?.value ?? unnamedOperation,\n\t\t\toperationType: operation.operation\n\t\t};\n\t}\n\tconst match = /\\b(query|mutation|subscription)\\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document);\n\tif (!match) return {\n\t\toperationName: unnamedOperation,\n\t\toperationType: /\\bmutation\\b/.test(document) ? \"mutation\" : defaultOperationType\n\t};\n\treturn {\n\t\toperationName: match[2],\n\t\toperationType: match[1]\n\t};\n}\n/**\n* Binds typed subgraph SDKs to one Switchboard's transport and auth.\n*\n* Every capability a Switchboard exposes lives behind the same base URL, so an\n* app should not have to build a second client - with a second copy of the auth\n* configuration - to reach a project's own subgraph. The registry derives the\n* endpoint, reuses one transport per subgraph and hands the code generator's\n* `getSdk` the very middleware the reactor operations already go through.\n*\n* Transport and typing only: subgraph results are not cached and produce no\n* change events.\n*/\nvar SubgraphSdkRegistry = class {\n\turl;\n\tmiddleware;\n\tbindings = /* @__PURE__ */ new Map();\n\tconstructor(url, middleware) {\n\t\tthis.url = url;\n\t\tthis.middleware = middleware;\n\t}\n\t/**\n\t* Returns the subgraph's SDK, building it on first use.\n\t*\n\t* The transport is kept per subgraph name, so repeated calls do not rebuild\n\t* it. The SDK itself is only reused when the same factory is passed again -\n\t* two different generated SDKs over one subgraph each get their own, rather\n\t* than the second call being handed the first one's methods.\n\t*/\n\tget(name, getSdk) {\n\t\tconst binding = this.binding(name);\n\t\tif (binding.factory === getSdk) return binding.sdk;\n\t\tconst sdk = getSdk(binding.transport, this.middleware);\n\t\tbinding.factory = getSdk;\n\t\tbinding.sdk = sdk;\n\t\treturn sdk;\n\t}\n\t/** Returns the subgraph's endpoint, for diagnostics and tests. */\n\turlFor(name) {\n\t\treturn subgraphUrlFromGraphqlUrl(this.url, name);\n\t}\n\tbinding(name) {\n\t\tconst existing = this.bindings.get(name);\n\t\tif (existing) return existing;\n\t\tconst binding = { transport: new GraphQLClient(this.urlFor(name)) };\n\t\tthis.bindings.set(name, binding);\n\t\treturn binding;\n\t}\n};\n//#endregion\n//#region src/graphql-client/subscriptions.ts\n/**\n* The 4403 close reasons a Switchboard refuses a handshake with.\n*\n* Mirrors `WS_AUTH_CLOSE_REASONS` in `@powerhousedao/reactor-api`\n* (`src/graphql/gateway/types.ts`). This package does not depend on that one,\n* so the strings are duplicated and are a wire contract: change them on both\n* sides or not at all.\n*/\nconst authCloseReasons = [\"authentication-required\", \"bearer-rejected\"];\n/** graphql-ws's own `isLikeCloseEvent`, which it does not export. */\nfunction isLikeCloseEvent(value) {\n\treturn typeof value === \"object\" && value !== null && \"code\" in value && \"reason\" in value;\n}\n/**\n* Whether a socket failure is the Switchboard refusing the credentials sent.\n*\n* Keyed on the close reason, not the code: both refusals close 4403, because\n* `connectionParams` is resolved per connect and a reconnect carrying a fresh\n* token genuinely succeeds. What the reason adds is that *this* attempt cannot\n* be fixed by repeating it.\n*/\nfunction isAuthRefusalClose(error) {\n\treturn isLikeCloseEvent(error) && authCloseReasons.includes(error.reason);\n}\n/**\n* Opens one `documentChanges` subscription and feeds every event to `onEvent`.\n*\n* The subscription is a firehose: no `search` argument, so the server sends\n* every change the connection is allowed to see and the caller filters. This is\n* the only module that knows about `graphql-ws`.\n*\n* Returns the stop function, which cancels the subscription and closes the\n* socket. It is safe to call more than once.\n*/\nfunction startDocumentChangesSubscription(options) {\n\tconst client = createClient({\n\t\turl: options.wsUrl,\n\t\tconnectionParams: options.connectionParams,\n\t\tshouldRetry: (errOrCloseEvent) => isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent)\n\t});\n\tconst unsubscribe = client.subscribe({\n\t\toperationName: \"DocumentChanges\",\n\t\tquery: print(DocumentChangesDocument)\n\t}, {\n\t\tnext: (result) => {\n\t\t\tconst event = result.data?.documentChanges;\n\t\t\tif (event) options.onEvent(event);\n\t\t},\n\t\terror: (error) => options.onError(error),\n\t\tcomplete: () => void 0\n\t});\n\tlet stopped = false;\n\treturn () => {\n\t\tif (stopped) return;\n\t\tstopped = true;\n\t\tunsubscribe();\n\t\tclient.dispose();\n\t};\n}\n/**\n* Derives the websocket endpoint from the GraphQL http endpoint.\n*\n* `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is\n* where the Switchboard mounts its websocket server (`packages/reactor-api`\n* `startServer`). A URL that already speaks `ws`/`wss` only gets the path.\n*/\nfunction subscriptionsUrlFromGraphqlUrl(url) {\n\tconst trimmed = url.replace(/\\/+$/, \"\");\n\treturn `${trimmed.startsWith(\"https://\") ? `wss://${trimmed.slice(8)}` : trimmed.startsWith(\"http://\") ? `ws://${trimmed.slice(7)}` : trimmed}/subscriptions`;\n}\n/**\n* Turns a bearer token provider into `connectionParams`.\n*\n* The header key is the lowercase `authorization` the Switchboard's websocket\n* context factory reads. Without a token the payload is empty: an open\n* Switchboard serves anonymous subscribers.\n*/\nfunction makeAuthConnectionParams(tokenProvider) {\n\treturn async () => {\n\t\tconst token = await tokenProvider();\n\t\tif (!token) return {};\n\t\treturn { authorization: `Bearer ${token}` };\n\t};\n}\n//#endregion\n//#region src/graphql-client/graphql-reactor-client.ts\n/** Paging defaults, matching the reactor's own client. */\nconst defaultPaging = {\n\tcursor: \"0\",\n\tlimit: 100\n};\n/**\n* The marker {@link isGraphQLReactorClient} looks for.\n*\n* A page can end up with two copies of this module - an app that bundles a\n* package carrying its own copy, or a dev server that hot-replaced it - and\n* then `instanceof` compares an instance against the other copy's class object\n* and answers `false`. A branded property survives both.\n*/\nconst graphQLReactorClientBrand = \"__powerhouseGraphQLReactorClient\";\n/**\n* A light implementation of {@link IReactorBrowserClient} that talks plain\n* GraphQL to a Switchboard, with no reactor in the bundle.\n*\n* It fills the same `window.ph` slots the full in-browser reactor client fills,\n* so the reactor-browser hooks cannot tell the two apart.\n*/\nvar GraphQLReactorClient = class {\n\t/** See {@link isGraphQLReactorClient}. */\n\t[graphQLReactorClientBrand] = true;\n\tsdk;\n\tsubgraphs;\n\tlisteners = [];\n\ttokenProvider;\n\tsubscriptionsUrl;\n\tdocumentModels;\n\tsigner;\n\tstopRealtime;\n\trealtimeStarted = false;\n\trealtimeGeneration = 0;\n\trealtimeErrorLogged = false;\n\t/** Whether the last socket died because the Switchboard refused its credentials. */\n\trealtimeRefusedCredentials = false;\n\tconstructor(options) {\n\t\tthis.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;\n\t\tthis.documentModels = [...options.documentModels ?? []];\n\t\tthis.signer = options.signer;\n\t\tthis.subscriptionsUrl = options.realtime === false ? void 0 : options.subscriptionsUrl ?? subscriptionsUrlFromGraphqlUrl(options.url);\n\t\tconst middleware = makeAuthMiddleware(this.tokenProvider);\n\t\tthis.sdk = options.graphqlClient ?? createClient$1(options.url, middleware);\n\t\tthis.subgraphs = new SubgraphSdkRegistry(options.url, middleware);\n\t}\n\tasync get(identifier, view, signal) {\n\t\tconst viewInput = viewFilterInputFromViewFilter(view);\n\t\tconst document = (await this.sdk.GetDocument({\n\t\t\tidentifier,\n\t\t\tview: viewInput\n\t\t}, void 0, signal)).document;\n\t\tif (!document) throw new Error(`Document not found: ${identifier}`);\n\t\treturn phDocumentFromGetDocument(document.document, view?.branch);\n\t}\n\tasync getOperations(documentIdentifier, view, filter, paging, signal) {\n\t\tconst viewInput = viewFilterInputFromViewFilter(view);\n\t\tconst operationsFilter = {\n\t\t\tdocumentId: documentIdentifier,\n\t\t\tbranch: viewInput?.branch,\n\t\t\tscopes: viewInput?.scopes,\n\t\t\tactionTypes: filter?.actionTypes,\n\t\t\ttimestampFrom: filter?.timestampFrom,\n\t\t\ttimestampTo: filter?.timestampTo,\n\t\t\tsinceRevision: filter?.sinceRevision\n\t\t};\n\t\tconst page = (await this.sdk.GetDocumentOperations({\n\t\t\tfilter: operationsFilter,\n\t\t\tpaging: pagingInputFromPaging(paging)\n\t\t}, void 0, signal)).documentOperations;\n\t\tconst nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;\n\t\tconst effectivePaging = paging ?? defaultPaging;\n\t\treturn {\n\t\t\tresults: page.items.map((item) => remoteOperationToLocal(item)),\n\t\t\toptions: effectivePaging,\n\t\t\tnextCursor,\n\t\t\ttotalCount: page.totalCount,\n\t\t\tnext: nextCursor ? () => this.getOperations(documentIdentifier, view, filter, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit: effectivePaging.limit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync create(document, parentIdentifier, signal) {\n\t\tconst created = phDocumentFromGetDocument((await this.sdk.CreateDocument({\n\t\t\tdocument,\n\t\t\tparentIdentifier\n\t\t}, void 0, signal)).createDocument);\n\t\tthis.emitChange({\n\t\t\ttype: DOCUMENT_CHANGE_TYPE.Created,\n\t\t\tdocuments: [created]\n\t\t});\n\t\treturn created;\n\t}\n\t/**\n\t* Pushes actions to the Switchboard and returns the updated document.\n\t*\n\t* The document is fetched first: the response is the baseline for the\n\t* `sinceRevision` filter that narrows the returned operations to the ones\n\t* this call appended, and it carries the state hash a signed action is\n\t* stamped with.\n\t*\n\t* The emitted `Updated` event carries the document's id, never the\n\t* identifier this was called with: subscribers - including `DocumentCache` -\n\t* work in id space.\n\t*\n\t* `IReactorClient.execute`'s trailing `subject` is deliberately not accepted\n\t* here. It names the subject a local read gate answers as, and this client\n\t* runs no gate: the Switchboard decides what to serve from the bearer on the\n\t* request. Declaring it would suggest a per-call choice that does not exist.\n\t*/\n\tasync execute(documentIdentifier, branch, actions, signal) {\n\t\tconst document = await this.get(documentIdentifier, { branch }, signal);\n\t\tconst variables = {\n\t\t\tdocumentIdentifier,\n\t\t\tactions: (await prepareActionsForPush(actions, document, this.documentModels, this.signer, signal)).map(toTransportAction),\n\t\t\tsinceRevision: sinceRevisionForActions(document, actions),\n\t\t\tscopes: scopesForActions(actions),\n\t\t\tbranch\n\t\t};\n\t\tconst mutated = (await this.sdk.RunDocument({\n\t\t\toperationName: \"MutateDocumentWithOperations\",\n\t\t\toperationType: \"mutation\",\n\t\t\tdocument: MutateDocumentWithOperationsDocument,\n\t\t\tvariables,\n\t\t\tsignal\n\t\t})).mutateDocument;\n\t\tconst updated = phDocumentFromMutation(mutated, mutated.operations?.items ?? [], branch);\n\t\tthis.emitChange({\n\t\t\ttype: DOCUMENT_CHANGE_TYPE.Updated,\n\t\t\tdocuments: [updated]\n\t\t});\n\t\treturn updated;\n\t}\n\t/**\n\t* Deletes a document and announces it as a `Deleted` event.\n\t*\n\t* Pass a document id. The server resolves a slug just as happily, but\n\t* `deleteDocument` returns a boolean - there is no document left to read an\n\t* id off - so the identifier is announced verbatim on `context.childId`. A\n\t* subscriber keyed by id, `DocumentCache` included, therefore only reacts to\n\t* a delete by id.\n\t*/\n\tasync deleteDocument(identifier, propagate, signal) {\n\t\tawait this.sdk.DeleteDocument({\n\t\t\tidentifier,\n\t\t\tpropagate: propagationModeInput(propagate)\n\t\t}, void 0, signal);\n\t\tthis.emitChange({\n\t\t\ttype: DOCUMENT_CHANGE_TYPE.Deleted,\n\t\t\tdocuments: [],\n\t\t\tcontext: { childId: identifier }\n\t\t});\n\t}\n\t/**\n\t* Registers a change subscriber and returns its unsubscribe function.\n\t*\n\t* Two things produce the events delivered here. Every successful `create`,\n\t* `execute` and `deleteDocument` emits one, which is what makes a\n\t* `DocumentCache` built on this client invalidate after a dispatch. And,\n\t* unless realtime is switched off, the first call to this method opens a\n\t* websocket to the Switchboard and every change it reports - from another\n\t* user, another tab or a server-side processor - is emitted too. A write of\n\t* this client's own is therefore announced twice, once locally and once by\n\t* the server; the cache refetches twice, which is harmless.\n\t*\n\t* A websocket that cannot be opened or is refused is logged once and then\n\t* ignored: realtime is an enhancement, never a dependency. The failed socket\n\t* is closed, so the next subscriber to arrive tries again.\n\t*\n\t* `view` is accepted for interface compatibility and ignored: the emitted\n\t* documents are whatever the write returned, so there is nothing to re-scope.\n\t*\n\t* Events live in id space: `search.ids` is matched against the resolved\n\t* document id, never against the identifier the write was issued with. The\n\t* one exception is `deleteDocument`, which has no document to resolve an id\n\t* from - see its own note. A `DocumentCache` on this client must therefore\n\t* be read by id: a slug-keyed entry is never invalidated.\n\t*/\n\tsubscribe(search, callback, view) {\n\t\tconst listener = {\n\t\t\tsearch,\n\t\t\tcallback\n\t\t};\n\t\tthis.listeners.push(listener);\n\t\tthis.startRealtime();\n\t\treturn () => {\n\t\t\tconst index = this.listeners.indexOf(listener);\n\t\t\tif (index !== -1) this.listeners.splice(index, 1);\n\t\t};\n\t}\n\t/**\n\t* Closes the realtime socket, if one was opened.\n\t*\n\t* Registered subscribers are left in place: they still receive the events\n\t* this client produces itself.\n\t*\n\t* Disposing is NOT final - a later `subscribe` opens a new socket. React\n\t* remounts a tree by running an effect's cleanup and then the effect again,\n\t* on the same client, and `StrictMode` does exactly that on every mount; a\n\t* terminal flag here would leave those pages without realtime for good, with\n\t* nothing logged.\n\t*/\n\tdispose() {\n\t\tthis.teardownRealtime();\n\t}\n\t/**\n\t* Binds a project's generated SDK to this client's transport and auth.\n\t*\n\t* Subgraphs are served next to the reactor's own supergraph, so the endpoint\n\t* is derived from the client's `url` by appending the name, and the SDK is\n\t* handed the same auth middleware every reactor call goes through. An app\n\t* therefore configures one URL and one token provider, and reaches every\n\t* capability of its Switchboard through this one client.\n\t*\n\t* `getSdk` is the function a GraphQL code generator emits for the subgraph's\n\t* schema - see the README in this folder for the codegen recipe.\n\t*\n\t* Transport and typing only. Subgraph results are not cached, produce no\n\t* change events and never reach `useDocument`.\n\t*/\n\tsubgraph(name, getSdk) {\n\t\treturn this.subgraphs.get(name, getSdk);\n\t}\n\t/**\n\t* Runs a one-off GraphQL document against the Switchboard's own endpoint,\n\t* through the same transport and auth as everything else.\n\t*\n\t* The escape hatch for an operation not worth generating an SDK for. Pass a\n\t* document a code generator typed and the result type follows; pass a plain\n\t* `gql` document or a string and name the result type at the call site.\n\t*/\n\tasync request(document, variables, options) {\n\t\tconst described = describeGraphQLDocument(document);\n\t\treturn this.sdk.RunDocument({\n\t\t\toperationName: options?.operationName ?? described.operationName,\n\t\t\toperationType: options?.operationType ?? described.operationType,\n\t\t\tdocument,\n\t\t\tvariables,\n\t\t\tsignal: options?.signal\n\t\t});\n\t}\n\t/**\n\t* Opens the realtime socket on the first subscriber.\n\t*\n\t* The subscription is a firehose - no `search` argument - and this client\n\t* applies each subscriber's own filter on the way out, exactly as it does for\n\t* its own emissions.\n\t*/\n\tstartRealtime() {\n\t\tif (!this.subscriptionsUrl || this.realtimeStarted) return;\n\t\tthis.realtimeStarted = true;\n\t\tconst generation = this.realtimeGeneration;\n\t\tconst stop = startDocumentChangesSubscription({\n\t\t\twsUrl: this.subscriptionsUrl,\n\t\t\tconnectionParams: makeAuthConnectionParams(this.tokenProvider),\n\t\t\tonEvent: (event) => this.emitServerEvent(event),\n\t\t\tonError: (error) => this.handleRealtimeFailure(generation, error)\n\t\t});\n\t\tif (this.realtimeGeneration !== generation) {\n\t\t\tstop();\n\t\t\treturn;\n\t\t}\n\t\tthis.stopRealtime = stop;\n\t}\n\t/**\n\t* Gives up on a failed socket so that a later subscriber can try again.\n\t*\n\t* `graphql-ws` retries on its own and only reports here once it has given up,\n\t* or once the Switchboard refused the credentials the socket carried - which\n\t* `shouldRetry` declines to retry at all. Keeping the dead stop function\n\t* would make every later `subscribe` a no-op, so realtime would stay off for\n\t* the life of the page even after the user signs in.\n\t*\n\t* Why it died is recorded: a refusal is undone by a credential change and\n\t* nothing else, and {@link notifyCredentialsChanged} acts only on that.\n\t*\n\t* The generation stamp discards a report from a socket that has already been\n\t* replaced or disposed.\n\t*/\n\thandleRealtimeFailure(generation, error) {\n\t\tif (generation !== this.realtimeGeneration) return;\n\t\tthis.teardownRealtime();\n\t\tthis.realtimeRefusedCredentials = isAuthRefusalClose(error);\n\t\tthis.logRealtimeError(error);\n\t}\n\t/**\n\t* Reopens realtime after a sign-in, a sign-out or a token swap.\n\t*\n\t* Call it whenever the credentials this client authenticates with change.\n\t*\n\t* A live socket is replaced. `connectionParams` are resolved once, when the\n\t* socket opens, so a socket keeps presenting the credentials it was opened\n\t* with until something closes it - and a sign-out closes nothing. That left\n\t* a signed-out tab still receiving the previous identity's document changes,\n\t* on a shared machine, for as long as the socket happened to survive.\n\t*\n\t* A refused socket is reopened, for the same reason from the other side:\n\t* otherwise it stays closed until an unrelated component happens to\n\t* `subscribe`, so signing in leaves realtime off with nothing said - the\n\t* state `handleRealtimeFailure` resets to avoid.\n\t*\n\t* A socket that died for any other reason is left alone: a network failure\n\t* is not something a new token fixes, and reopening one here would turn a\n\t* credential change into a reconnect loop.\n\t*/\n\tnotifyCredentialsChanged() {\n\t\tif (!this.realtimeStarted && !this.realtimeRefusedCredentials) return;\n\t\tthis.teardownRealtime();\n\t\tif (this.listeners.length === 0) return;\n\t\tthis.startRealtime();\n\t}\n\t/** Closes the socket and lets a later subscriber open a new one. */\n\tteardownRealtime() {\n\t\tthis.realtimeGeneration += 1;\n\t\tthis.realtimeStarted = false;\n\t\tthis.realtimeRefusedCredentials = false;\n\t\tthis.stopRealtime?.();\n\t\tthis.stopRealtime = void 0;\n\t}\n\t/** Maps a server event onto the client-side event and emits it. */\n\temitServerEvent(event) {\n\t\tthis.emitChange({\n\t\t\ttype: documentChangeTypes[event.type],\n\t\t\tdocuments: event.documents.map((document) => phDocumentFromGetDocument(document)),\n\t\t\tcontext: event.context ? {\n\t\t\t\tparentId: event.context.parentId ?? void 0,\n\t\t\t\tchildId: event.context.childId ?? void 0\n\t\t\t} : void 0\n\t\t});\n\t}\n\t/**\n\t* Reports a broken realtime socket once per client, however many sockets it\n\t* goes through.\n\t*\n\t* `graphql-ws` retries on its own, and a Switchboard without a websocket\n\t* endpoint would otherwise fill the console for as long as the page is open.\n\t*/\n\tlogRealtimeError(error) {\n\t\tif (this.realtimeErrorLogged) return;\n\t\tthis.realtimeErrorLogged = true;\n\t\tlogger.warn(\"GraphQLReactorClient: realtime document changes are unavailable, falling back to local change events\", error);\n\t}\n\t/**\n\t* Delivers an event to every matching subscriber.\n\t*\n\t* A subscriber that throws is logged and skipped so one bad listener cannot\n\t* stop the others from being notified.\n\t*/\n\temitChange(event) {\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (!eventMatchesSearch(event, listener.search)) continue;\n\t\t\ttry {\n\t\t\t\tlistener.callback(event);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"GraphQLReactorClient: a document change subscriber threw\", error);\n\t\t\t}\n\t\t}\n\t}\n};\n/**\n* Whether a value is a {@link GraphQLReactorClient}, including one built by\n* another copy of this module.\n*\n* Use this rather than `instanceof`: the brand it tests for is shared by every\n* copy of the class, so a client built by a hot-replaced module or by a package\n* that bundled its own copy is still recognised.\n*/\nfunction isGraphQLReactorClient(client) {\n\treturn client?.[graphQLReactorClientBrand] === true;\n}\n/** The schema's change types, mapped onto the reactor's. */\nconst documentChangeTypes = {\n\t[DocumentChangeType.Created]: DOCUMENT_CHANGE_TYPE.Created,\n\t[DocumentChangeType.Deleted]: DOCUMENT_CHANGE_TYPE.Deleted,\n\t[DocumentChangeType.Updated]: DOCUMENT_CHANGE_TYPE.Updated,\n\t[DocumentChangeType.ParentAdded]: DOCUMENT_CHANGE_TYPE.ParentAdded,\n\t[DocumentChangeType.ParentRemoved]: DOCUMENT_CHANGE_TYPE.ParentRemoved,\n\t[DocumentChangeType.ChildAdded]: DOCUMENT_CHANGE_TYPE.ChildAdded,\n\t[DocumentChangeType.ChildRemoved]: DOCUMENT_CHANGE_TYPE.ChildRemoved\n};\n/**\n* Decides whether an event reaches a subscriber.\n*\n* Every populated field of the search filter is an AND condition, matching the\n* reactor's own subscription manager - which also treats an empty array as a\n* filter that nothing satisfies. `parentId` is a drive concept and is ignored.\n*\n* A `Deleted` event carries no documents, so it is matched on its\n* `context.childId` for identifier filters and delivered unconditionally to\n* type and slug filters: there is no document left to check them against.\n*/\nfunction eventMatchesSearch(event, search) {\n\tconst deleted = event.type === DOCUMENT_CHANGE_TYPE.Deleted;\n\tconst { ids, slugs, type } = search;\n\tif (ids) {\n\t\tif (!(deleted ? [event.context?.childId] : event.documents.map((document) => document.header.id)).some((id) => id !== void 0 && ids.includes(id))) return false;\n\t}\n\tif (slugs && !deleted) {\n\t\tif (!event.documents.map((document) => document.header.slug).some((slug) => slugs.includes(slug))) return false;\n\t}\n\tif (type && !deleted) {\n\t\tif (!event.documents.map((document) => document.header.documentType).includes(type)) return false;\n\t}\n\treturn true;\n}\n/**\n* Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.\n*\n* Point-in-time reads are rejected: the Switchboard read API has no revision\n* argument, so silently returning the head state would be wrong.\n*/\nfunction viewFilterInputFromViewFilter(view) {\n\tif (!view) return;\n\tif (view.revision !== void 0) throw new Error(\"point-in-time views are not supported by GraphQLReactorClient\");\n\tif (view.branch === void 0 && view.scopes === void 0) return;\n\treturn {\n\t\tbranch: view.branch,\n\t\tscopes: view.scopes\n\t};\n}\nfunction pagingInputFromPaging(paging) {\n\tif (!paging) return;\n\treturn {\n\t\tcursor: paging.cursor,\n\t\tlimit: paging.limit\n\t};\n}\n/**\n* The reactor and the GraphQL schema disagree on the enum: the reactor's\n* `None` is the schema's `ORPHAN`. This is the inverse of the server's\n* `toReactorPropagationMode`.\n*/\nconst propagationModeInputs = {\n\tcascade: PropagationMode.Cascade,\n\tnone: PropagationMode.Orphan\n};\nfunction propagationModeInput(propagate) {\n\treturn propagate === void 0 ? void 0 : propagationModeInputs[propagate];\n}\n/**\n* Stamps and signs the actions about to be pushed.\n*\n* With no signer the actions go out exactly as given, batch or not - this\n* client does not require signatures. With one, every action is signed:\n* {@link prepareSignedActions} predicts the chain a batch will produce by\n* running the document's own reducer between signatures, which is why a batch\n* needs the module matching the document's type and exact version.\n*\n* A batch that cannot be predicted - no matching module, mixed scopes, an\n* action needing history - throws here, before the mutation. Sending it\n* unsigned instead would silently drop the signatures the caller asked for.\n*/\nasync function prepareActionsForPush(actions, document, documentModels, explicitSigner, signal) {\n\tconst signer = explicitSigner ?? resolveAmbientSigner();\n\tif (!signer || actions.length === 0) return actions;\n\treturn prepareSignedActions(actions, document, signer, actions.length > 1 ? resolveDocumentModelModule(documentModels, document.header.documentType, documentModelVersion(document)) : void 0, signal);\n}\n/**\n* The document-model version the document's actions must be reduced with.\n*\n* `state` arrives as JSON over GraphQL, so its `document` scope is only as\n* reliable as the server that sent it - one written before that scope existed\n* carries no version at all. `normalizeDocumentModelVersion` maps that, and 0,\n* to 1: the same rule `SimpleJobExecutor` applies before asking the registry\n* for a module, so client and server cannot resolve different reducers.\n*/\nfunction documentModelVersion(document) {\n\tconst documentScope = document.state.document;\n\treturn normalizeDocumentModelVersion(documentScope?.version);\n}\n/** Resolves the signer of the logged-in user, if there is one. */\nfunction resolveAmbientSigner() {\n\tif (typeof window === \"undefined\") return;\n\tconst renown = window.ph?.renown;\n\treturn renown?.user ? renown.signer : void 0;\n}\n/**\n* The revision the pushed operations start from: the lowest head revision\n* across the scopes the actions target.\n*\n* The baseline is only meaningful together with {@link scopesForActions}: a\n* batch that touches a scope at revision 1 and one at revision 5000 would\n* otherwise re-download the whole history of every scope of the document.\n*/\nfunction sinceRevisionForActions(document, actions) {\n\tconst revisions = actions.map((action) => document.header.revision[action.scope] ?? 0);\n\treturn revisions.length > 0 ? Math.min(...revisions) : 0;\n}\n/** The distinct scopes the pushed actions target, in first-seen order. */\nfunction scopesForActions(actions) {\n\tif (actions.length === 0) return;\n\treturn [...new Set(actions.map((action) => action.scope))];\n}\n//#endregion\n//#region src/hooks/config/editor.ts\nconst isExternalControlsEnabledEventFunctions = makePHEventFunctions(\"isExternalControlsEnabled\");\n/** Sets whether external controls are enabled for a given editor. */\nconst setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;\n/** Gets whether external controls are enabled for a given editor. */\nconst useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;\n/** Adds an event handler for when the external controls enabled state changes. */\nconst addIsExternalControlsEnabledEventHandler = isExternalControlsEnabledEventFunctions.addEventHandler;\nconst isDragAndDropEnabledEventFunctions = makePHEventFunctions(\"isDragAndDropEnabled\");\n/** Sets whether drag and drop is enabled for a given app. */\nconst setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;\n/** Gets whether drag and drop is enabled for a given app. */\nconst useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;\n/** Adds an event handler for when the drag and drop enabled state changes. */\nconst addIsDragAndDropEnabledEventHandler = isDragAndDropEnabledEventFunctions.addEventHandler;\nconst allowedDocumentTypesEventFunctions = makePHEventFunctions(\"allowedDocumentTypes\");\n/** Sets the allowed document types for a given app. */\nconst setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;\n/** Defines the document types a drive supports.\n*\n* Defaults to all of the document types registered in the reactor.\n*/\nfunction useAllowedDocumentTypes() {\n\treturn allowedDocumentTypesEventFunctions.useValue();\n}\n/** Adds an event handler for when the allowed document types for a given app changes. */\nconst addAllowedDocumentTypesEventHandler = allowedDocumentTypesEventFunctions.addEventHandler;\nconst phAppConfigSetters = {\n\tallowedDocumentTypes: setAllowedDocumentTypes,\n\tisDragAndDropEnabled: setIsDragAndDropEnabled\n};\nconst phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };\nconst phAppConfigHooks = {\n\tallowedDocumentTypes: useAllowedDocumentTypes,\n\tisDragAndDropEnabled: useIsDragAndDropEnabled\n};\nconst phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };\n//#endregion\n//#region src/hooks/config/connect.ts\nconst { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions(\"routerBasename\");\nconst { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions(\"version\");\nconst { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions(\"requiresHardRefresh\");\nconst { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions(\"warnOutdatedApp\");\nconst { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions(\"studioMode\");\nconst { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions(\"basePath\");\nconst { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions(\"versionCheckInterval\");\nconst { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions(\"cliVersion\");\nconst { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions(\"fileUploadOperationsChunkSize\");\nconst { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions(\"isDocumentModelSelectionSettingsEnabled\");\nconst { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions(\"gaTrackingId\");\nconst { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions(\"defaultDrivesUrl\");\nconst { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions(\"drivesPreserveStrategy\");\nconst { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isLocalDrivesEnabled\");\nconst { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions(\"isAddDriveEnabled\");\nconst { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions(\"isPublicDrivesEnabled\");\nconst { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions(\"isAddPublicDrivesEnabled\");\nconst { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions(\"isDeletePublicDrivesEnabled\");\nconst { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions(\"isCloudDrivesEnabled\");\nconst { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions(\"isAddCloudDrivesEnabled\");\nconst { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions(\"isDeleteCloudDrivesEnabled\");\nconst { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isLocalDrivesEnabled\");\nconst { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isAddLocalDrivesEnabled\");\nconst { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions(\"isDeleteLocalDrivesEnabled\");\nconst { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions(\"isEditorDebugModeEnabled\");\nconst { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions(\"isEditorReadModeEnabled\");\nconst { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions(\"isAnalyticsDatabaseWorkerEnabled\");\nconst { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions(\"isDiffAnalyticsEnabled\");\nconst { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions(\"isDriveAnalyticsEnabled\");\nconst { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions(\"renownUrl\");\nconst { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions(\"renownNetworkId\");\nconst { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions(\"renownChainId\");\nconst { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions(\"switchboardUrl\");\nconst { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions(\"renownAdapters\");\nconst { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions(\"sentryRelease\");\nconst { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions(\"sentryDsn\");\nconst { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions(\"sentryEnv\");\nconst { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions(\"isSentryTracingEnabled\");\nconst { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions(\"isExternalProcessorsEnabled\");\nconst { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions(\"isExternalPackagesEnabled\");\nconst enabledEditorsEventFunctions = makePHEventFunctions(\"enabledEditors\");\n/** Sets the enabled editors for Connect. */\nconst setEnabledEditors = enabledEditorsEventFunctions.setValue;\n/** Gets the enabled editors for Connect. */\nconst useEnabledEditors = enabledEditorsEventFunctions.useValue;\n/** Adds an event handler for when the enabled editors for Connect changes. */\nconst addEnabledEditorsEventHandler = enabledEditorsEventFunctions.addEventHandler;\nconst disabledEditorsEventFunctions = makePHEventFunctions(\"disabledEditors\");\n/** Sets the disabled editors for Connect. */\nconst setDisabledEditors = disabledEditorsEventFunctions.setValue;\n/** Gets the disabled editors for Connect. */\nconst useDisabledEditors = disabledEditorsEventFunctions.useValue;\n/** Adds an event handler for when the disabled editors for Connect changes. */\nconst addDisabledEditorsEventHandler = disabledEditorsEventFunctions.addEventHandler;\nconst isRelationalProcessorsEnabled = makePHEventFunctions(\"isRelationalProcessorsEnabled\");\n/** Sets the isRelationalProcessorsEnabled for Connect. */\nconst setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;\n/** Gets the isRelationalProcessorsEnabled for Connect. */\nconst useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;\n/** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */\nconst addIsRelationalProcessorsEnabledEventHandler = isRelationalProcessorsEnabled.addEventHandler;\nconst isExternalRelationalProcessorsEnabled = makePHEventFunctions(\"isExternalRelationalProcessorsEnabled\");\n/** Sets the isExternalRelationalProcessorsEnabled for Connect. */\nconst setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;\n/** Gets the isExternalRelationalProcessorsEnabled for Connect. */\nconst useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;\n/** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */\nconst addIsExternalRelationalProcessorsEnabledEventHandler = isExternalRelationalProcessorsEnabled.addEventHandler;\nconst isAnalyticsEnabledEventFunctions = makePHEventFunctions(\"isAnalyticsEnabled\");\n/** Sets the isAnalyticsEnabled for Connect. */\nconst setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;\n/** Gets the isAnalyticsEnabled for Connect. */\nconst useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;\n/** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */\nconst addIsAnalyticsEnabledEventHandler = isAnalyticsEnabledEventFunctions.addEventHandler;\nconst isAnalyticsExternalProcessorsEnabled = makePHEventFunctions(\"isAnalyticsExternalProcessorsEnabled\");\n/** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */\nconst setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;\n/** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */\nconst useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;\n/** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */\nconst addIsAnalyticsExternalProcessorsEnabledEventHandler = isAnalyticsExternalProcessorsEnabled.addEventHandler;\nconst analyticsDatabaseNameEventFunctions = makePHEventFunctions(\"analyticsDatabaseName\");\n/** Sets the analytics database name for Connect. */\nconst setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;\n/** Gets the analytics database name for Connect. */\nconst useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;\n/** Adds an event handler for when the analytics database name for Connect changes. */\nconst addAnalyticsDatabaseNameEventHandler = analyticsDatabaseNameEventFunctions.addEventHandler;\nconst logLevelEventFunctions = makePHEventFunctions(\"logLevel\");\n/** Sets the log level for Connect. */\nconst setLogLevel = logLevelEventFunctions.setValue;\n/** Gets the log level for Connect. */\nconst useLogLevel = logLevelEventFunctions.useValue;\n/** Adds an event handler for when the log level for Connect changes. */\nconst addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;\nconst allowListEventFunctions = makePHEventFunctions(\"allowList\");\n/** Sets the allow list for Connect. */\nconst setAllowList = allowListEventFunctions.setValue;\n/** Gets the allow list for Connect. */\nconst useAllowList = allowListEventFunctions.useValue;\n/** Adds an event handler for when the allow list for Connect changes. */\nconst addAllowListEventHandler = allowListEventFunctions.addEventHandler;\nconst nonUserConfigSetters = {\n\trouterBasename: setRouterBasename,\n\tversion: setVersion,\n\trequiresHardRefresh: setRequiresHardRefresh,\n\twarnOutdatedApp: setWarnOutdatedApp,\n\tstudioMode: setStudioMode,\n\tbasePath: setBasePath,\n\tversionCheckInterval: setVersionCheckInterval,\n\tcliVersion: setCliVersion,\n\tfileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,\n\tisDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,\n\tgaTrackingId: setGaTrackingId,\n\tdefaultDrivesUrl: setDefaultDrivesUrl,\n\tdrivesPreserveStrategy: setDrivesPreserveStrategy,\n\tisLocalDrivesEnabled: setIsLocalDrivesEnabled,\n\tisAddDriveEnabled: setIsAddDriveEnabled,\n\tisPublicDrivesEnabled: setIsPublicDrivesEnabled,\n\tisAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,\n\tisDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,\n\tisCloudDrivesEnabled: setIsCloudDrivesEnabled,\n\tisAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,\n\tisDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,\n\tisAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,\n\tisDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,\n\tisEditorDebugModeEnabled: setIsEditorDebugModeEnabled,\n\tisEditorReadModeEnabled: setIsEditorReadModeEnabled,\n\tisRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,\n\tisExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,\n\tisAnalyticsEnabled: setIsAnalyticsEnabled,\n\tanalyticsDatabaseName: setAnalyticsDatabaseName,\n\tisAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,\n\tisAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,\n\tisDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,\n\tisDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,\n\trenownUrl: setRenownUrl,\n\trenownNetworkId: setRenownNetworkId,\n\trenownChainId: setRenownChainId,\n\tswitchboardUrl: setSwitchboardUrl,\n\trenownAdapters: setRenownAdapters,\n\tsentryRelease: setSentryRelease,\n\tsentryDsn: setSentryDsn,\n\tsentryEnv: setSentryEnv,\n\tisSentryTracingEnabled: setIsSentryTracingEnabled,\n\tisExternalProcessorsEnabled: setIsExternalProcessorsEnabled,\n\tisExternalPackagesEnabled: setIsExternalPackagesEnabled,\n\tallowList: setAllowList,\n\tlogLevel: setLogLevel,\n\tdisabledEditors: setDisabledEditors,\n\tenabledEditors: setEnabledEditors\n};\nconst phGlobalConfigSetters = {\n\t...phAppConfigSetters,\n\t...phDocumentEditorConfigSetters,\n\t...nonUserConfigSetters\n};\nconst nonUserConfigHooks = {\n\trouterBasename: useRouterBasename,\n\tversion: useVersion,\n\trequiresHardRefresh: useRequiresHardRefresh,\n\twarnOutdatedApp: useWarnOutdatedApp,\n\tstudioMode: useStudioMode,\n\tbasePath: useBasePath,\n\tversionCheckInterval: useVersionCheckInterval,\n\tcliVersion: useCliVersion,\n\tfileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,\n\tisDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,\n\tgaTrackingId: useGaTrackingId,\n\tdefaultDrivesUrl: useDefaultDrivesUrl,\n\tdrivesPreserveStrategy: useDrivesPreserveStrategy,\n\tisAddDriveEnabled: useIsAddDriveEnabled,\n\tisPublicDrivesEnabled: useIsPublicDrivesEnabled,\n\tisAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,\n\tisDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,\n\tisCloudDrivesEnabled: useIsCloudDrivesEnabled,\n\tisAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,\n\tisDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,\n\tisLocalDrivesEnabled: useIsLocalDrivesEnabled,\n\tisAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,\n\tisDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,\n\tisEditorDebugModeEnabled: useIsEditorDebugModeEnabled,\n\tisEditorReadModeEnabled: useIsEditorReadModeEnabled,\n\tisAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,\n\tisDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,\n\tisDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,\n\trenownUrl: useRenownUrl,\n\trenownNetworkId: useRenownNetworkId,\n\trenownChainId: useRenownChainId,\n\tswitchboardUrl: useSwitchboardUrl,\n\trenownAdapters: useRenownAdapters,\n\tsentryRelease: useSentryRelease,\n\tsentryDsn: useSentryDsn,\n\tsentryEnv: useSentryEnv,\n\tisSentryTracingEnabled: useIsSentryTracingEnabled,\n\tisExternalProcessorsEnabled: useIsExternalProcessorsEnabled,\n\tisExternalPackagesEnabled: useIsExternalPackagesEnabled,\n\tallowList: useAllowList,\n\tisAnalyticsEnabled: useIsAnalyticsEnabled,\n\tisAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,\n\tisRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,\n\tisExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,\n\tanalyticsDatabaseName: useAnalyticsDatabaseName,\n\tlogLevel: useLogLevel,\n\tdisabledEditors: useDisabledEditors,\n\tenabledEditors: useEnabledEditors\n};\nconst phGlobalConfigHooks = {\n\t...phAppConfigHooks,\n\t...phDocumentEditorConfigHooks,\n\t...nonUserConfigHooks\n};\n//#endregion\n//#region src/hooks/attachment-service.ts\nconst attachmentServiceEventFunctions = makePHEventFunctions(\"attachmentService\");\n/** Returns the attachment service from window.ph */\nconst useAttachmentService = attachmentServiceEventFunctions.useValue;\n/** Sets the attachment service on window.ph */\nconst setAttachmentService = attachmentServiceEventFunctions.setValue;\n/** Registers the attachmentService window event handler */\nconst addAttachmentServiceEventHandler = attachmentServiceEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/features.ts\nconst featuresEventFunctions = makePHEventFunctions(\"features\");\nconst useFeatures = featuresEventFunctions.useValue;\nconst setFeatures = featuresEventFunctions.setValue;\nconst addFeaturesEventHandler = featuresEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/use-drop-target.ts\nfunction useDropTarget() {\n\tconst [isDropTarget, setIsDropTarget] = useState(false);\n\tconst isDragAndDropEnabled = useIsDragAndDropEnabled();\n\tconst targetSetter = funnel(() => setIsDropTarget(true), {\n\t\ttriggerAt: \"start\",\n\t\tminQuietPeriodMs: 100\n\t});\n\tconst targetUnsetter = funnel(() => setIsDropTarget(false), {\n\t\ttriggerAt: \"start\",\n\t\tminQuietPeriodMs: 100\n\t});\n\tfunction setTarget() {\n\t\tif (!isDragAndDropEnabled) return;\n\t\ttargetUnsetter.cancel();\n\t\ttargetSetter.call();\n\t}\n\tfunction unsetTarget() {\n\t\tif (!isDragAndDropEnabled) return;\n\t\ttargetSetter.cancel();\n\t\ttargetUnsetter.call();\n\t}\n\treturn {\n\t\tisDropTarget,\n\t\tsetTarget,\n\t\tunsetTarget\n\t};\n}\n//#endregion\n//#region src/hooks/node-drag-and-drop.ts\nconst draggingNodeEventFunctions = makePHEventFunctions(\"draggingNode\");\nconst useDraggingNode = draggingNodeEventFunctions.useValue;\nconst setDraggingNode = draggingNodeEventFunctions.setValue;\nconst addDraggingNodeEventHandler = draggingNodeEventFunctions.addEventHandler;\nconst draggingNodeSetter = funnel((node) => setDraggingNode(node), {\n\treducer: (_, newNode) => newNode,\n\ttriggerAt: \"start\",\n\tminQuietPeriodMs: 100\n});\nconst draggingNodeUnsetter = funnel(() => setDraggingNode(void 0), {\n\ttriggerAt: \"start\",\n\tminQuietPeriodMs: 100\n});\nfunction setDragging(node) {\n\tdraggingNodeUnsetter.cancel();\n\tdraggingNodeSetter.call(node);\n}\nfunction unsetDragging() {\n\tdraggingNodeSetter.cancel();\n\tdraggingNodeUnsetter.call();\n}\nconst isNodeDrag = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isTruthy)(driveId), constant(false)], [({ driveId, srcId }) => isStrictEqual(driveId, srcId), constant(false)], constant(true));\nfunction useDragNode(args) {\n\tconst { srcId, parentId } = args;\n\tconst driveId = useSelectedDriveId();\n\tconst draggingNodeId = useDraggingNode()?.srcId;\n\tconst params = {\n\t\tdriveId,\n\t\tsrcId,\n\t\tparentId\n\t};\n\tconst draggable = isNodeDrag(params);\n\tconst isDragging = allPass({\n\t\tsrcId,\n\t\tdraggingNodeId\n\t}, [\n\t\t() => draggable,\n\t\t({ srcId }) => isString(srcId),\n\t\t({ draggingNodeId }) => isString(draggingNodeId),\n\t\t({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId)\n\t]);\n\tconst onDragStart = () => {\n\t\tif (!draggable) return;\n\t\tsetDragging(params);\n\t};\n\tconst onDragEnd = () => {\n\t\tif (!draggable) return;\n\t\tunsetDragging();\n\t};\n\treturn {\n\t\tisDragging,\n\t\tdraggable,\n\t\tonDragStart,\n\t\tonDragEnd\n\t};\n}\nconst isNodeDrop = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isDefined)(driveId), constant(false)], [({ srcId, targetId }) => isStrictEqual(srcId, targetId), constant(false)], [({ driveId, parentId, targetId }) => isNot(isTruthy)(parentId) && isStrictEqual(targetId, driveId), constant(false)], [({ targetId, parentId }) => isStrictEqual(targetId, parentId), constant(false)], constant(true));\nfunction useDropNode(targetId) {\n\tconst driveId = useSelectedDriveId();\n\tconst { srcId, parentId } = useDraggingNode() ?? {};\n\tconst { isDropTarget, setTarget, unsetTarget } = useDropTarget();\n\tconst params = {\n\t\tdriveId,\n\t\tparentId,\n\t\ttargetId,\n\t\tsrcId\n\t};\n\tfunction handleNodeDrop(event, cb) {\n\t\tif (!isNodeDrop(params)) return;\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\tcb?.();\n\t}\n\tconst onDragEnter = (event) => handleNodeDrop(event);\n\tconst onDragOver = (event) => handleNodeDrop(event, once(setTarget));\n\tconst onDragLeave = (event) => handleNodeDrop(event, once(unsetTarget));\n\tconst onDrop = (event) => handleNodeDrop(event, once(() => {\n\t\tunsetDragging();\n\t\tunsetTarget();\n\t\tmoveNodeById(params).catch(console.error);\n\t}));\n\treturn {\n\t\tisDropTarget,\n\t\tonDragEnter,\n\t\tonDragOver,\n\t\tonDragLeave,\n\t\tonDrop\n\t};\n}\n//#endregion\n//#region src/hooks/graphql-reactor-client.ts\nconst graphQLReactorClientEventFunctions = makePHEventFunctions(\"reactorGraphQLClient\");\nconst useGraphQLReactorClient = graphQLReactorClientEventFunctions.useValue;\nconst setGraphQLReactorClient = graphQLReactorClientEventFunctions.setValue;\nconst addGraphQLReactorClientEventHandler = graphQLReactorClientEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/package-discovery.ts\nconst packageDiscoveryFunctions = makePHEventFunctions(\"packageDiscoveryService\");\nconst usePackageDiscoveryService = packageDiscoveryFunctions.useValue;\nconst setPackageDiscoveryService = packageDiscoveryFunctions.setValue;\nconst addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/reactor.ts\nconst reactorClientModuleEventFunctions = makePHEventFunctions(\"reactorClientModule\");\nconst reactorClientEventFunctions = makePHEventFunctions(\"reactorClient\");\n/** Returns the reactor client module (in-process or worker-backed) */\nconst useReactorClientModule = reactorClientModuleEventFunctions.useValue;\n/** Sets the reactor client module */\nconst setReactorClientModule = reactorClientModuleEventFunctions.setValue;\n/** Adds an event handler for the reactor client module */\nconst addReactorClientModuleEventHandler = reactorClientModuleEventFunctions.addEventHandler;\n/** Returns the reactor client */\nconst useReactorClient = reactorClientEventFunctions.useValue;\n/** Sets the reactor client */\nconst setReactorClient = reactorClientEventFunctions.setValue;\n/** Adds an event handler for the reactor client */\nconst addReactorClientEventHandler = reactorClientEventFunctions.addEventHandler;\nconst useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;\nconst useSyncList = () => {\n\treturn useSync()?.list() ?? [];\n};\nconst useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;\nconst useDatabase = () => {\n\tconst module = useReactorClientModule();\n\treturn module?.kind === \"browser\" ? module.reactorModule?.database : void 0;\n};\nconst usePGlite = () => {\n\tconst module = useReactorClientModule();\n\treturn module?.kind === \"browser\" ? module.reactorModule?.pg : void 0;\n};\n//#endregion\n//#region src/hooks/revision-history.ts\nconst revisionHistoryEventFunctions = makePHEventFunctions(\"revisionHistoryVisible\");\n/** Returns whether revision history is visible */\nconst useRevisionHistoryVisible = revisionHistoryEventFunctions.useValue;\n/** Sets revision history visibility */\nconst setRevisionHistoryVisible = revisionHistoryEventFunctions.setValue;\n/** Adds event handler for revision history visibility */\nconst addRevisionHistoryVisibleEventHandler = revisionHistoryEventFunctions.addEventHandler;\n/** Shows the revision history */\nfunction showRevisionHistory() {\n\tsetRevisionHistoryVisible(true);\n}\n/** Hides the revision history */\nfunction hideRevisionHistory() {\n\tsetRevisionHistoryVisible(false);\n}\n//#endregion\n//#region src/hooks/selected-timeline-item.ts\nconst selectedTimelineItemEventFunctions = makePHEventFunctions(\"selectedTimelineItem\");\n/** Returns the selected timeline item */\nconst useSelectedTimelineItem = selectedTimelineItemEventFunctions.useValue;\n/** Sets the selected timeline item */\nconst setSelectedTimelineItem = selectedTimelineItemEventFunctions.setValue;\n/** Adds event handler for selected timeline item */\nconst addSelectedTimelineItemEventHandler = selectedTimelineItemEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/timeline-revision.ts\nconst selectedTimelineRevisionEventFunctions = makePHEventFunctions(\"selectedTimelineRevision\");\n/** Returns the selected timeline revision. */\nconst useSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.useValue;\n/** Sets the selected timeline revision. */\nconst setSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.setValue;\n/** Adds an event handler for the selected timeline revision. */\nconst addSelectedTimelineRevisionEventHandler = selectedTimelineRevisionEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/toast.ts\nconst toastEventFunctions = makePHEventFunctions(\"toast\");\n/** Returns the toast function */\nconst usePHToast = toastEventFunctions.useValue;\n/** Sets the toast function */\nconst setPHToast = toastEventFunctions.setValue;\n/** Adds an event handler for the toast */\nconst addToastEventHandler = toastEventFunctions.addEventHandler;\n//#endregion\n//#region src/hooks/add-ph-event-handlers.ts\nconst commonGlobalEventHandlerFunctions = {\n\tloading: addLoadingEventHandler,\n\tdrives: addDrivesEventHandler,\n\tselectedDriveId: () => {\n\t\taddSelectedDriveIdEventHandler();\n\t\taddSetSelectedDriveOnPopStateEventHandler();\n\t\taddResetSelectedNodeEventHandler();\n\t},\n\tselectedNodeId: () => {\n\t\taddSelectedNodeIdEventHandler();\n\t\taddSetSelectedNodeOnPopStateEventHandler();\n\t},\n\tdocumentCache: addDocumentCacheEventHandler,\n\treactorGraphQLClient: addGraphQLReactorClientEventHandler,\n\tdraggingNode: addDraggingNodeEventHandler\n};\nconst phGlobalEventHandlerRegisterFunctions = {\n\t...commonGlobalEventHandlerFunctions,\n\treactorClientModule: addReactorClientModuleEventHandler,\n\treactorClient: addReactorClientEventHandler,\n\tattachmentService: addAttachmentServiceEventHandler,\n\tfeatures: addFeaturesEventHandler,\n\tmodal: addModalEventHandler,\n\trenown: addRenownEventHandler,\n\tvetraPackageManager: addVetraPackageManagerEventHandler,\n\tpackageDiscoveryService: addPackageDiscoveryServiceEventHandler,\n\tselectedTimelineRevision: addSelectedTimelineRevisionEventHandler,\n\trevisionHistoryVisible: addRevisionHistoryVisibleEventHandler,\n\tselectedTimelineItem: addSelectedTimelineItemEventHandler,\n\trouterBasename: addRouterBasenameEventHandler,\n\tversion: addVersionEventHandler,\n\tlogLevel: addLogLevelEventHandler,\n\trequiresHardRefresh: addRequiresHardRefreshEventHandler,\n\twarnOutdatedApp: addWarnOutdatedAppEventHandler,\n\tstudioMode: addStudioModeEventHandler,\n\tbasePath: addBasePathEventHandler,\n\tversionCheckInterval: addVersionCheckIntervalEventHandler,\n\tcliVersion: addCliVersionEventHandler,\n\tfileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,\n\tisDocumentModelSelectionSettingsEnabled: addIsDocumentModelSelectionSettingsEnabledEventHandler,\n\tgaTrackingId: addGaTrackingIdEventHandler,\n\tallowList: addAllowListEventHandler,\n\tdefaultDrivesUrl: addDefaultDrivesUrlEventHandler,\n\tdrivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,\n\tallowedDocumentTypes: addAllowedDocumentTypesEventHandler,\n\tenabledEditors: addEnabledEditorsEventHandler,\n\tdisabledEditors: addDisabledEditorsEventHandler,\n\tisAddDriveEnabled: addIsAddDriveEnabledEventHandler,\n\tisLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,\n\tisPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,\n\tisAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,\n\tisDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,\n\tisCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,\n\tisAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,\n\tisDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,\n\tisAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,\n\tisDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,\n\tisDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,\n\tisExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,\n\tisEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,\n\tisEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,\n\tisRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,\n\tisExternalRelationalProcessorsEnabled: addIsExternalRelationalProcessorsEnabledEventHandler,\n\tisAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,\n\tisAnalyticsExternalProcessorsEnabled: addIsAnalyticsExternalProcessorsEnabledEventHandler,\n\tanalyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,\n\tisAnalyticsDatabaseWorkerEnabled: addIsAnalyticsDatabaseWorkerEnabledEventHandler,\n\tisDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,\n\tisDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,\n\trenownUrl: addRenownUrlEventHandler,\n\trenownNetworkId: addRenownNetworkIdEventHandler,\n\trenownChainId: addRenownChainIdEventHandler,\n\tswitchboardUrl: addSwitchboardUrlEventHandler,\n\trenownAdapters: addRenownAdaptersEventHandler,\n\tsentryRelease: addSentryReleaseEventHandler,\n\tsentryDsn: addSentryDsnEventHandler,\n\tsentryEnv: addSentryEnvEventHandler,\n\tisSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,\n\tisExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,\n\tisExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,\n\ttoast: addToastEventHandler\n};\nfunction addPHEventHandlers() {\n\tcallEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);\n}\nfunction callEventHandlerRegisterFunctions(registerFunctions) {\n\tforEachObj(registerFunctions, (fn) => fn());\n}\n//#endregion\n//#region src/graphql-client/graphql-reactor-provider.tsx\n/**\n* Registers the `window.ph` event handlers once per page.\n*\n* The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`\n* until `addPHEventHandlers` has registered the listeners that do. Registration\n* is guarded by a marker on `window` rather than a module-level flag so that a\n* hot module replacement, or two copies of this module, still register once.\n*/\nfunction ensurePHEventHandlers() {\n\tif (typeof window === \"undefined\" || window.__phEventHandlersRegistered) return;\n\taddPHEventHandlers();\n\twindow.__phEventHandlersRegistered = true;\n}\n/**\n* Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the\n* reactor-browser hooks read, so `useDocument`, `useDispatch` and\n* `useReactorClient` work below it against a Switchboard, with no reactor in\n* the bundle.\n*\n* It fills the document slots, plus `window.ph.vetraPackageManager` when\n* `documentModels` is given (a fixed {@link StaticPackageManager}, which makes\n* the document-model hooks work). The same modules go to the client itself, so\n* a dispatch of two or more actions is signed rather than refused.\n* `window.ph.reactorClientModule` always stays empty, so full-reactor surfaces\n* (drives, jobs, editor auto-discovery) find nothing - an app below this\n* provider renders components it imports itself.\n*\n* The client is built on the client only: on the server the slots stay empty\n* and the hooks report their normal loading states. The props are read once,\n* when the client is built - changing `url` afterwards does not rebuild it.\n*\n* The effect's cleanup disposes the cache and the client's socket, and the\n* effect rebuilds both if it runs again on the same client - which is what a\n* `StrictMode` mount does.\n*/\nfunction GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, documentModels, children }) {\n\tconst [client] = useState(() => typeof window === \"undefined\" ? void 0 : new GraphQLReactorClient({\n\t\turl,\n\t\ttokenProvider,\n\t\tsubscriptionsUrl,\n\t\trealtime,\n\t\tdocumentModels\n\t}));\n\tuseEffect(() => {\n\t\tif (!client) return;\n\t\tensurePHEventHandlers();\n\t\tsetReactorClient(client);\n\t\tconst documentCache = new DocumentCache(client);\n\t\tsetDocumentCache(documentCache);\n\t\treturn () => {\n\t\t\tdocumentCache.dispose();\n\t\t\tclient.dispose();\n\t\t};\n\t}, [client]);\n\tuseEffect(() => {\n\t\tif (!attachmentService) return;\n\t\tensurePHEventHandlers();\n\t\tsetAttachmentService(attachmentService);\n\t}, [attachmentService]);\n\tuseEffect(() => {\n\t\tif (!documentModels || documentModels.length === 0) return;\n\t\tensurePHEventHandlers();\n\t\tsetVetraPackageManager(new StaticPackageManager([packageFromDocumentModels(documentModels)]));\n\t}, [documentModels]);\n\treturn /* @__PURE__ */ jsx(Fragment, { children });\n}\n/**\n* Returns the {@link GraphQLReactorClient} mounted by\n* {@link GraphQLReactorProvider}, or `undefined` when the slot holds something\n* else - the full in-browser reactor client, or nothing yet.\n*\n* `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both\n* implementations share. This is how a component reaches the light client's own\n* surface, i.e. `subgraph` and `request`.\n*\n* The narrowing is by brand, not by `instanceof`: a page can carry two copies\n* of this module - a bundled package with its own copy, or a hot-replaced one -\n* and `instanceof` would then answer `false` for a perfectly good client and\n* leave the component silently without one.\n*/\nfunction useSwitchboardClient() {\n\tconst client = useReactorClient();\n\treturn isGraphQLReactorClient(client) ? client : void 0;\n}\n//#endregion\n//#region src/hooks/document-operations.ts\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*/\nfunction useDocumentOperations(documentId) {\n\tconst reactorClient = useReactorClient();\n\tconst hasFetchedRef = useRef(false);\n\tconst [state, setState] = useState(() => ({\n\t\tglobalOperations: [],\n\t\tlocalOperations: [],\n\t\tisLoading: !!documentId,\n\t\terror: void 0\n\t}));\n\tconst fetchOperations = useCallback(async (retryCount = 0) => {\n\t\tconst MAX_RETRIES = 5;\n\t\tconst RETRY_DELAY_MS = 500;\n\t\tif (!documentId || !reactorClient) {\n\t\t\tsetState({\n\t\t\t\tglobalOperations: [],\n\t\t\t\tlocalOperations: [],\n\t\t\t\tisLoading: false,\n\t\t\t\terror: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tsetState((prev) => ({\n\t\t\t...prev,\n\t\t\tisLoading: true,\n\t\t\terror: void 0\n\t\t}));\n\t\tlet globalOps = [];\n\t\tlet localOps = [];\n\t\tlet fetchError;\n\t\ttry {\n\t\t\tglobalOps = (await reactorClient.getOperations(documentId, { scopes: [\"global\"] })).results;\n\t\t} catch (err) {\n\t\t\tfetchError = err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (!fetchError) try {\n\t\t\tlocalOps = (await reactorClient.getOperations(documentId, { scopes: [\"local\"] })).results;\n\t\t} catch (err) {\n\t\t\tfetchError = err instanceof Error ? err : new Error(String(err));\n\t\t}\n\t\tif (!fetchError && globalOps.length === 0 && localOps.length === 0 && retryCount < MAX_RETRIES) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));\n\t\t\treturn fetchOperations(retryCount + 1);\n\t\t}\n\t\tsetState({\n\t\t\tglobalOperations: globalOps,\n\t\t\tlocalOperations: localOps,\n\t\t\tisLoading: false,\n\t\t\terror: fetchError\n\t\t});\n\t\thasFetchedRef.current = true;\n\t}, [documentId, reactorClient]);\n\tuseEffect(() => {\n\t\tif (documentId && reactorClient) fetchOperations();\n\t\telse if (!documentId) {\n\t\t\tsetState({\n\t\t\t\tglobalOperations: [],\n\t\t\t\tlocalOperations: [],\n\t\t\t\tisLoading: false,\n\t\t\t\terror: void 0\n\t\t\t});\n\t\t\thasFetchedRef.current = false;\n\t\t}\n\t}, [\n\t\tdocumentId,\n\t\treactorClient,\n\t\tfetchOperations\n\t]);\n\tconst refetch = useCallback(() => {\n\t\tfetchOperations(0);\n\t}, [fetchOperations]);\n\treturn {\n\t\t...state,\n\t\trefetch\n\t};\n}\n//#endregion\nexport { addDefaultDrivesUrlEventHandler as $, useIsAddLocalDrivesEnabled as $n, isAuthRefusalClose as $r, setEnabledEditors as $t, useReactorClientModule as A, fetchDocumentOperations as Ai, setRenownUrl as An, useSentryRelease as Ar, addRenownAdaptersEventHandler as At, useDragNode as B, addModalEventHandler as Bi, setWarnOutdatedApp as Bn, phAppConfigHooks as Br, addSwitchboardUrlEventHandler as Bt, addReactorClientModuleEventHandler as C, addDocument as Ci, setIsRelationalProcessorsEnabled as Cn, useRenownChainId as Cr, addIsExternalRelationalProcessorsEnabledEventHandler as Ct, useModelRegistry as D, deleteNode as Di, setRenownAdapters as Dn, useRouterBasename as Dr, addIsSentryTracingEnabledEventHandler as Dt, useDatabase as E, copyNode$1 as Ei, setLogLevel as En, useRequiresHardRefresh as Er, addIsRelationalProcessorsEnabledEventHandler as Et, usePackageDiscoveryService as F, renameNode as Fi, setSentryRelease as Fn, useWarnOutdatedApp as Fr, addRouterBasenameEventHandler as Ft, useFeatures as G, showPHModal as Gi, useDefaultDrivesUrl as Gn, setIsDragAndDropEnabled as Gr, phGlobalConfigSetters as Gt, useDropTarget as H, setPHModal as Hi, useAnalyticsDatabaseName as Hn, phDocumentEditorConfigHooks as Hr, addVersionEventHandler as Ht, addGraphQLReactorClientEventHandler as I, setPreferredEditorOnNode as Ii, setStudioMode as In, addAllowedDocumentTypesEventHandler as Ir, addSentryDsnEventHandler as It, useAttachmentService as J, useEnabledEditors as Jn, useIsDragAndDropEnabled as Jr, setBasePath as Jt, addAttachmentServiceEventHandler as K, usePHModal as Ki, useDisabledEditors as Kn, setIsExternalControlsEnabled as Kr, setAllowList as Kt, setGraphQLReactorClient as L, upgradeDocument as Li, setSwitchboardUrl as Ln, addIsDragAndDropEnabledEventHandler as Lr, addSentryEnvEventHandler as Lt, useSyncList as M, loadFile as Mi, setRouterBasename as Mn, useSwitchboardUrl as Mr, addRenownNetworkIdEventHandler as Mt, addPackageDiscoveryServiceEventHandler as N, moveNode$1 as Ni, setSentryDsn as Nn, useVersion as Nr, addRenownUrlEventHandler as Nt, usePGlite as O, exportFile as Oi, setRenownChainId as On, useSentryDsn as Or, addLocalDrivesEnabledEventHandler as Ot, setPackageDiscoveryService as P, renameDriveNode as Pi, setSentryEnv as Pn, useVersionCheckInterval as Pr, addRequiresHardRefreshEventHandler as Pt, addCliVersionEventHandler as Q, useIsAddDriveEnabled as Qn, viewFilterInputFromViewFilter as Qr, setDrivesPreserveStrategy as Qt, useGraphQLReactorClient as R, getUserPermissions as Ri, setVersion as Rn, addIsExternalControlsEnabledEventHandler as Rr, addSentryReleaseEventHandler as Rt, addReactorClientEventHandler as S, screamingSnakeToCamel as Si, setIsPublicDrivesEnabled as Sn, useRenownAdapters as Sr, addIsExternalProcessorsEnabledEventHandler as St, setReactorClientModule as T, addFolder$1 as Ti, setLocalDrivesEnabled as Tn, useRenownUrl as Tr, addIsPublicDrivesEnabledEventHandler as Tt, addFeaturesEventHandler as U, showCreateDocumentModal as Ui, useBasePath as Un, phDocumentEditorConfigSetters as Ur, addWarnOutdatedAppEventHandler as Ut, useDropNode as V, closePHModal as Vi, useAllowList as Vn, phAppConfigSetters as Vr, addVersionCheckIntervalEventHandler as Vt, setFeatures as W, showDeleteNodeModal as Wi, useCliVersion as Wn, setAllowedDocumentTypes as Wr, phGlobalConfigHooks as Wt, addAnalyticsDatabaseNameEventHandler as X, useGaTrackingId as Xn, GraphQLReactorClient as Xr, setDefaultDrivesUrl as Xt, addAllowListEventHandler as Y, useFileUploadOperationsChunkSize as Yn, useIsExternalControlsEnabled as Yr, setCliVersion as Yt, addBasePathEventHandler as Z, useIsAddCloudDrivesEnabled as Zn, isGraphQLReactorClient as Zr, setDisabledEditors as Zt, addRevisionHistoryVisibleEventHandler as _, ConflictError as _i, setIsEditorReadModeEnabled as _n, useIsPublicDrivesEnabled as _r, addIsDocumentModelSelectionSettingsEnabledEventHandler as _t, addPHEventHandlers as a, subgraphUrlFromGraphqlUrl as ai, setIsAddPublicDrivesEnabled as an, useIsDeleteCloudDrivesEnabled as ar, addIsAddCloudDrivesEnabledEventHandler as at, showRevisionHistory as b, extractRevisionMap as bi, setIsExternalRelationalProcessorsEnabled as bn, useLocalDrivesEnabled as br, addIsEditorReadModeEnabledEventHandler as bt, addToastEventHandler as c, resolveDocumentModelModule as ci, setIsAnalyticsExternalProcessorsEnabled as cn, useIsDiffAnalyticsEnabled as cr, addIsAddPublicDrivesEnabledEventHandler as ct, addSelectedTimelineRevisionEventHandler as d, stampAction as di, setIsDeleteLocalDrivesEnabled as dn, useIsEditorDebugModeEnabled as dr, addIsAnalyticsExternalProcessorsEnabledEventHandler as dt, makeAuthConnectionParams as ei, setFileUploadOperationsChunkSize as en, useIsAddPublicDrivesEnabled as er, addDisabledEditorsEventHandler as et, setSelectedTimelineRevision as f, MutateDocumentWithOperationsDocument as fi, setIsDeletePublicDrivesEnabled as fn, useIsEditorReadModeEnabled as fr, addIsCloudDrivesEnabledEventHandler as ft, useSelectedTimelineItem as g, revisionMapFromRevisionsList as gi, setIsEditorDebugModeEnabled as gn, useIsLocalDrivesEnabled as gr, addIsDiffAnalyticsEnabledEventHandler as gt, setSelectedTimelineItem as h, phDocumentFromMutation as hi, setIsDriveAnalyticsEnabled as hn, useIsExternalRelationalProcessorsEnabled as hr, addIsDeletePublicDrivesEnabledEventHandler as ht, useSwitchboardClient as i, describeGraphQLDocument as ii, setIsAddLocalDrivesEnabled as in, useIsCloudDrivesEnabled as ir, addGaTrackingIdEventHandler as it, useSync as j, getDocumentExtension as ji, setRequiresHardRefresh as jn, useStudioMode as jr, addRenownChainIdEventHandler as jt, useReactorClient as k, extractInitialState as ki, setRenownNetworkId as kn, useSentryEnv as kr, addLogLevelEventHandler as kt, setPHToast as l, prepareSignedActions as li, setIsCloudDrivesEnabled as ln, useIsDocumentModelSelectionSettingsEnabled as lr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as lt, addSelectedTimelineItemEventHandler as m, phDocumentFromGetDocument as mi, setIsDocumentModelSelectionSettingsEnabled as mn, useIsExternalProcessorsEnabled as mr, addIsDeleteLocalDrivesEnabledEventHandler as mt, GraphQLReactorProvider as n, subscriptionsUrlFromGraphqlUrl as ni, setIsAddCloudDrivesEnabled as nn, useIsAnalyticsEnabled as nr, addEnabledEditorsEventHandler as nt, callEventHandlerRegisterFunctions as o, StaticPackageManager as oi, setIsAnalyticsDatabaseWorkerEnabled as on, useIsDeleteLocalDrivesEnabled as or, addIsAddDriveEnabledEventHandler as ot, useSelectedTimelineRevision as p, ReactorOperationFieldsFragmentDoc as pi, setIsDiffAnalyticsEnabled as pn, useIsExternalPackagesEnabled as pr, addIsDeleteCloudDrivesEnabledEventHandler as pt, setAttachmentService as q, useDrivesPreserveStrategy as qn, useAllowedDocumentTypes as qr, setAnalyticsDatabaseName as qt, ensurePHEventHandlers as r, SubgraphSdkRegistry as ri, setIsAddDriveEnabled as rn, useIsAnalyticsExternalProcessorsEnabled as rr, addFileUploadOperationsChunkSizeEventHandler as rt, commonGlobalEventHandlerFunctions as s, packageFromDocumentModels as si, setIsAnalyticsEnabled as sn, useIsDeletePublicDrivesEnabled as sr, addIsAddLocalDrivesEnabledEventHandler as st, useDocumentOperations as t, startDocumentChangesSubscription as ti, setGaTrackingId as tn, useIsAnalyticsDatabaseWorkerEnabled as tr, addDrivesPreserveStrategyEventHandler as tt, usePHToast as u, signStampedAction as ui, setIsDeleteCloudDrivesEnabled as un, useIsDriveAnalyticsEnabled as ur, addIsAnalyticsEnabledEventHandler as ut, hideRevisionHistory as v, buildPulledDocument as vi, setIsExternalPackagesEnabled as vn, useIsRelationalProcessorsEnabled as vr, addIsDriveAnalyticsEnabledEventHandler as vt, setReactorClient as w, addFileWithProgress as wi, setIsSentryTracingEnabled as wn, useRenownNetworkId as wr, addIsLocalDrivesEnabledEventHandler as wt, useRevisionHistoryVisible as x, hasRevisionConflict as xi, setIsLocalDrivesEnabled as xn, useLogLevel as xr, addIsExternalPackagesEnabledEventHandler as xt, setRevisionHistoryVisible as y, convertRemoteOperations as yi, setIsExternalProcessorsEnabled as yn, useIsSentryTracingEnabled as yr, addIsEditorDebugModeEnabledEventHandler as yt, addDraggingNodeEventHandler as z, isDocumentTypeSupported as zi, setVersionCheckInterval as zn, isExternalControlsEnabledEventFunctions as zr, addStudioModeEventHandler as zt };\n\n//# sourceMappingURL=document-operations-WeE6wIDt.js.map","import { t as useDocumentById } from \"./document-by-id-B4FIzG1w.js\";\nimport { K as ambientRenownTokenProvider, U as DocumentTypeMismatchError, W as NoSelectedDocumentError, s as useSelectedNode, t as useDocumentModelModuleById } from \"./document-model-modules-bTP87nyr.js\";\nimport { DriveCollectionId, ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport { z } from \"zod\";\n//#region src/hooks/document-of-type.ts\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nfunction useDocumentOfType(documentId, documentType) {\n\tconst [document, dispatch] = useDocumentById(documentId);\n\tconst documentModelModule = useDocumentModelModuleById(documentType);\n\tif (!documentId || !documentType) return [];\n\tif (!document) throw new Error(`Document not found: ${documentId}`);\n\tif (!documentModelModule) throw new ModuleNotFoundError(documentType);\n\tif (document.header.documentType !== documentType) throw new DocumentTypeMismatchError(documentId, documentType, document.header.documentType);\n\treturn [document, dispatch];\n}\n//#endregion\n//#region src/hooks/selected-document.ts\n/** Returns the selected document id */\nfunction useSelectedDocumentId() {\n\tconst selectedNode = useSelectedNode();\n\treturn selectedNode && isFileNode(selectedNode) ? selectedNode.id : void 0;\n}\n/** Returns the selected document. */\nfunction useSelectedDocument() {\n\tconst [document, dispatch] = useDocumentById(useSelectedDocumentId());\n\tif (!document) throw new NoSelectedDocumentError();\n\treturn [document, dispatch];\n}\n/** Returns the selected document. */\nfunction useSelectedDocumentSafe() {\n\treturn useDocumentById(useSelectedDocumentId());\n}\nfunction useSelectedDocumentOfType(documentType) {\n\tconst documentId = useSelectedDocumentId();\n\tif (!documentType) return [];\n\tif (!documentId) throw new NoSelectedDocumentError();\n\treturn useDocumentOfType(documentId, documentType);\n}\n//#endregion\n//#region src/ai/switchboard.ts\n/**\n* Reads the tab-side sync manager from the browser global. Returns\n* `undefined` in non-browser environments or before the reactor client\n* module is initialized.\n*/\nfunction getBrowserSyncManager() {\n\tif (typeof window === \"undefined\") return;\n\treturn window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n}\n/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nconst GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n/**\n* Resolves the switchboard that serves a drive, if any.\n*\n* Every remote drive stores its switchboard's exact GraphQL channel\n* endpoint in its sync remote — `channelConfig = { type: \"gql\",\n* parameters: { url: \"<origin>/graphql/r\" } }` — and the switchboard base\n* is that URL minus the `/graphql/r` suffix. Deriving it per drive (rather\n* than from a global setting) is what keeps multi-switchboard deployments\n* correct. Drives that are not synced to a remote switchboard (local\n* drives, other channel types, unexpected shapes) return `undefined`.\n*/\nfunction resolveDriveSwitchboard(driveId, syncManager) {\n\tconst manager = syncManager ?? getBrowserSyncManager();\n\tif (!driveId || !manager) return;\n\tconst collectionId = DriveCollectionId.forDrive(driveId);\n\tconst remote = manager.list().find((r) => r.meta.collectionId.equals(collectionId));\n\tif (!remote) return;\n\tconst { channelConfig } = remote.meta;\n\tif (channelConfig.type !== \"gql\") return;\n\tconst url = channelConfig.parameters.url;\n\tif (typeof url !== \"string\" || !url.endsWith(\"/graphql/r\")) return;\n\tconst switchboardUrl = url.slice(0, -10);\n\treturn {\n\t\tswitchboardUrl,\n\t\tgraphqlUrl: `${switchboardUrl}/graphql`\n\t};\n}\n/**\n* Introspection over the switchboard supergraph's root query and mutation\n* fields. Types are requested with three levels of `ofType` nesting so\n* that common shapes like `[X!]!` (LIST(NON_NULL(LIST(X)))) render fully.\n*/\nconst SWITCHBOARD_INTROSPECTION_QUERY = `\n query SwitchboardIntrospection {\n __schema {\n queryType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n mutationType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n/**\n* Renders an introspected type reference as a GraphQL type string.\n* Recursion is bounded by the `ofType` nesting of the query, so it always\n* terminates.\n*/\nfunction renderTypeRef(type) {\n\tif (!type) return \"Unknown\";\n\tswitch (type.kind) {\n\t\tcase \"NON_NULL\": return `${renderTypeRef(type.ofType)}!`;\n\t\tcase \"LIST\": return `[${renderTypeRef(type.ofType)}]`;\n\t\tdefault: return type.name ?? \"Unknown\";\n\t}\n}\n/** Cap on the number of fields reported per root type. */\nconst MAX_FIELDS_PER_ROOT = 200;\nfunction summarizeFields(fields) {\n\tconst list = fields ?? [];\n\treturn {\n\t\tfields: list.slice(0, MAX_FIELDS_PER_ROOT).map((field) => ({\n\t\t\tname: field.name,\n\t\t\t...field.description ? { description: field.description } : {},\n\t\t\targs: field.args.map((arg) => `${arg.name}: ${renderTypeRef(arg.type)}`).join(\", \"),\n\t\t\treturns: renderTypeRef(field.type)\n\t\t})),\n\t\ttruncated: list.length > MAX_FIELDS_PER_ROOT\n\t};\n}\n/**\n* Reduces a GraphQL `__schema` introspection payload (the `data.__schema`\n* object) to a compact summary of its root query and mutation fields.\n* Accepts `unknown` because the payload arrives over the wire.\n*/\nfunction summarizeIntrospectionSchema(schema) {\n\tconst introspection = schema ?? {};\n\tconst queries = summarizeFields(introspection.queryType?.fields);\n\tconst mutations = summarizeFields(introspection.mutationType?.fields);\n\treturn {\n\t\tqueries: queries.fields,\n\t\tmutations: mutations.fields,\n\t\ttruncated: queries.truncated || mutations.truncated\n\t};\n}\nconst SWITCHBOARD_SCHEMA_TOOL_NAME = \"getSwitchboardSchema\";\n/**\n* Creates the read-only `getSwitchboardSchema` tool: it introspects the\n* GraphQL supergraph of the switchboard serving a drive and returns a\n* summary of its root queries and mutations. It reads the schema only and\n* never modifies data.\n*/\nfunction createSwitchboardSchemaTool(deps) {\n\tconst getSyncManager = deps?.getSyncManager ?? getBrowserSyncManager;\n\tconst getSelectedDriveId = deps?.getSelectedDriveId ?? (() => typeof window === \"undefined\" ? void 0 : window.ph?.selectedDriveId);\n\tconst tokenProvider = deps?.tokenProvider ?? ambientRenownTokenProvider;\n\tconst fetchImpl = deps?.fetchImpl ?? fetch;\n\tconst timeoutMs = deps?.timeoutMs ?? 1e4;\n\treturn {\n\t\tname: SWITCHBOARD_SCHEMA_TOOL_NAME,\n\t\tdescription: \"Introspect the GraphQL endpoint of the switchboard serving a drive and list the queries and mutations it exposes (reactor operations, document-model read models, package subgraphs). Read-only: it reads the schema only and never modifies data. Omit driveId to introspect the currently selected drive.\",\n\t\tinputSchema: { driveId: z.string().describe(\"Drive to introspect. Omit to use the currently selected drive.\").optional() },\n\t\tannotations: { readOnlyHint: true },\n\t\tcallback: async (input) => {\n\t\t\tconst driveId = input?.driveId ?? getSelectedDriveId();\n\t\t\tconst sb = resolveDriveSwitchboard(driveId, getSyncManager());\n\t\t\tif (!sb) throw new Error(driveId ? `Drive \"${driveId}\" has no switchboard: it is not synced to a remote switchboard.` : \"No drive is currently selected and no driveId was given.\");\n\t\t\tconst token = await tokenProvider();\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = await fetchImpl(sb.graphqlUrl, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t...token ? { authorization: `Bearer ${token}` } : {}\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify({ query: SWITCHBOARD_INTROSPECTION_QUERY }),\n\t\t\t\t\tsignal: AbortSignal.timeout(timeoutMs)\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Switchboard at ${sb.graphqlUrl} is not reachable: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n\t\t\t}\n\t\t\tif (response.status === 401 || response.status === 403) throw new Error(`Switchboard at ${sb.graphqlUrl} refused the request (HTTP ${response.status}). Sign in to the switchboard (Renown) and try again.`);\n\t\t\tif (!response.ok) throw new Error(`Switchboard introspection failed: HTTP ${response.status} ${response.statusText} from ${sb.graphqlUrl}`);\n\t\t\tconst body = await response.json();\n\t\t\tconst schemaErrors = body?.errors;\n\t\t\tif (schemaErrors && schemaErrors.length > 0) throw new Error(schemaErrors.map((e) => e.message ?? \"unknown error\").join(\"; \"));\n\t\t\tconst schema = body?.data?.__schema;\n\t\t\tif (!schema?.queryType) throw new Error(`Switchboard at ${sb.graphqlUrl} did not return a GraphQL schema.`);\n\t\t\tconst summary = summarizeIntrospectionSchema(schema);\n\t\t\treturn {\n\t\t\t\tswitchboardUrl: sb.switchboardUrl,\n\t\t\t\tgraphqlUrl: sb.graphqlUrl,\n\t\t\t\t...summary\n\t\t\t};\n\t\t}\n\t};\n}\n//#endregion\nexport { getBrowserSyncManager as a, useSelectedDocument as c, useSelectedDocumentSafe as d, useDocumentOfType as f, createSwitchboardSchemaTool as i, useSelectedDocumentId as l, SWITCHBOARD_INTROSPECTION_QUERY as n, resolveDriveSwitchboard as o, SWITCHBOARD_SCHEMA_TOOL_NAME as r, summarizeIntrospectionSchema as s, GQL_CHANNEL_SUFFIX as t, useSelectedDocumentOfType as u };\n\n//# sourceMappingURL=switchboard-CaXQ4-5Q.js.map","\nexport const normalizeDescriptors=(error)=>{\nCORE_ERROR_PROPS.forEach((propName)=>{\nnormalizeDescriptor(error,propName)\n})\n};\n\nexport const CORE_ERROR_PROPS=[\"name\",\"message\",\"stack\",\"cause\",\"errors\"];\n\nconst normalizeDescriptor=(error,propName)=>{\nconst descriptor=getDescriptor(error,propName);\n\nif(descriptor===undefined){\nreturn\n}\n\nif(isReadonlyGetter(descriptor)){\nsetErrorProperty(error,propName,error[propName]);\nreturn\n}\n\nif(isInvalidDescriptor(descriptor)){\nsetErrorDescriptor(error,propName,descriptor)\n}\n};\n\n\nexport const getDescriptor=(value,propName)=>{\nconst descriptor=Object.getOwnPropertyDescriptor(value,propName);\n\nif(descriptor!==undefined){\nreturn descriptor\n}\n\nconst prototype=Object.getPrototypeOf(value);\nreturn prototype===null?undefined:getDescriptor(prototype,propName)\n};\n\n\nconst isReadonlyGetter=({get,set})=>\nget!==undefined&&set===undefined;\n\nconst isInvalidDescriptor=({enumerable,writable})=>\nenumerable||!writable;\n\n\nexport const setErrorProperty=(error,propName,value)=>{\nsetErrorDescriptor(error,propName,{value})\n};\n\n\nconst setErrorDescriptor=(error,propName,descriptor)=>{\n\nObject.defineProperty(error,propName,{\n...descriptor,\n...(\"get\"in descriptor||\"set\"in descriptor?{}:{writable:true}),\nenumerable:false,\nconfigurable:true\n})\n};","import{setErrorProperty}from\"./descriptors.js\";\n\n\n\n\n\n\nexport const normalizeAggregate=(error,recurse)=>{\nif(Array.isArray(error.errors)){\nconst aggregateErrors=error.errors.\nfilter(isDefined).\nmap(recurse).\nfilter(Boolean);\nsetErrorProperty(error,\"errors\",aggregateErrors)\n}else if(isAggregateError(error)){\nsetErrorProperty(error,\"errors\",[])\n}else if(error.errors!==undefined){\ndeleteAggregateErrors(error)\n}\n};\n\nconst isDefined=(error)=>error!==undefined;\n\nconst isAggregateError=(error)=>\n\"AggregateError\"in globalThis&&(\nerror.name===\"AggregateError\"||error instanceof AggregateError);\n\nconst deleteAggregateErrors=(error)=>{\n\ndelete error.errors;\n\nif(error.errors!==undefined){\nsetErrorProperty(error,\"errors\",[])\n}\n};","import{setErrorProperty}from\"./descriptors.js\";\n\n\n\n\n\n\n\n\n\n\n\n\nexport const normalizeCause=(error,recurse)=>{\nif(!(\"cause\"in error)){\nreturn\n}\n\nconst cause=error.cause===undefined?error.cause:recurse(error.cause);\n\nif(cause===undefined){\n\ndelete error.cause\n}else{\nsetErrorProperty(error,\"cause\",cause)\n}\n};","\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst isErrorInstance=(value)=>\nisInstanceOfError(value)||hasErrorTag(value);\n\nexport default isErrorInstance;\n\n\n\nconst isInstanceOfError=(value)=>{\ntry{\nreturn value instanceof Error\n}catch{\nreturn false\n}\n};\n\nconst hasErrorTag=(value)=>{\ntry{\nreturn ERROR_TAGS.has(Object.prototype.toString.call(value))\n}catch{\nreturn false\n}\n};\n\nconst ERROR_TAGS=new Set([\n\n\"[object Error]\",\n\n\"[object DOMException]\",\n\n\"[object DOMError]\",\n\n\"[object Exception]\"]\n);","export default function isPlainObject(value) {\n\tif (typeof value !== 'object' || value === null) {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);\n}\n","import{CORE_ERROR_PROPS}from\"../descriptors.js\";\n\n\nexport const isNonModifiableError=(error)=>\n!Object.isExtensible(error)||\nCORE_ERROR_PROPS.some(\n(propName)=>\nisNonConfigurableProp(error,propName)||isThrowingProp(error,propName)\n);\n\n\n\nconst isNonConfigurableProp=(error,propName)=>{\nconst descriptor=Object.getOwnPropertyDescriptor(error,propName);\nreturn descriptor!==undefined&&!descriptor.configurable\n};\n\n\nconst isThrowingProp=(error,propName)=>{\ntry{\n\nerror[propName];\nreturn false\n}catch{\nreturn true\n}\n};","import{setErrorProperty}from\"./descriptors.js\";\n\n\n\n\n\n\n\n\n\n\nexport const setStack=(error)=>{\nconst stack=getStack(error.message,error.name);\nsetErrorProperty(error,\"stack\",stack)\n};\n\n\n\n\n\n\n\nconst getStack=(message=\"\",name=\"Error\")=>{\nconst StackError=getErrorClass(name);\nconst{stack}=new StackError(message);\nreturn typeof stack===\"string\"&&stack!==\"\"?\nstack:\n`${name}: ${message}`\n};\n\n\n\n\n\nconst getErrorClass=(name)=>{\nconst descriptor={\nvalue:name,\nenumerable:false,\nwritable:true,\nconfigurable:true\n};\n\nconst StackError=Object.defineProperty(\nclass extends Error{},\n\"name\",\ndescriptor\n);\n\nObject.defineProperty(StackError.prototype,\"name\",descriptor);\nreturn StackError\n};","import{CORE_ERROR_PROPS,getDescriptor}from\"../descriptors.js\";\n\n\n\n\nexport const copyObject=(object)=>{\nconst objectCopy={};\n\n\nfor(const propName of getPropsToCopy(object)){\n\ntry{\nconst value=object[propName];\nconst{\nenumerable,\nconfigurable,\nwritable=true\n}=getDescriptor(object,propName);\n\nObject.defineProperty(objectCopy,propName,{\nvalue,\nenumerable,\nconfigurable,\nwritable\n})\n}catch{}\n}\n\nreturn objectCopy\n};\n\n\n\n\n\nconst getPropsToCopy=(object)=>{\nconst propNames=getOwnKeys(object);\n\n\nfor(const propName of CORE_ERROR_PROPS){\n\nif(isInheritedProp(object,propName)){\n\npropNames.push(propName)\n}\n}\n\nreturn propNames\n};\n\n\nconst getOwnKeys=(object)=>{\ntry{\nreturn Reflect.ownKeys(object)\n}catch{\nreturn[]\n}\n};\n\n\nconst isInheritedProp=(object,propName)=>{\ntry{\nreturn propName in object&&!Object.hasOwn(object,propName)\n}catch{\nreturn false\n}\n};","import{setErrorProperty}from\"../descriptors.js\";\nimport{setStack}from\"../stack.js\";\n\nimport{copyObject}from\"./copy.js\";\n\n\nexport const objectifyError=(object)=>{\nconst{name,message,stack,cause,errors,...objectA}=copyObject(object);\nconst messageA=getMessage(message,objectA);\nconst error=newError(name,messageA);\n\nif(message===messageA){\nassignObjectProps(error,objectA)\n}\n\nObject.entries({name,stack,cause,errors}).forEach(\n([propName,propValue])=>{\nsetNewErrorProperty(error,propName,propValue)\n}\n);\n\nif(stack===undefined){\nsetStack(error)\n}\n\nreturn error\n};\n\n\nconst getMessage=(message,object)=>\ntypeof message===\"string\"&&message!==\"\"?\nmessage:\ntruncateMessage(safeJsonStringify(object));\n\nconst safeJsonStringify=(object)=>{\ntry{\nreturn JSON.stringify(object)\n}catch{\nreturn safeStringify(object)\n}\n};\n\nconst safeStringify=(object)=>{\ntry{\nreturn String(object)\n}catch{\nreturn\"Invalid error\"\n}\n};\n\nconst truncateMessage=(message)=>\nmessage.length<MESSAGE_MAX_SIZE?\nmessage:\n`${message.slice(0,MESSAGE_MAX_SIZE)}...`;\n\nconst MESSAGE_MAX_SIZE=1e3;\n\nconst newError=(name,message)=>{\nif(name===\"AggregateError\"&&\"AggregateError\"in globalThis){\nreturn new AggregateError([],message)\n}\n\nif(name in NATIVE_ERRORS){\nreturn new NATIVE_ERRORS[name](message)\n}\n\nreturn new Error(message)\n};\n\nconst NATIVE_ERRORS={\nError,\nReferenceError,\nTypeError,\nSyntaxError,\nRangeError,\nURIError,\nEvalError\n};\n\n\nconst assignObjectProps=(error,object)=>{\n\nfor(const propName in object){\n\nif(!(propName in error)){\nerror[propName]=object[propName]\n}\n}\n};\n\nconst setNewErrorProperty=(error,propName,propValue)=>{\nif(propValue!==undefined){\nsetErrorProperty(error,propName,propValue)\n}\n};","import{setStack}from\"../stack.js\";\n\n\nexport const stringifyError=(value)=>{\ntry{\nconst error=new Error(String(value));\nsetStack(error);\nreturn error\n}catch(error_){\nreturn error_\n}\n};","import isErrorInstance from\"is-error-instance\";\nimport isPlainObj from\"is-plain-obj\";\n\nimport{isNonModifiableError}from\"./modifiable.js\";\nimport{objectifyError}from\"./object.js\";\nimport{stringifyError}from\"./string.js\";\n\nconst{toString:objectToString}=Object.prototype;\n\n\nexport const createError=(value)=>{\nif(isErrorPlainObj(value)){\nreturn objectifyError(value)\n}\n\nif(!isErrorInstance(value)){\nreturn stringifyError(value)\n}\n\nif(isInvalidError(value)){\nreturn objectifyError(value)\n}\n\nreturn value\n};\n\n\nconst isErrorPlainObj=(value)=>{\ntry{\nreturn isPlainObj(value)\n}catch{\nreturn false\n}\n};\n\nconst isInvalidError=(value)=>\nisProxy(value)||isNonModifiableError(value)||hasInvalidConstructor(value);\n\n\n\n\nconst isProxy=(value)=>{\ntry{\nreturn objectToString.call(value)===\"[object Object]\"\n}catch{\nreturn true\n}\n};\n\n\n\nconst hasInvalidConstructor=(error)=>\ntypeof error.constructor!==\"function\"||\ntypeof error.constructor.name!==\"string\"||\nerror.constructor.name===\"\"||\nerror.constructor.prototype!==Object.getPrototypeOf(error);","import{normalizeAggregate}from\"./aggregate.js\";\nimport{normalizeCause}from\"./cause.js\";\nimport{createError}from\"./create/main.js\";\nimport{normalizeDescriptors,setErrorProperty}from\"./descriptors.js\";\nimport{setStack}from\"./stack.js\";\n\n\nconst normalizeException=(error,{shallow=false}={})=>\nrecurseException(error,[],shallow);\n\nexport default normalizeException;\n\nconst recurseException=(error,parents,shallow)=>{\nif(parents.includes(error)){\nreturn\n}\n\nconst recurse=shallow?\nidentity:\n(innerError)=>recurseException(innerError,[...parents,error],shallow);\n\nconst errorA=createError(error);\nnormalizeProps(errorA,recurse);\nreturn errorA\n};\n\nconst identity=(error)=>error;\n\nconst normalizeProps=(error,recurse)=>{\nnormalizeName(error);\nnormalizeMessage(error);\nnormalizeStack(error);\nnormalizeCause(error,recurse);\nnormalizeAggregate(error,recurse);\nnormalizeDescriptors(error)\n};\n\n\n\n\n\n\nconst normalizeName=(error)=>{\nif(isDefinedString(error.name)){\nreturn\n}\n\nconst prototypeName=Object.getPrototypeOf(error).name;\nconst name=isDefinedString(prototypeName)?\nprototypeName:\nerror.constructor.name;\nsetErrorProperty(error,\"name\",name)\n};\n\n\nconst normalizeMessage=(error)=>{\nif(!isDefinedString(error.message)){\nsetErrorProperty(error,\"message\",\"\")\n}\n};\n\n\nconst normalizeStack=(error)=>{\nif(!isDefinedString(error.stack)){\nsetStack(error)\n}\n};\n\nconst isDefinedString=(value)=>typeof value===\"string\"&&value!==\"\";","// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>\n// This work is free. You can redistribute it and/or modify it\n// under the terms of the WTFPL, Version 2\n// For more information see LICENSE.txt or http://www.wtfpl.net/\n//\n// For more information, the home page:\n// http://pieroxy.net/blog/pages/lz-string/testing.html\n//\n// LZ-based compression algorithm, version 1.4.5\nvar LZString = (function() {\n\n// private property\nvar f = String.fromCharCode;\nvar keyStrBase64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\nvar keyStrUriSafe = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$\";\nvar baseReverseDic = {};\n\nfunction getBaseValue(alphabet, character) {\n if (!baseReverseDic[alphabet]) {\n baseReverseDic[alphabet] = {};\n for (var i=0 ; i<alphabet.length ; i++) {\n baseReverseDic[alphabet][alphabet.charAt(i)] = i;\n }\n }\n return baseReverseDic[alphabet][character];\n}\n\nvar LZString = {\n compressToBase64 : function (input) {\n if (input == null) return \"\";\n var res = LZString._compress(input, 6, function(a){return keyStrBase64.charAt(a);});\n switch (res.length % 4) { // To produce valid Base64\n default: // When could this happen ?\n case 0 : return res;\n case 1 : return res+\"===\";\n case 2 : return res+\"==\";\n case 3 : return res+\"=\";\n }\n },\n\n decompressFromBase64 : function (input) {\n if (input == null) return \"\";\n if (input == \"\") return null;\n return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrBase64, input.charAt(index)); });\n },\n\n compressToUTF16 : function (input) {\n if (input == null) return \"\";\n return LZString._compress(input, 15, function(a){return f(a+32);}) + \" \";\n },\n\n decompressFromUTF16: function (compressed) {\n if (compressed == null) return \"\";\n if (compressed == \"\") return null;\n return LZString._decompress(compressed.length, 16384, function(index) { return compressed.charCodeAt(index) - 32; });\n },\n\n //compress into uint8array (UCS-2 big endian format)\n compressToUint8Array: function (uncompressed) {\n var compressed = LZString.compress(uncompressed);\n var buf=new Uint8Array(compressed.length*2); // 2 bytes per character\n\n for (var i=0, TotalLen=compressed.length; i<TotalLen; i++) {\n var current_value = compressed.charCodeAt(i);\n buf[i*2] = current_value >>> 8;\n buf[i*2+1] = current_value % 256;\n }\n return buf;\n },\n\n //decompress from uint8array (UCS-2 big endian format)\n decompressFromUint8Array:function (compressed) {\n if (compressed===null || compressed===undefined){\n return LZString.decompress(compressed);\n } else {\n var buf=new Array(compressed.length/2); // 2 bytes per character\n for (var i=0, TotalLen=buf.length; i<TotalLen; i++) {\n buf[i]=compressed[i*2]*256+compressed[i*2+1];\n }\n\n var result = [];\n buf.forEach(function (c) {\n result.push(f(c));\n });\n return LZString.decompress(result.join(''));\n\n }\n\n },\n\n\n //compress into a string that is already URI encoded\n compressToEncodedURIComponent: function (input) {\n if (input == null) return \"\";\n return LZString._compress(input, 6, function(a){return keyStrUriSafe.charAt(a);});\n },\n\n //decompress from an output of compressToEncodedURIComponent\n decompressFromEncodedURIComponent:function (input) {\n if (input == null) return \"\";\n if (input == \"\") return null;\n input = input.replace(/ /g, \"+\");\n return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrUriSafe, input.charAt(index)); });\n },\n\n compress: function (uncompressed) {\n return LZString._compress(uncompressed, 16, function(a){return f(a);});\n },\n _compress: function (uncompressed, bitsPerChar, getCharFromInt) {\n if (uncompressed == null) return \"\";\n var i, value,\n context_dictionary= {},\n context_dictionaryToCreate= {},\n context_c=\"\",\n context_wc=\"\",\n context_w=\"\",\n context_enlargeIn= 2, // Compensate for the first entry which should not count\n context_dictSize= 3,\n context_numBits= 2,\n context_data=[],\n context_data_val=0,\n context_data_position=0,\n ii;\n\n for (ii = 0; ii < uncompressed.length; ii += 1) {\n context_c = uncompressed.charAt(ii);\n if (!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)) {\n context_dictionary[context_c] = context_dictSize++;\n context_dictionaryToCreate[context_c] = true;\n }\n\n context_wc = context_w + context_c;\n if (Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)) {\n context_w = context_wc;\n } else {\n if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {\n if (context_w.charCodeAt(0)<256) {\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<8 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n } else {\n value = 1;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | value;\n if (context_data_position ==bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = 0;\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<16 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n delete context_dictionaryToCreate[context_w];\n } else {\n value = context_dictionary[context_w];\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n // Add wc to the dictionary.\n context_dictionary[context_wc] = context_dictSize++;\n context_w = String(context_c);\n }\n }\n\n // Output the code for w.\n if (context_w !== \"\") {\n if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {\n if (context_w.charCodeAt(0)<256) {\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<8 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n } else {\n value = 1;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | value;\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = 0;\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<16 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n delete context_dictionaryToCreate[context_w];\n } else {\n value = context_dictionary[context_w];\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n }\n\n // Mark the end of the stream\n value = 2;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n // Flush the last char\n while (true) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data.push(getCharFromInt(context_data_val));\n break;\n }\n else context_data_position++;\n }\n return context_data.join('');\n },\n\n decompress: function (compressed) {\n if (compressed == null) return \"\";\n if (compressed == \"\") return null;\n return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); });\n },\n\n _decompress: function (length, resetValue, getNextValue) {\n var dictionary = [],\n next,\n enlargeIn = 4,\n dictSize = 4,\n numBits = 3,\n entry = \"\",\n result = [],\n i,\n w,\n bits, resb, maxpower, power,\n c,\n data = {val:getNextValue(0), position:resetValue, index:1};\n\n for (i = 0; i < 3; i += 1) {\n dictionary[i] = i;\n }\n\n bits = 0;\n maxpower = Math.pow(2,2);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n switch (next = bits) {\n case 0:\n bits = 0;\n maxpower = Math.pow(2,8);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n c = f(bits);\n break;\n case 1:\n bits = 0;\n maxpower = Math.pow(2,16);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n c = f(bits);\n break;\n case 2:\n return \"\";\n }\n dictionary[3] = c;\n w = c;\n result.push(c);\n while (true) {\n if (data.index > length) {\n return \"\";\n }\n\n bits = 0;\n maxpower = Math.pow(2,numBits);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n switch (c = bits) {\n case 0:\n bits = 0;\n maxpower = Math.pow(2,8);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n dictionary[dictSize++] = f(bits);\n c = dictSize-1;\n enlargeIn--;\n break;\n case 1:\n bits = 0;\n maxpower = Math.pow(2,16);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n dictionary[dictSize++] = f(bits);\n c = dictSize-1;\n enlargeIn--;\n break;\n case 2:\n return result.join('');\n }\n\n if (enlargeIn == 0) {\n enlargeIn = Math.pow(2, numBits);\n numBits++;\n }\n\n if (dictionary[c]) {\n entry = dictionary[c];\n } else {\n if (c === dictSize) {\n entry = w + w.charAt(0);\n } else {\n return null;\n }\n }\n result.push(entry);\n\n // Add w+entry[0] to the dictionary.\n dictionary[dictSize++] = w + entry.charAt(0);\n enlargeIn--;\n\n w = entry;\n\n if (enlargeIn == 0) {\n enlargeIn = Math.pow(2, numBits);\n numBits++;\n }\n\n }\n }\n};\n return LZString;\n})();\n\nif (typeof define === 'function' && define.amd) {\n define(function () { return LZString; });\n} else if( typeof module !== 'undefined' && module != null ) {\n module.exports = LZString\n} else if( typeof angular !== 'undefined' && angular != null ) {\n angular.module('LZString', [])\n .factory('LZString', function () {\n return LZString;\n });\n}\n","import { a as setDocumentCache, c as useDocumentSafe, d as useGetDocumentAsync, f as useGetDocuments, h as readPromiseState, i as addDocumentCacheEventHandler, l as useDocuments, m as addPromiseState, n as useDocumentsByIds, o as useDocument, p as DocumentCache, r as useDispatch, s as useDocumentCache, t as useDocumentById, u as useGetDocument, y as dispatchActions } from \"./document-by-id-B4FIzG1w.js\";\nimport { A as createUrlWithPreservedParams, B as makeNodeSlug, C as addResetSelectedNodeEventHandler, D as addDrivesEventHandler, E as setSelectedNode, F as extractNodeIdFromSlug, G as UnsupportedDocumentTypeError, H as DocumentModelNotFoundError, I as extractNodeSlugFromPath, K as ambientRenownTokenProvider, L as findUuid, M as extractDriveIdFromSlug, N as extractDriveSlugFromPath, O as setDrives, P as extractNodeIdFromPath, R as getPathWithoutBase, S as useSelectedDriveSafe, T as addSetSelectedNodeOnPopStateEventHandler, U as DocumentTypeMismatchError, V as resolveUrlPathname, W as NoSelectedDocumentError, _ as addSetSelectedDriveOnPopStateEventHandler, a as useVetraPackageManager, b as useSelectedDrive, c as useDocumentTypesInSelectedDrive, d as useFolderNodesInSelectedDrive, f as useNodesInSelectedDrive, g as addSelectedDriveIdEventHandler, h as sortNodesByName, i as setVetraPackageManager, j as extractDriveIdFromPath, k as useDrives, l as useDocumentsInSelectedDrive, m as isFolderNodeKind, n as useDocumentModelModules, o as useVetraPackages, p as isFileNodeKind, q as makeAuthMiddleware, r as addVetraPackageManagerEventHandler, s as useSelectedNode, t as useDocumentModelModuleById, u as useFileNodesInSelectedDrive, v as setSelectedDrive, w as addSelectedNodeIdEventHandler, x as useSelectedDriveId, y as setSelectedDriveId, z as makeDriveUrlComponent } from \"./document-model-modules-bTP87nyr.js\";\nimport { t as makePHEventFunctions } from \"./make-ph-event-functions-DBq3iWYn.js\";\nimport { $ as addDefaultDrivesUrlEventHandler, $n as useIsAddLocalDrivesEnabled, $r as isAuthRefusalClose, $t as setEnabledEditors, A as useReactorClientModule, Ai as fetchDocumentOperations, An as setRenownUrl, Ar as useSentryRelease, At as addRenownAdaptersEventHandler, B as useDragNode, Bi as addModalEventHandler, Bn as setWarnOutdatedApp, Br as phAppConfigHooks, Bt as addSwitchboardUrlEventHandler, C as addReactorClientModuleEventHandler, Ci as addDocument, Cn as setIsRelationalProcessorsEnabled, Cr as useRenownChainId, Ct as addIsExternalRelationalProcessorsEnabledEventHandler, D as useModelRegistry, Di as deleteNode, Dn as setRenownAdapters, Dr as useRouterBasename, Dt as addIsSentryTracingEnabledEventHandler, E as useDatabase, Ei as copyNode$1, En as setLogLevel, Er as useRequiresHardRefresh, Et as addIsRelationalProcessorsEnabledEventHandler, F as usePackageDiscoveryService, Fi as renameNode, Fn as setSentryRelease, Fr as useWarnOutdatedApp, Ft as addRouterBasenameEventHandler, G as useFeatures, Gi as showPHModal, Gn as useDefaultDrivesUrl, Gr as setIsDragAndDropEnabled, Gt as phGlobalConfigSetters, H as useDropTarget, Hi as setPHModal, Hn as useAnalyticsDatabaseName, Hr as phDocumentEditorConfigHooks, Ht as addVersionEventHandler, I as addGraphQLReactorClientEventHandler, Ii as setPreferredEditorOnNode, In as setStudioMode, Ir as addAllowedDocumentTypesEventHandler, It as addSentryDsnEventHandler, J as useAttachmentService, Jn as useEnabledEditors, Jr as useIsDragAndDropEnabled, Jt as setBasePath, K as addAttachmentServiceEventHandler, Ki as usePHModal, Kn as useDisabledEditors, Kr as setIsExternalControlsEnabled, Kt as setAllowList, L as setGraphQLReactorClient, Li as upgradeDocument, Ln as setSwitchboardUrl, Lr as addIsDragAndDropEnabledEventHandler, Lt as addSentryEnvEventHandler, M as useSyncList, Mi as loadFile, Mn as setRouterBasename, Mr as useSwitchboardUrl, Mt as addRenownNetworkIdEventHandler, N as addPackageDiscoveryServiceEventHandler, Ni as moveNode$1, Nn as setSentryDsn, Nr as useVersion, Nt as addRenownUrlEventHandler, O as usePGlite, Oi as exportFile, On as setRenownChainId, Or as useSentryDsn, Ot as addLocalDrivesEnabledEventHandler, P as setPackageDiscoveryService, Pi as renameDriveNode, Pn as setSentryEnv, Pr as useVersionCheckInterval, Pt as addRequiresHardRefreshEventHandler, Q as addCliVersionEventHandler, Qn as useIsAddDriveEnabled, Qr as viewFilterInputFromViewFilter, Qt as setDrivesPreserveStrategy, R as useGraphQLReactorClient, Ri as getUserPermissions, Rn as setVersion, Rr as addIsExternalControlsEnabledEventHandler, Rt as addSentryReleaseEventHandler, S as addReactorClientEventHandler, Si as screamingSnakeToCamel, Sn as setIsPublicDrivesEnabled, Sr as useRenownAdapters, St as addIsExternalProcessorsEnabledEventHandler, T as setReactorClientModule, Ti as addFolder, Tn as setLocalDrivesEnabled, Tr as useRenownUrl, Tt as addIsPublicDrivesEnabledEventHandler, U as addFeaturesEventHandler, Ui as showCreateDocumentModal, Un as useBasePath, Ur as phDocumentEditorConfigSetters, Ut as addWarnOutdatedAppEventHandler, V as useDropNode, Vi as closePHModal, Vn as useAllowList, Vr as phAppConfigSetters, Vt as addVersionCheckIntervalEventHandler, W as setFeatures, Wi as showDeleteNodeModal, Wn as useCliVersion, Wr as setAllowedDocumentTypes, Wt as phGlobalConfigHooks, X as addAnalyticsDatabaseNameEventHandler, Xn as useGaTrackingId, Xr as GraphQLReactorClient, Xt as setDefaultDrivesUrl, Y as addAllowListEventHandler, Yn as useFileUploadOperationsChunkSize, Yr as useIsExternalControlsEnabled, Yt as setCliVersion, Z as addBasePathEventHandler, Zn as useIsAddCloudDrivesEnabled, Zr as isGraphQLReactorClient, Zt as setDisabledEditors, _ as addRevisionHistoryVisibleEventHandler, _i as ConflictError, _n as setIsEditorReadModeEnabled, _r as useIsPublicDrivesEnabled, _t as addIsDocumentModelSelectionSettingsEnabledEventHandler, a as addPHEventHandlers, ai as subgraphUrlFromGraphqlUrl, an as setIsAddPublicDrivesEnabled, ar as useIsDeleteCloudDrivesEnabled, at as addIsAddCloudDrivesEnabledEventHandler, b as showRevisionHistory, bi as extractRevisionMap, bn as setIsExternalRelationalProcessorsEnabled, br as useLocalDrivesEnabled, bt as addIsEditorReadModeEnabledEventHandler, c as addToastEventHandler, ci as resolveDocumentModelModule, cn as setIsAnalyticsExternalProcessorsEnabled, cr as useIsDiffAnalyticsEnabled, ct as addIsAddPublicDrivesEnabledEventHandler, d as addSelectedTimelineRevisionEventHandler, di as stampAction, dn as setIsDeleteLocalDrivesEnabled, dr as useIsEditorDebugModeEnabled, dt as addIsAnalyticsExternalProcessorsEnabledEventHandler, ei as makeAuthConnectionParams, en as setFileUploadOperationsChunkSize, er as useIsAddPublicDrivesEnabled, et as addDisabledEditorsEventHandler, f as setSelectedTimelineRevision, fi as MutateDocumentWithOperationsDocument, fn as setIsDeletePublicDrivesEnabled, fr as useIsEditorReadModeEnabled, ft as addIsCloudDrivesEnabledEventHandler, g as useSelectedTimelineItem, gi as revisionMapFromRevisionsList, gn as setIsEditorDebugModeEnabled, gr as useIsLocalDrivesEnabled, gt as addIsDiffAnalyticsEnabledEventHandler, h as setSelectedTimelineItem, hi as phDocumentFromMutation, hn as setIsDriveAnalyticsEnabled, hr as useIsExternalRelationalProcessorsEnabled, ht as addIsDeletePublicDrivesEnabledEventHandler, i as useSwitchboardClient, ii as describeGraphQLDocument, in as setIsAddLocalDrivesEnabled, ir as useIsCloudDrivesEnabled, it as addGaTrackingIdEventHandler, j as useSync, ji as getDocumentExtension, jn as setRequiresHardRefresh, jr as useStudioMode, jt as addRenownChainIdEventHandler, k as useReactorClient, ki as extractInitialState, kn as setRenownNetworkId, kr as useSentryEnv, kt as addLogLevelEventHandler, l as setPHToast, li as prepareSignedActions, ln as setIsCloudDrivesEnabled, lr as useIsDocumentModelSelectionSettingsEnabled, lt as addIsAnalyticsDatabaseWorkerEnabledEventHandler, m as addSelectedTimelineItemEventHandler, mi as phDocumentFromGetDocument, mn as setIsDocumentModelSelectionSettingsEnabled, mr as useIsExternalProcessorsEnabled, mt as addIsDeleteLocalDrivesEnabledEventHandler, n as GraphQLReactorProvider, ni as subscriptionsUrlFromGraphqlUrl, nn as setIsAddCloudDrivesEnabled, nr as useIsAnalyticsEnabled, nt as addEnabledEditorsEventHandler, o as callEventHandlerRegisterFunctions, oi as StaticPackageManager, on as setIsAnalyticsDatabaseWorkerEnabled, or as useIsDeleteLocalDrivesEnabled, ot as addIsAddDriveEnabledEventHandler, p as useSelectedTimelineRevision, pi as ReactorOperationFieldsFragmentDoc, pn as setIsDiffAnalyticsEnabled, pr as useIsExternalPackagesEnabled, pt as addIsDeleteCloudDrivesEnabledEventHandler, q as setAttachmentService, qn as useDrivesPreserveStrategy, qr as useAllowedDocumentTypes, qt as setAnalyticsDatabaseName, r as ensurePHEventHandlers, ri as SubgraphSdkRegistry, rn as setIsAddDriveEnabled, rr as useIsAnalyticsExternalProcessorsEnabled, rt as addFileUploadOperationsChunkSizeEventHandler, s as commonGlobalEventHandlerFunctions, si as packageFromDocumentModels, sn as setIsAnalyticsEnabled, sr as useIsDeletePublicDrivesEnabled, st as addIsAddLocalDrivesEnabledEventHandler, t as useDocumentOperations, ti as startDocumentChangesSubscription, tn as setGaTrackingId, tr as useIsAnalyticsDatabaseWorkerEnabled, tt as addDrivesPreserveStrategyEventHandler, u as usePHToast, ui as signStampedAction, un as setIsDeleteCloudDrivesEnabled, ur as useIsDriveAnalyticsEnabled, ut as addIsAnalyticsEnabledEventHandler, v as hideRevisionHistory, vi as buildPulledDocument, vn as setIsExternalPackagesEnabled, vr as useIsRelationalProcessorsEnabled, vt as addIsDriveAnalyticsEnabledEventHandler, w as setReactorClient, wi as addFileWithProgress, wn as setIsSentryTracingEnabled, wr as useRenownNetworkId, wt as addIsLocalDrivesEnabledEventHandler, x as useRevisionHistoryVisible, xi as hasRevisionConflict, xn as setIsLocalDrivesEnabled, xr as useLogLevel, xt as addIsExternalPackagesEnabledEventHandler, y as setRevisionHistoryVisible, yi as convertRemoteOperations, yn as setIsExternalProcessorsEnabled, yr as useIsSentryTracingEnabled, yt as addIsEditorDebugModeEnabledEventHandler, z as addDraggingNodeEventHandler, zi as isDocumentTypeSupported, zn as setVersionCheckInterval, zr as isExternalControlsEnabledEventFunctions, zt as addStudioModeEventHandler } from \"./document-operations-WeE6wIDt.js\";\nimport { a as setGlobal, i as getGlobal, n as getAnalyticsStore, r as clearGlobal, t as createAnalyticsStore } from \"./store-BJYcr_FL.js\";\nimport { baseDocumentModels, baseDocumentModelsMap } from \"./src/document-model.js\";\nimport { i as GetDocumentWithOperationsDocument, o as PropagationMode, t as createClient } from \"./client-D66jVnot.js\";\nimport { a as useRenown, c as RENOWN_INITIAL_UNKNOWN, d as useRenownInitialUser, f as addLoadingEventHandler, h as useLoading, i as useLoginStatus, l as RenownInitialUserProvider, m as setLoading, n as setRenown, o as useUser, p as loading, r as useDid, s as RENOWN_INITIAL_ANONYMOUS, t as addRenownEventHandler, u as useRenownInitialAuth } from \"./renown-BHxwP7xU.js\";\nimport { A as RENOWN_CHAIN_ID, C as logout, D as CREDENTIAL_TYPES, E as CREDENTIAL_SUBJECT_TYPE, M as RENOWN_RETURN_URL_STRIPPED_PARAMS, N as RENOWN_URL, O as DOMAIN_TYPE, P as VERIFIABLE_CREDENTIAL_EIP712_TYPE, S as login, T as CREDENTIAL_SCHEMA_EIP712_TYPE, _ as RenownLogo, a as Renown, b as useRenownAuth, c as useRenownSessionSynced, d as RenownAuthButton, f as RenownUserButton, g as DisconnectIcon, h as CopyIcon, i as RenownWalletProvider, j as RENOWN_NETWORK_ID, k as ISSUER_TYPE, l as initConnectCrypto, m as ChevronDownIcon, n as useRenownLoginMethods, o as useRenownInit, p as RenownLoginButton, r as RenownProvider, s as useRenownSessionCookie, t as useRenownWalletAdapter, u as initRenownCrypto, v as SpinnerIcon, w as openRenown, x as useRenownAuthAsync, y as UserIcon } from \"./renown-rqK8sokh.js\";\nimport { c as useSelectedDocument, d as useSelectedDocumentSafe, f as useDocumentOfType, l as useSelectedDocumentId, t as GQL_CHANNEL_SUFFIX, u as useSelectedDocumentOfType } from \"./switchboard-CaXQ4-5Q.js\";\nimport { i as setPGliteDB, n as useRelationalQuery, r as useRelationalDb, t as createProcessorQuery } from \"./relational-D1RB45sA.js\";\nimport { a as getPackagesByDocumentType, i as getPackages, n as getPackageInfo, o as getPackagesForDocumentType, r as getPackagePage, s as trimTrailingSlash, t as RegistryClient } from \"./client-DjK30EQ-.js\";\nimport { createZip, isDocumentZip, parseBulkArchive, toTransportAction, validateInitialState, validateModules, validateStateSchemaName, zipEntries } from \"@powerhousedao/shared/document-model\";\nimport { AuthEnforcementDisabledError, ChannelScheme, DocumentChangeType, DocumentChangeType as DocumentChangeType$1, DocumentIntegrityService, DriveCollectionId, DriveCollectionId as DriveCollectionId$1, DriveRequestError, GqlRequestChannel, InMemoryQueue, IntervalPollTimer, PollBehavior, PropagationMode as PropagationMode$1, REACTOR_SCHEMA, REACTOR_SCHEMA as REACTOR_SCHEMA$1, ReactorBuilder, ReactorClientBuilder, RelationalDbProcessor, SyncOperationStatus, SyncStatus, driveIdFromUrl, isDriveAuthError, isDriveAuthError as isDriveAuthError$1, parseDriveUrl } from \"@powerhousedao/reactor\";\nimport { DriveDocumentSchema, driveCreateDocument, getDescendants, getNextCopyNumber, isFileNode, isFolderNode, setAvailableOffline, setDriveIcon, setDriveName, setSharingType } from \"@powerhousedao/shared/document-drive\";\nimport { allPass, filter, find, forEach, funnel, hasAtLeast, isArray, isDefined, isIncludedIn, isStrictEqual, isTruthy, last, map, mapToObj, once, pipe, prop, split, unique } from \"remeda\";\nimport { pascalCase } from \"change-case\";\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { Kind, parse } from \"graphql\";\nimport { z } from \"zod\";\nimport normalizeException from \"normalize-exception\";\nimport lzString from \"lz-string\";\nimport { createAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\n//#region src/actions/drive-info.ts\n/**\n* Reads a drive's info from a switchboard's REST endpoint.\n*\n* Drive discovery is the one read a client makes before it can authenticate\n* anything else: `graphqlEndpoint` is what the sync remote is registered with,\n* so nothing authenticated can happen until this call returns. That makes it\n* the one request most likely to be sent logged-out — and it is exactly the\n* call that must NOT be, because a switchboard running\n* `DOCUMENT_PERMISSIONS` refuses a protected drive to an anonymous caller\n* even when the logged-in user holds a grant on it.\n*\n* So the token goes out whenever there is one, with no `if (user)` guard: the\n* provider already answers `undefined` when logged out, and an open\n* switchboard serves that anonymously exactly as before.\n*\n* A failure throws `DriveRequestError` carrying the status, so\n* `isDriveAuthError` can tell a refusal from an unreachable host and the\n* caller can prompt for a login instead of reporting a network fault.\n*/\nasync function fetchDriveInfo(url) {\n\tconst token = await ambientRenownTokenProvider();\n\tconst response = await fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {} });\n\tif (!response.ok) throw new DriveRequestError(`Failed to resolve drive info from ${url}: HTTP ${response.status}`, response.status);\n\treturn await response.json();\n}\n//#endregion\n//#region src/actions/bulk-archive.ts\n/**\n* Expand a dropped file into import jobs. A single-document zip is passed\n* through unchanged. A bulk archive (a zip whose tree of files are\n* single-document zips) has its top-level folder — and subfolders —\n* recreated under `targetParent` (existing same-named folders are reused),\n* and each leaf becomes one job targeting its recreated folder. Throws\n* without touching the drive when no leaf is a document zip.\n*/\nasync function expandBulkArchive(file, driveId, targetParent) {\n\tconst data = new Uint8Array(await file.arrayBuffer());\n\tif (await isDocumentZip(data)) return [{\n\t\tfile,\n\t\tparent: targetParent\n\t}];\n\tconst entries = await parseBulkArchive(data);\n\tif (!(await Promise.all(entries.map((entry) => isDocumentZip(entry.data)))).some(Boolean)) throw new Error(\"Archive contains no Powerhouse documents\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst knownNodes = [...(await reactorClient.get(driveId)).state.global.nodes];\n\tconst dirToNode = /* @__PURE__ */ new Map();\n\tconst ensureDir = async (dirPath, parent) => {\n\t\tconst cached = dirToNode.get(dirPath);\n\t\tif (cached) return cached;\n\t\tconst name = dirPath.split(\"/\").pop() ?? dirPath;\n\t\tconst node = knownNodes.find((n) => isFolderNode(n) && n.name === name && (n.parentFolder ?? null) === (parent?.id ?? null)) ?? await addFolder(driveId, name, parent?.id);\n\t\tdirToNode.set(dirPath, node);\n\t\tknownNodes.push(node);\n\t\treturn node;\n\t};\n\tconst jobs = [];\n\tfor (const entry of entries) {\n\t\tconst segments = entry.path.split(\"/\");\n\t\tconst leaf = segments.pop();\n\t\tlet parent = targetParent;\n\t\tlet prefix = \"\";\n\t\tfor (const segment of segments) {\n\t\t\tprefix = prefix ? `${prefix}/${segment}` : segment;\n\t\t\tparent = await ensureDir(prefix, parent);\n\t\t}\n\t\tjobs.push({\n\t\t\tfile: new File([new Uint8Array(entry.data)], leaf),\n\t\t\tparent\n\t\t});\n\t}\n\treturn jobs;\n}\n//#endregion\n//#region src/actions/folder-zip.ts\nconst sanitize = (segment) => segment.replace(/\\//g, \"-\");\n/**\n* Name segments from the exported folder (exclusive) down to `node`\n* (inclusive), in top-down order. `root === undefined` means the drive root:\n* all ancestors. A node that IS the exported folder yields no segments.\n*/\nfunction segmentsBelow(root, node, allNodes) {\n\tconst segments = [];\n\tlet current = node;\n\twhile (current && current.id !== root?.id) {\n\t\tsegments.push(sanitize(current.name));\n\t\tconst parentId = current.parentFolder;\n\t\tcurrent = parentId ? allNodes.find((n) => n.id === parentId) : void 0;\n\t}\n\treturn segments.reverse();\n}\n/**\n* Assemble the archive zip for a folder (or the whole drive when\n* `folderNode` is undefined). Every folder in the subtree becomes a\n* directory entry (empty folders survive); every file becomes a standard\n* single-document zip named after the node (drive naming convention:\n* `${name}.${extension}.phd`, ` (copy) N` on a same-folder collision).\n*\n* `fetchDocument` must return the document WITH its full operations and\n* initialState (see downloadFolderZip).\n*/\nasync function buildFolderZip(drive, folderNode, fetchDocument, onProgress) {\n\tconst allNodes = drive.state.global.nodes;\n\tconst topName = sanitize(folderNode?.name ?? (drive.state.global.name || drive.header.name));\n\tconst subtree = folderNode ? [folderNode, ...getDescendants(folderNode, allNodes)] : allNodes;\n\tconst entries = { [topName + \"/\"]: new Uint8Array(0) };\n\tfor (const node of subtree) {\n\t\tif (!isFolderNode(node)) continue;\n\t\tconst dir = [topName, ...segmentsBelow(folderNode, node, allNodes)].join(\"/\");\n\t\tentries[dir + \"/\"] = new Uint8Array(0);\n\t}\n\tconst files = subtree.filter(isFileNode);\n\tconst failed = [];\n\tconst usedNamesByDir = /* @__PURE__ */ new Map();\n\tlet done = 0;\n\tfor (const node of files) try {\n\t\tconst doc = await fetchDocument(node.id);\n\t\tconst extension = await getDocumentExtension(doc);\n\t\tconst parent = node.parentFolder ? allNodes.find((n) => n.id === node.parentFolder) : void 0;\n\t\tconst dir = [topName, ...parent ? segmentsBelow(folderNode, parent, allNodes) : []].join(\"/\");\n\t\tlet usedNames = usedNamesByDir.get(dir);\n\t\tif (!usedNames) {\n\t\t\tusedNames = /* @__PURE__ */ new Set();\n\t\t\tusedNamesByDir.set(dir, usedNames);\n\t\t}\n\t\tconst base = sanitize(node.name);\n\t\tlet candidate = base;\n\t\tlet count = getNextCopyNumber([...usedNames], base);\n\t\twhile (usedNames.has(candidate)) {\n\t\t\tcandidate = `${base} (copy) ${count}`;\n\t\t\tcount += 1;\n\t\t}\n\t\tusedNames.add(candidate);\n\t\tconst leaf = extension ? `${candidate}.${extension}.phd` : `${candidate}.phd`;\n\t\tentries[`${dir}/${leaf}`] = await createZip(doc);\n\t} catch {\n\t\tfailed.push(node.name);\n\t} finally {\n\t\tdone += 1;\n\t\tonProgress?.(done, files.length);\n\t}\n\treturn {\n\t\tzip: await zipEntries(entries),\n\t\tarchiveName: `${topName}.zip`,\n\t\tentryCount: files.length - failed.length,\n\t\tfailed\n\t};\n}\n/**\n* Export a folder (or whole drive) to disk: fetches every document with its\n* full operation history, builds the archive, and saves it via\n* showSaveFilePicker (fallback: blob download), mirroring exportFile.\n*/\nasync function downloadFolderZip(drive, folderNode, onProgress) {\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst result = await buildFolderZip(drive, folderNode, async (id) => {\n\t\tconst doc = await reactorClient.get(id);\n\t\tconst operations = await fetchDocumentOperations(reactorClient, doc);\n\t\tconst initialState = extractInitialState(operations[\"document\"] ?? []);\n\t\treturn {\n\t\t\t...doc,\n\t\t\toperations,\n\t\t\tinitialState\n\t\t};\n\t}, onProgress);\n\tif (!window.showSaveFilePicker) {\n\t\tconst blob = new Blob([new Uint8Array(result.zip)], { type: \"application/zip\" });\n\t\tconst link = window.document.createElement(\"a\");\n\t\tlink.style.display = \"none\";\n\t\tlink.href = URL.createObjectURL(blob);\n\t\tlink.download = result.archiveName;\n\t\twindow.document.body.appendChild(link);\n\t\tlink.click();\n\t\twindow.document.body.removeChild(link);\n\t\treturn result;\n\t}\n\ttry {\n\t\tconst writable = await (await window.showSaveFilePicker({ suggestedName: result.archiveName })).createWritable();\n\t\tawait writable.write(new Uint8Array(result.zip));\n\t\tawait writable.close();\n\t} catch (e) {\n\t\tif (!(e instanceof DOMException && e.name === \"AbortError\")) throw e;\n\t}\n\treturn result;\n}\n//#endregion\n//#region src/actions/drive.ts\nconst DEFAULT_INITIAL_SYNC_TIMEOUT_MS = 3e4;\nconst inFlightRemoteRegistrations = /* @__PURE__ */ new Map();\n/**\n* Resolves once a document with the given id is queryable through the\n* reactor client. Subscribes to Created events filtered by id and\n* short-circuits if the document already exists.\n*/\nasync function waitForDocumentReady(reactorClient, documentId, options) {\n\tconst timeoutMs = options?.timeoutMs ?? DEFAULT_INITIAL_SYNC_TIMEOUT_MS;\n\tconst signal = options?.signal;\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet unsubscribe;\n\t\tlet timer;\n\t\tlet abortHandler;\n\t\tconst settle = (action) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tunsubscribe?.();\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n\t\t\taction();\n\t\t};\n\t\tunsubscribe = reactorClient.subscribe({ ids: [documentId] }, (event) => {\n\t\t\tif (event.type === DocumentChangeType$1.Created) settle(() => resolve());\n\t\t});\n\t\treactorClient.find({ ids: [documentId] }).then((existing) => {\n\t\t\tif (existing.results.length > 0) settle(() => resolve());\n\t\t}).catch(() => {});\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tsettle(() => reject(new DOMException(\"Aborted\", \"AbortError\")));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tabortHandler = () => {\n\t\t\t\tsettle(() => reject(new DOMException(\"Aborted\", \"AbortError\")));\n\t\t\t};\n\t\t\tsignal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\t\ttimer = setTimeout(() => {\n\t\t\tsettle(() => reject(/* @__PURE__ */ new Error(`Timed out after ${timeoutMs}ms waiting for document ${documentId}`)));\n\t\t}, timeoutMs);\n\t});\n}\nasync function addDrive(input, preferredEditor) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to create drives\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst driveDoc = driveCreateDocument({ global: {\n\t\tname: input.global.name || \"\",\n\t\ticon: input.global.icon ?? null,\n\t\tnodes: []\n\t} });\n\tif (input.id) driveDoc.header.id = input.id;\n\tif (preferredEditor) driveDoc.header.meta = { preferredEditor };\n\treturn await reactorClient.create(driveDoc);\n}\nasync function addRemoteDrive(url, driveId, options) {\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n\tif (!sync) throw new Error(\"Sync not initialized\");\n\tlet driveInfo;\n\ttry {\n\t\tdriveInfo = await fetchDriveInfo(url);\n\t} catch (error) {\n\t\tif (isDriveAuthError$1(error)) showPHModal({ type: \"driveAuthRequired\" });\n\t\tthrow error;\n\t}\n\tconst resolvedDriveId = driveId ?? driveInfo.id;\n\tconst collectionId = DriveCollectionId$1.forDrive(resolvedDriveId);\n\tconst inFlight = inFlightRemoteRegistrations.get(collectionId.key);\n\ttry {\n\t\tif (inFlight) await inFlight;\n\t\telse if (!sync.list().find((remote) => remote.meta.collectionId.equals(collectionId))) {\n\t\t\tconst remoteName = crypto.randomUUID();\n\t\t\tconst registration = sync.add(remoteName, collectionId, {\n\t\t\t\ttype: \"gql\",\n\t\t\t\tparameters: { url: driveInfo.graphqlEndpoint }\n\t\t\t}, void 0, options?.pollBehavior ? { pollBehavior: options.pollBehavior } : void 0).finally(() => inFlightRemoteRegistrations.delete(collectionId.key));\n\t\t\tinFlightRemoteRegistrations.set(collectionId.key, registration);\n\t\t\tawait registration;\n\t\t}\n\t} catch (error) {\n\t\tif (isDriveAuthError$1(error)) showPHModal({ type: \"driveAuthRequired\" });\n\t\tthrow error;\n\t}\n\tif (options?.awaitInitialSync) await waitForDocumentReady(reactorClient, resolvedDriveId, {\n\t\ttimeoutMs: options.initialSyncTimeoutMs,\n\t\tsignal: options.signal\n\t});\n\treturn resolvedDriveId;\n}\nasync function deleteDrive(driveId) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to delete drives\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst sync = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n\tif (sync) {\n\t\tconst collectionId = DriveCollectionId$1.forDrive(driveId);\n\t\tconst remotes = sync.list().filter((remote) => remote.meta.collectionId.equals(collectionId));\n\t\tfor (const remote of remotes) await sync.remove(remote.meta.name);\n\t}\n\tawait reactorClient.deleteDocument(driveId, PropagationMode$1.Cascade);\n}\nasync function renameDrive(driveId, name) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to rename drives\");\n\tconst reactorClient = window.ph?.reactorClientModule?.client;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.rename(driveId, name);\n}\nasync function setDriveAvailableOffline(driveId, availableOffline) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to change drive availability\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(driveId, \"main\", [setAvailableOffline({ availableOffline })]);\n}\nasync function setDriveSharingType(driveId, sharingType) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to change drive sharing type\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\treturn await reactorClient.execute(driveId, \"main\", [setSharingType({ type: sharingType })]);\n}\nasync function setDriveMetadata(driveId, metadata) {\n\tconst { isAllowedToCreateDocuments } = getUserPermissions();\n\tif (!isAllowedToCreateDocuments) throw new Error(\"User is not allowed to update drive metadata\");\n\tconst reactorClient = window.ph?.reactorClient;\n\tif (!reactorClient) throw new Error(\"ReactorClient not initialized\");\n\tconst actions = [];\n\tif (metadata.name) actions.push(setDriveName({ name: metadata.name }));\n\tif (metadata.icon !== void 0) actions.push(setDriveIcon({ icon: metadata.icon }));\n\tif (actions.length === 0) return;\n\treturn await reactorClient.execute(driveId, \"main\", actions);\n}\n//#endregion\n//#region src/constants.ts\nconst DEFAULT_DRIVE_EDITOR_ID = \"powerhouse/generic-drive-explorer\";\nconst COMMON_PACKAGE_ID = \"powerhouse/common\";\n/** Document types that represent a \"drive\": a container of nodes. */\nconst DRIVE_DOCUMENT_TYPES = [\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"];\n//#endregion\n//#region src/graphql/adapters.ts\nfunction phDocumentFromQuery(document, documentSchema) {\n\tconst phDocument = {\n\t\theader: phDocumentHeaderFromQuery(document),\n\t\tstate: phDocumentStateFromQuery(document),\n\t\tinitialState: phDocumentStateFromQuery(document),\n\t\toperations: phDocumentOperationsFromGetDocumentWithOperationsQuery(document),\n\t\tclipboard: []\n\t};\n\tif (documentSchema !== void 0) documentSchema.parse(phDocument);\n\treturn phDocument;\n}\nfunction phDocumentsFromQuery(items, documentSchema) {\n\treturn pipe(items, map((document) => phDocumentFromQuery(document, documentSchema)));\n}\nfunction phDocumentHeaderFromQuery(queryDocument) {\n\treturn {\n\t\tbranch: \"main\",\n\t\tid: queryDocument.id,\n\t\tname: queryDocument.name,\n\t\tdocumentType: queryDocument.documentType,\n\t\tcreatedAtUtcIso: queryDocument.createdAtUtcIso instanceof Date ? queryDocument.createdAtUtcIso.toUTCString() : queryDocument.createdAtUtcIso,\n\t\tlastModifiedAtUtcIso: queryDocument.lastModifiedAtUtcIso instanceof Date ? queryDocument.lastModifiedAtUtcIso.toUTCString() : queryDocument.lastModifiedAtUtcIso,\n\t\tslug: queryDocument.slug ?? \"\"\n\t};\n}\nfunction phDocumentStateFromQuery(queryDocument, documentSchema) {\n\tif (documentSchema !== void 0) return documentSchema.shape.state.parse(queryDocument.state);\n\treturn queryDocument.state;\n}\nfunction phDocumentOperationsFromGetDocumentWithOperationsQuery(queryDocument) {\n\tif (queryDocument.operations === null || queryDocument.operations === void 0) return { global: [] };\n\treturn { global: [...queryDocument.operations.items] };\n}\nfunction identifierFromMutateDocumentOperationVariables(variables) {\n\treturn z.object({ documentIdentifier: z.string() }).parse(variables).documentIdentifier;\n}\n//#endregion\n//#region src/graphql/constants.ts\nconst DEFAULT_DRIVE_ID = \"powerhouse\";\nconst DEFAULT_SWITCHBOARD_URL = \"http://localhost:4001/graphql\";\nconst graphqlEventsToSyncDrive = [\n\t\"CreateEmptyDocument\",\n\t\"CreateDocument\",\n\t\"AddChildren\",\n\t\"RemoveChildren\",\n\t\"MoveChildren\",\n\t\"DeleteDocument\",\n\t\"DeleteDocuments\"\n];\nconst graphqlDocumentEvents = [\n\t\"MutateDocument\",\n\t\"MutateDocumentAsync\",\n\t\"DeleteDocument\"\n];\nconst graphqlDocumentsEvents = [\"DeleteDocuments\"];\n//#endregion\n//#region src/graphql/fetchers.ts\nasync function reactorGraphqlFetchDocument(identifier, documentSchema) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\ttry {\n\t\tconst document = (await client.GetDocument({ identifier })).document?.document;\n\t\tif (!document) return void 0;\n\t\treturn phDocumentFromQuery(document, documentSchema);\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function reactorGraphqlBatchFetchDocuments(identifiers) {\n\tif (!window.ph?.reactorGraphQLClient) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\tconst promises = map(identifiers, (identifier) => reactorGraphqlFetchDocument(identifier));\n\treturn await Promise.all(promises);\n}\n//#endregion\n//#region src/graphql/batch.ts\n/**\n* A reference implementation for an async batching utility function built on\n* top of the `funnel` general purpose execution utility function. It will\n* accumulate all params passed to an async `call` method within the defined\n* burst duration and then use an async executor to process them in one\n* invocation. It then extracts an individual result for each call which is\n* used to resolve the original call.\n*\n* This allows synchronizing multiple async calls while keeping each call site\n* isolated from the rest (for example, as react components).\n*\n* This reference implementation can be copied into your project as-is, or you\n* can use it as the basis for a more complex implementation with additional\n* features.\n*\n* @param callback - The main function that takes a batch and returns an\n* aggregated response. The typing for the it's parameters will derive the\n* typing for the extractor and the `call` method.\n* @param extractor - A function that takes the aggregated response and extracts\n* from it the result for each individual call. The function is called with both\n* the index in the batch, and the params passed to the `call` method. This\n* allows handling APIs that return batch results as both objects and arrays.\n* @param maxBurstDurationMs - The period of time where the batcher would\n* collect params before triggering the executor. When set to 0 the batcher\n* does not incur any additional delays to the execution and would trigger at\n* the next tick, just like a regular async function would. This is also the\n* default value.\n* @returns A Funnel object with the `call` method augmented to support async\n* response.\n*/\nfunction batch(callback, extractor, maxBurstDurationMs = 0) {\n\tconst batchFunnel = funnel((requests) => {\n\t\tcallback(requests.map(({ params }) => params)).then((response) => {\n\t\t\tfor (const [index, { params, promiseCallbacks: [resolve, reject] }] of requests.entries()) try {\n\t\t\t\tresolve(extractor(response, index, ...params));\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tfor (const { promiseCallbacks: [, reject] } of requests) reject(error);\n\t\t});\n\t}, {\n\t\treducer: (requests, request) => [...requests ?? [], request],\n\t\tmaxBurstDurationMs,\n\t\ttriggerAt: \"end\"\n\t});\n\treturn {\n\t\t...batchFunnel,\n\t\tcall: (...params) => new Promise((...promiseCallbacks) => {\n\t\t\tbatchFunnel.call({\n\t\t\t\tpromiseCallbacks,\n\t\t\t\tparams\n\t\t\t});\n\t\t})\n\t};\n}\n//#endregion\n//#region src/graphql/document-fetcher.ts\nfunction makeDocumentsById(documents = []) {\n\treturn pipe(documents, filter(isTruthy), mapToObj((document) => [document.header.id, document]));\n}\nvar DocumentFetcher = class {\n\tbatchGetDocuments;\n\tconstructor() {\n\t\tthis.batchGetDocuments = batch(async (requests) => {\n\t\t\treturn makeDocumentsById(await reactorGraphqlBatchFetchDocuments(unique(map(requests, ([id]) => id))));\n\t\t}, (documentsById, _, id) => {\n\t\t\treturn prop(documentsById, id);\n\t\t});\n\t}\n\tget(id) {\n\t\treturn this.batchGetDocuments.call(id);\n\t}\n\tgetBatch(ids) {\n\t\treturn Promise.all(map(ids, (id) => this.get(id)));\n\t}\n};\n//#endregion\n//#region src/graphql/graphql-client-document-cache.ts\nvar GraphQLClientDocumentCache = class {\n\tfetcher;\n\tdocuments = /* @__PURE__ */ new Map();\n\tbatchPromises = /* @__PURE__ */ new Map();\n\tlisteners = /* @__PURE__ */ new Map();\n\tconstructor() {\n\t\tthis.fetcher = new DocumentFetcher();\n\t\twindow.addEventListener(\"MutateDocument\", (event) => {\n\t\t\tthis.handleDocumentMutated(event.detail.identifier).catch(console.error);\n\t\t});\n\t\twindow.addEventListener(\"MutateDocumentAsync\", (event) => {\n\t\t\tthis.handleDocumentMutated(event.detail.identifier).catch(console.error);\n\t\t});\n\t}\n\tget(id, refetch) {\n\t\tconst current = this.documents.get(id);\n\t\tif (current) {\n\t\t\tif (current.status === \"pending\") return current;\n\t\t\tif (!refetch) return current;\n\t\t}\n\t\tconst promise = addPromiseState(this.fetcher.get(id).then((document) => {\n\t\t\tthis.invalidateBatchesContaining(id);\n\t\t\treturn document;\n\t\t}));\n\t\tthis.documents.set(id, promise);\n\t\treturn promise;\n\t}\n\tgetBatch(ids) {\n\t\tconst key = ids.join(\",\");\n\t\tconst cached = this.batchPromises.get(key);\n\t\tconst currentPromises = ids.map((id) => this.get(id));\n\t\tif (cached) {\n\t\t\tif (currentPromises.every((promise, index) => promise === cached.promises[index])) return cached.promise;\n\t\t}\n\t\tconst states = currentPromises.map((promise) => readPromiseState(promise));\n\t\tif (states.every((state) => state.status !== \"pending\")) {\n\t\t\tconst values = states.filter((state) => state.status === \"fulfilled\").map((state) => state.value);\n\t\t\tconst batchPromise = Promise.resolve(values);\n\t\t\tbatchPromise.status = \"fulfilled\";\n\t\t\tbatchPromise.value = values;\n\t\t\tthis.batchPromises.set(key, {\n\t\t\t\tpromises: currentPromises,\n\t\t\t\tpromise: batchPromise\n\t\t\t});\n\t\t\treturn batchPromise;\n\t\t}\n\t\tconst batchPromise = addPromiseState(Promise.allSettled(currentPromises).then((results) => {\n\t\t\tconst documents = [];\n\t\t\tfor (const result of results) if (result.status === \"fulfilled\") documents.push(result.value);\n\t\t\telse console.warn(\"[GraphQLClientDocumentCache] Skipped unavailable document:\", result.reason);\n\t\t\treturn documents;\n\t\t}));\n\t\tthis.batchPromises.set(key, {\n\t\t\tpromises: currentPromises,\n\t\t\tpromise: batchPromise\n\t\t});\n\t\treturn batchPromise;\n\t}\n\tinvalidateBatchesContaining(documentId) {\n\t\tfor (const key of this.batchPromises.keys()) if (key.split(\",\").includes(documentId)) this.batchPromises.delete(key);\n\t}\n\tsubscribe(id, callback) {\n\t\tconst ids = Array.isArray(id) ? id : [id];\n\t\tfor (const documentId of ids) {\n\t\t\tconst listeners = this.listeners.get(documentId) ?? [];\n\t\t\tthis.listeners.set(documentId, [...listeners, callback]);\n\t\t}\n\t\treturn () => {\n\t\t\tfor (const documentId of ids) {\n\t\t\t\tconst listeners = this.listeners.get(documentId) ?? [];\n\t\t\t\tthis.listeners.set(documentId, listeners.filter((listener) => listener !== callback));\n\t\t\t}\n\t\t};\n\t}\n\tnotify(id) {\n\t\tconst listeners = this.listeners.get(id) ?? [];\n\t\tfor (const listener of listeners) listener();\n\t}\n\tasync handleDocumentMutated(id) {\n\t\tthis.invalidateBatchesContaining(id);\n\t\tawait this.get(id);\n\t\tthis.notify(id);\n\t}\n\thandleDocumentDeleted(id) {\n\t\tthis.documents.delete(id);\n\t\tthis.invalidateBatchesContaining(id);\n\t\tthis.notify(id);\n\t}\n\thandleDocumentsDeleted(ids) {\n\t\tforEach(ids, (id) => this.handleDocumentDeleted(id));\n\t}\n};\n//#endregion\n//#region src/graphql/mutators.ts\nasync function reactorGraphqlCreateDocument(document, parentIdentifier = DEFAULT_DRIVE_ID) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.CreateDocument({\n\t\tdocument,\n\t\tparentIdentifier\n\t});\n}\nasync function reactorGraphqlDeleteDocument(identifier) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.DeleteDocument({ identifier });\n}\nasync function reactorGraphqlDeleteDocuments(identifiers) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.DeleteDocuments({ identifiers });\n}\nasync function reactorGraphqlMutateDocument(documentIdentifier, ...actions) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\treturn await client.MutateDocument({\n\t\tdocumentIdentifier,\n\t\tactions\n\t});\n}\n//#endregion\n//#region src/hooks/allowed-document-model-modules.ts\nfunction useAllowedDocumentModelModules() {\n\tconst documentModelModules = useDocumentModelModules();\n\tconst allowedDocumentTypes = useAllowedDocumentTypes();\n\tif (!allowedDocumentTypes?.length) return documentModelModules;\n\treturn documentModelModules?.filter((module) => allowedDocumentTypes.includes(module.documentModel.global.id));\n}\n//#endregion\n//#region src/hooks/selected-folder.ts\n/** Returns the selected folder. */\nfunction useSelectedFolder() {\n\tconst selectedNode = useSelectedNode();\n\tif (isFolderNodeKind(selectedNode)) return selectedNode;\n}\n//#endregion\n//#region src/hooks/child-nodes.ts\n/** Returns the child nodes for the selected drive or folder. */\nfunction useNodesInSelectedDriveOrFolder() {\n\tconst nodes = useNodesInSelectedDrive();\n\tconst selectedFolderId = useSelectedFolder()?.id;\n\tif (!nodes) return [];\n\tif (!selectedFolderId) return sortNodesByName(nodes.filter((n) => !n.parentFolder));\n\treturn sortNodesByName(nodes.filter((n) => n.parentFolder === selectedFolderId));\n}\n//#endregion\n//#region src/hooks/config/set-config-by-key.ts\nfunction setPHGlobalConfigByKey(key, value) {\n\tconst setter = phGlobalConfigSetters[key];\n\tsetter(value);\n}\nfunction setPHAppConfigByKey(key, value) {\n\tconst setter = phAppConfigSetters[key];\n\tsetter(value);\n}\nfunction setPHDocumentEditorConfigByKey(key, value) {\n\tconst setter = phDocumentEditorConfigSetters[key];\n\tsetter(value);\n}\n//#endregion\n//#region src/hooks/config/utils.ts\nfunction callGlobalSetterForKey(key, value) {\n\tconst setter = phGlobalConfigSetters[key];\n\tsetter(value);\n}\n//#endregion\n//#region src/hooks/config/set-config-by-object.ts\nfunction setDefaultPHGlobalConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\nfunction useSetDefaultPHGlobalConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetDefaultPHGlobalConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\nfunction useResetPHGlobalConfig(defaultConfigForReset) {\n\treturn function reset() {\n\t\tsetPHGlobalConfig(defaultConfigForReset);\n\t};\n}\nfunction setPHGlobalConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\nfunction useSetPHGlobalConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetPHGlobalConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\n/** Sets the global drive config.\n*\n* Pass in a partial object of the global drive config to set.\n*/\nfunction setPHAppConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\n}\n/** Sets the global document config.\n*\n* Pass in a partial object of the global document config to set.\n*/\nfunction setPHDocumentEditorConfig(config) {\n\tfor (const key of Object.keys(config)) callGlobalSetterForKey(key, config[key]);\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*/\nfunction useSetPHAppConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetPHAppConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\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*/\nfunction useSetPHDocumentEditorConfig(config) {\n\tconst [isInitialized, setIsInitialized] = useState(false);\n\tuseEffect(() => {\n\t\tif (isInitialized) return;\n\t\tsetPHDocumentEditorConfig(config);\n\t\tsetIsInitialized(true);\n\t}, [config, isInitialized]);\n}\n//#endregion\n//#region src/hooks/config/use-value-by-key.ts\nfunction usePHGlobalConfigByKey(key) {\n\tconst useValueHook = phGlobalConfigHooks[key];\n\treturn useValueHook();\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*/\nfunction usePHAppConfigByKey(key) {\n\tconst useValueHook = phAppConfigHooks[key];\n\treturn useValueHook();\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*/\nfunction usePHDocumentEditorConfigByKey(key) {\n\tconst useValueHook = phDocumentEditorConfigHooks[key];\n\treturn useValueHook();\n}\n//#endregion\n//#region src/hooks/connection-state.ts\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*/\nfunction useConnectionStates() {\n\tconst syncManager = useSync();\n\tconst [states, setStates] = useState(() => buildSnapshot(syncManager));\n\tconst unsubscribesRef = useRef([]);\n\tuseEffect(() => {\n\t\tif (!syncManager) return;\n\t\tfunction subscribe() {\n\t\t\tfor (const unsub of unsubscribesRef.current) unsub();\n\t\t\tunsubscribesRef.current = [];\n\t\t\tconst remotes = syncManager.list();\n\t\t\tfor (const remote of remotes) {\n\t\t\t\tconst unsub = remote.channel.onConnectionStateChange(() => {\n\t\t\t\t\tsetStates(buildSnapshot(syncManager));\n\t\t\t\t});\n\t\t\t\tunsubscribesRef.current.push(unsub);\n\t\t\t}\n\t\t\tsetStates(buildSnapshot(syncManager));\n\t\t}\n\t\tsubscribe();\n\t\tconst interval = setInterval(subscribe, 5e3);\n\t\treturn () => {\n\t\t\tclearInterval(interval);\n\t\t\tfor (const unsub of unsubscribesRef.current) unsub();\n\t\t\tunsubscribesRef.current = [];\n\t\t};\n\t}, [syncManager]);\n\treturn states;\n}\n/**\n* Returns the connection state snapshot for a specific remote by name.\n*/\nfunction useConnectionState(remoteName) {\n\treturn useConnectionStates().get(remoteName);\n}\nfunction buildSnapshot(syncManager) {\n\tconst map = /* @__PURE__ */ new Map();\n\tif (!syncManager) return map;\n\tfor (const remote of syncManager.list()) map.set(remote.meta.name, remote.channel.getConnectionState());\n\treturn map;\n}\n//#endregion\n//#region src/hooks/supported-document-types.ts\n/** Returns the supported document types for the reactor (derived from the document model modules) */\nfunction useSupportedDocumentTypesInReactor() {\n\treturn useDocumentModelModules()?.map((module) => module.documentModel.global.id);\n}\n//#endregion\n//#region src/hooks/document-types.ts\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*/\nfunction useDocumentTypes() {\n\tconst allowedDocumentTypes = useAllowedDocumentTypes();\n\tconst supportedDocumentTypes = useSupportedDocumentTypesInReactor();\n\treturn allowedDocumentTypes ?? supportedDocumentTypes;\n}\n//#endregion\n//#region src/hooks/document-version-status.ts\n/**\n* Classifies a document's model version against the installed module\n* versions. Pure logic, extracted for testing.\n*/\nfunction getDocumentVersionStatus(documentVersion, availableVersions, hasUpgradePath) {\n\tif (availableVersions.length === 0) return;\n\tconst sorted = [...availableVersions].sort((a, b) => a - b);\n\tconst latestVersion = sorted[sorted.length - 1];\n\tif (documentVersion > latestVersion) return {\n\t\tkind: \"unsupported\",\n\t\tdocumentVersion,\n\t\tavailableVersions: sorted\n\t};\n\tif (documentVersion === latestVersion) return {\n\t\tkind: \"current\",\n\t\tdocumentVersion\n\t};\n\treturn {\n\t\tkind: \"upgrade-available\",\n\t\tdocumentVersion,\n\t\tlatestVersion,\n\t\tcanUpgrade: hasUpgradePath(documentVersion, latestVersion)\n\t};\n}\n/**\n* Compares the given document's model version against the versions available\n* from installed Vetra packages. Returns undefined while packages load or\n* when the document type has no installed modules.\n*/\nfunction useDocumentVersionStatus(document) {\n\tconst modules = useDocumentModelModules();\n\tconst registry = useModelRegistry();\n\tif (!document || !modules) return;\n\tconst documentType = document.header.documentType;\n\treturn getDocumentVersionStatus(document.state.document.version || 1, modules.filter((m) => m.documentModel.global.id === documentType).map((m) => m.version ?? 1), (fromVersion, toVersion) => {\n\t\tif (!registry) return false;\n\t\ttry {\n\t\t\tregistry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n//#endregion\n//#region src/utils/validate-document.ts\nconst validateDocument = (document) => {\n\tconst errors = [];\n\tif (document.header.documentType !== \"powerhouse/document-model\") return errors;\n\tconst doc = document;\n\tconst specs = doc.state.global.specifications[0];\n\tconst initialStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {\n\t\tconst scope = scopeKey;\n\t\treturn [...acc, ...validateInitialState(specs.state[scope].initialValue, scope !== \"global\").map((err) => ({\n\t\t\t...err,\n\t\t\tmessage: `${err.message}. Scope: ${scope}`,\n\t\t\tdetails: {\n\t\t\t\t...err.details,\n\t\t\t\tscope\n\t\t\t}\n\t\t}))];\n\t}, []);\n\tconst schemaStateErrors = Object.keys(specs.state).reduce((acc, scopeKey) => {\n\t\tconst scope = scopeKey;\n\t\tconst isGlobalScope = scope === \"global\";\n\t\treturn [...acc, ...validateStateSchemaName(specs.state[scope].schema, doc.state.global?.name || doc.header.name || \"\", !isGlobalScope ? scope : \"\", !isGlobalScope).map((err) => ({\n\t\t\t...err,\n\t\t\tmessage: `${err.message}. Scope: ${scope}`,\n\t\t\tdetails: {\n\t\t\t\t...err.details,\n\t\t\t\tscope\n\t\t\t}\n\t\t}))];\n\t}, []);\n\tconst modulesErrors = validateModules(specs.modules);\n\treturn [\n\t\t...initialStateErrors,\n\t\t...schemaStateErrors,\n\t\t...modulesErrors\n\t];\n};\n//#endregion\n//#region src/utils/download-document.ts\nfunction defaultHandleError(error) {\n\tconsole.error(`Failed to export document: ${error.message}`);\n}\nfunction handleDocumentValidation(document) {\n\tif (hasAtLeast(validateDocument(document), 1)) return false;\n\treturn true;\n}\nfunction downloadDocument(document, handleError = defaultHandleError) {\n\tif (!document) return;\n\tif (!handleDocumentValidation(document)) {\n\t\tshowPHModal({\n\t\t\ttype: \"downloadDocumentWithErrors\",\n\t\t\tdocumentId: document.header.id\n\t\t});\n\t\treturn;\n\t}\n\texportFile(document).catch((error) => handleError(normalizeException(error)));\n}\n//#endregion\n//#region src/hooks/download-document.ts\nfunction useDownloadDocument(id) {\n\tconst getDocument = useGetDocument();\n\tconst toast = usePHToast();\n\treturn async () => {\n\t\tif (!id) return;\n\t\tconst handleError = (error) => toast?.(`Failed to export document: ${error.message}`);\n\t\ttry {\n\t\t\tdownloadDocument(await getDocument(id), handleError);\n\t\t} catch (error) {\n\t\t\thandleError(error);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/hooks/download-folder.ts\n/**\n* Downloads the selected drive's folder (or the whole drive when no folder\n* is given) as a single zip archive mirroring the folder tree.\n*/\nfunction useDownloadFolder(folderNode) {\n\tconst [selectedDrive] = useSelectedDriveSafe();\n\tconst toast = usePHToast();\n\treturn async () => {\n\t\tif (!selectedDrive) return;\n\t\tconst name = folderNode?.name ?? selectedDrive.header.name;\n\t\ttoast?.(`Downloading \"${name}\"…`);\n\t\ttry {\n\t\t\tconst { entryCount, failed } = await downloadFolderZip(selectedDrive, folderNode);\n\t\t\ttoast?.(failed.length ? `Downloaded ${entryCount} files (${failed.length} failed)` : `Downloaded ${entryCount} files`);\n\t\t} catch (error) {\n\t\t\ttoast?.(`Failed to download \"${name}\": ${error.message}`);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/hooks/drive-by-id.ts\nfunction useDriveById(driveId) {\n\tconst foundDrive = useDrives()?.find((drive) => drive.header.id === driveId);\n\tconst [drive, dispatch] = useDispatch(foundDrive);\n\tif (!foundDrive) throw new Error(`Drive with id ${driveId} not found`);\n\treturn [drive, dispatch];\n}\n//#endregion\n//#region src/hooks/editor-modules.ts\n/** An editor is a drive \"app\" if it targets any supported drive document type. */\nfunction isDriveEditor(module) {\n\tconst driveTypes = DRIVE_DOCUMENT_TYPES;\n\treturn module.documentTypes.some((t) => driveTypes.includes(t));\n}\nfunction useEditorModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.editors).filter((module) => !isDriveEditor(module));\n}\nfunction useAppModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.editors).filter(isDriveEditor);\n}\nfunction useFallbackEditorModule(documentType) {\n\tconst editorModules = useEditorModules();\n\tif (!documentType) return void 0;\n\tif (editorModules?.length === 0) return void 0;\n\treturn (editorModules?.filter((module) => module.documentTypes.includes(documentType)))?.[0];\n}\nfunction useAppModuleById(id) {\n\treturn useAppModules()?.find((module) => module.config.id === id);\n}\nfunction useDefaultAppModule() {\n\treturn useAppModuleById(DEFAULT_DRIVE_EDITOR_ID);\n}\nfunction useEditorModuleById(id) {\n\treturn useEditorModules()?.find((module) => module.config.id === id);\n}\nfunction useEditorModulesForDocumentType(documentType) {\n\tconst editorModules = useEditorModules();\n\tif (!documentType) return void 0;\n\treturn editorModules?.filter((module) => module.documentTypes.includes(documentType));\n}\n//#endregion\n//#region src/utils/preload-editor.ts\nfunction preloadEditorModule(module) {\n\tconst Component = module.Component;\n\tif (typeof Component.preload === \"function\") return Component.preload();\n\tconst payload = Component._payload;\n\tconst init = Component._init;\n\tif (!payload || typeof init !== \"function\") return void 0;\n\ttry {\n\t\tinit(payload);\n\t} catch (thrown) {\n\t\tif (thrown && typeof thrown.then === \"function\") return thrown;\n\t}\n}\nfunction hasPreloadBandwidth() {\n\tif (typeof navigator === \"undefined\") return false;\n\tconst connection = navigator.connection;\n\tif (!connection) return true;\n\tif (connection.saveData) return false;\n\treturn ![\"slow-2g\", \"2g\"].includes(connection.effectiveType ?? \"\");\n}\n//#endregion\n//#region src/hooks/use-editor-preloader.ts\nfunction requestIdle(cb) {\n\tif (typeof window.requestIdleCallback === \"function\") return window.requestIdleCallback(cb);\n\treturn window.setTimeout(() => {\n\t\tconst start = Date.now();\n\t\tcb({\n\t\t\tdidTimeout: false,\n\t\t\ttimeRemaining: () => Math.max(0, 8 - (Date.now() - start))\n\t\t});\n\t}, 200);\n}\nfunction cancelIdle(handle) {\n\tif (typeof window.cancelIdleCallback === \"function\") window.cancelIdleCallback(handle);\n\telse window.clearTimeout(handle);\n}\nfunction useEditorPreloader() {\n\tconst editorModules = useEditorModules();\n\tconst appModules = useAppModules();\n\tuseEffect(() => {\n\t\tconst queue = [...editorModules ?? [], ...appModules ?? []];\n\t\tif (queue.length === 0 || !hasPreloadBandwidth()) return;\n\t\tlet cancelled = false;\n\t\tlet handle = 0;\n\t\tconst pump = (deadline) => {\n\t\t\twhile (!cancelled && queue.length > 0 && (deadline.didTimeout || deadline.timeRemaining() > 0)) preloadEditorModule(queue.shift());\n\t\t\tif (!cancelled && queue.length > 0) handle = requestIdle(pump);\n\t\t};\n\t\thandle = requestIdle(pump);\n\t\treturn () => {\n\t\t\tcancelled = true;\n\t\t\tif (handle) cancelIdle(handle);\n\t\t};\n\t}, [editorModules, appModules]);\n}\n//#endregion\n//#region src/hooks/file-drag-and-drop.ts\nconst allowedExtensions = [\n\t\"zip\",\n\t\"phd\",\n\t\"phdm\"\n];\nconst hasFilesType = (types) => isDefined(find(types, (type) => isStrictEqual(type, \"Files\")));\nconst isFileDrop = (event) => allPass(event.dataTransfer.types, [\n\tisArray,\n\thasAtLeast(1),\n\thasFilesType\n]);\nconst EDITOR_FILE_DROP_OPT_OUT_ATTR = \"data-accepts-files\";\nconst isInsideEditorFileDropOptOut = (event) => {\n\tconst target = event.target;\n\tif (!(target instanceof Element)) return false;\n\treturn target.closest(`[${EDITOR_FILE_DROP_OPT_OUT_ATTR}]`) !== null;\n};\nconst hasAllowedExtension = (file) => pipe(file, (file) => file.name, split(\".\"), last(), isIncludedIn(allowedExtensions));\nconst getFileItems = (event) => pipe([...event.dataTransfer.items], filter((item) => isStrictEqual(item.kind, \"file\")), map((item) => item.getAsFile()), filter(isTruthy));\nfunction useDropFile(handleAddFile) {\n\tconst { isDropTarget, setTarget, unsetTarget } = useDropTarget();\n\tconst isDragAndDropEnabled = useIsDragAndDropEnabled();\n\tconst selectedFolder = useSelectedFolder();\n\tconst selectedDriveId = useSelectedDriveId();\n\tfunction handleDragEvent(event, cb) {\n\t\tif (!isDragAndDropEnabled) return;\n\t\tif (!isFileDrop(event)) return;\n\t\tif (isInsideEditorFileDropOptOut(event)) {\n\t\t\tunsetTarget();\n\t\t\treturn;\n\t\t}\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\tcb?.();\n\t}\n\tconst handleAddFiles = async (event) => {\n\t\tconst dropped = pipe(event, getFileItems, filter(hasAllowedExtension));\n\t\tconst jobs = [];\n\t\tfor (const file of dropped) {\n\t\t\tif (selectedDriveId) try {\n\t\t\t\tconst expanded = await expandBulkArchive(file, selectedDriveId, selectedFolder);\n\t\t\t\tjobs.push(...expanded);\n\t\t\t\tcontinue;\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Bulk archive expansion failed\", error);\n\t\t\t}\n\t\t\tjobs.push({\n\t\t\t\tfile,\n\t\t\t\tparent: selectedFolder\n\t\t\t});\n\t\t}\n\t\tawait Promise.all(jobs.map((job) => handleAddFile(job.file, job.parent)));\n\t};\n\tconst onDragEnter = (event) => handleDragEvent(event);\n\tconst onDragOver = (event) => handleDragEvent(event, setTarget);\n\tconst onDragLeave = (event) => handleDragEvent(event, unsetTarget);\n\tconst onDrop = (event) => handleDragEvent(event, once(() => {\n\t\tunsetTarget();\n\t\thandleAddFiles(event).catch(console.error);\n\t}));\n\treturn {\n\t\tonDragEnter,\n\t\tonDragOver,\n\t\tonDragLeave,\n\t\tonDrop,\n\t\tisDropTarget\n\t};\n}\n//#endregion\n//#region src/hooks/folder-by-id.ts\nfunction useFolderById(id) {\n\treturn useFolderNodesInSelectedDrive()?.find((n) => n.id === id);\n}\n//#endregion\n//#region src/graphql/events.ts\nfunction dispatchGraphQLClientDocumentEvent(operationName, identifier) {\n\tconst event = new CustomEvent(operationName, { detail: { identifier } });\n\twindow.dispatchEvent(event);\n}\n//#endregion\n//#region src/graphql/document-cache-client-middleware.ts\nconst documentCacheClientMiddleware = async (action, operationName, operationType, variables) => {\n\tconsole.log({\n\t\toperationName,\n\t\toperationType,\n\t\tvariables\n\t});\n\tconst result = await action();\n\tif (isIncludedIn(operationName, graphqlEventsToSyncDrive)) window.dispatchEvent(new CustomEvent(operationName));\n\tif (isStrictEqual(operationName, \"MutateDocument\")) dispatchGraphQLClientDocumentEvent(operationName, identifierFromMutateDocumentOperationVariables(variables));\n\treturn result;\n};\n//#endregion\n//#region src/hooks/init-graphql-reactor-client.ts\nfunction useInitReactorGraphqlClient(switchboardUrl = DEFAULT_SWITCHBOARD_URL, driveId = DEFAULT_DRIVE_ID) {\n\tconst [hasInit, setHasInit] = useState(false);\n\tuseEffect(() => {\n\t\tif (hasInit) return;\n\t\tinitGraphQLReactorClientWithDocumentCache(switchboardUrl, driveId).then(() => setHasInit(true)).catch(console.error);\n\t}, [hasInit]);\n\treturn hasInit;\n}\nasync function reactorGraphqlFetchDrive(identifier) {\n\tconst client = window.ph?.reactorGraphQLClient;\n\tif (!client) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\tconst result = await client.GetDocument({ identifier });\n\tif (!result.document?.document) throw new Error(\"Could not fetch drive with id: \" + identifier);\n\treturn phDocumentFromQuery(result.document.document, DriveDocumentSchema);\n}\nasync function reactorGraphqlSyncDrive(driveId) {\n\tif (!window.ph?.reactorGraphQLClient) throw new Error(\"Please call `useInitReactorGraphqlClient` to use its functions\");\n\tconst drive = await reactorGraphqlFetchDrive(driveId);\n\tsetDrives([drive]);\n\tsetSelectedDrive(drive);\n}\nasync function initGraphQLReactorClientWithDocumentCache(switchboardUrl, driveId) {\n\tif (!window.ph) window.ph = {};\n\tcallEventHandlerRegisterFunctions(commonGlobalEventHandlerFunctions);\n\tsetGraphQLReactorClient(createClient(switchboardUrl, documentCacheClientMiddleware));\n\tawait reactorGraphqlSyncDrive(driveId);\n\tsetSelectedNode(void 0);\n\tsetDocumentCache(new GraphQLClientDocumentCache());\n\tforEach(graphqlEventsToSyncDrive, (name) => {\n\t\twindow.addEventListener(name, () => {\n\t\t\treactorGraphqlSyncDrive(driveId).catch(console.error);\n\t\t});\n\t});\n}\n//#endregion\n//#region src/hooks/items-in-selected-folder.ts\n/** Returns the nodes in the selected folder. */\nfunction useNodesInSelectedFolder() {\n\tconst selectedFolder = useSelectedFolder();\n\tconst nodes = useNodesInSelectedDrive();\n\tif (!selectedFolder || !nodes) return void 0;\n\treturn nodes.filter((n) => n.parentFolder === selectedFolder.id);\n}\n/** Returns the file nodes in the selected folder. */\nfunction useFileNodesInSelectedFolder() {\n\tconst nodes = useNodesInSelectedFolder();\n\tif (!nodes) return void 0;\n\treturn nodes.filter((n) => isFileNodeKind(n));\n}\n/** Returns the folder nodes in the selected folder. */\nfunction useFolderNodesInSelectedFolder() {\n\tconst nodes = useNodesInSelectedFolder();\n\tif (!nodes) return void 0;\n\treturn nodes.filter((n) => isFolderNodeKind(n));\n}\n/** Returns the documents in the selected folder. */\nfunction useDocumentsInSelectedFolder() {\n\tconst documents = useDocumentsInSelectedDrive();\n\tconst fileNodeIds = useFileNodesInSelectedFolder()?.map((node) => node.id);\n\treturn documents?.filter((d) => fileNodeIds?.includes(d.header.id));\n}\n//#endregion\n//#region src/hooks/node-actions.ts\nfunction resolveNode(driveId, node) {\n\treturn node?.id !== driveId ? node : void 0;\n}\nfunction useNodeActions() {\n\tconst [selectedDrive] = useSelectedDriveSafe();\n\tconst selectedFolder = useSelectedFolder();\n\tconst selectedParentFolder = useFolderById(useSelectedNode()?.parentFolder);\n\tconst selectedDriveId = selectedDrive?.header.id;\n\tconst drives = useDrives();\n\tasync function onAddFile(file, parent) {\n\t\tif (!selectedDriveId) return;\n\t\treturn addFileWithProgress(file, selectedDriveId, file.name.replace(/\\..+/gim, \"\"), resolveNode(selectedDriveId, parent)?.id, void 0, void 0, \"duplicate\");\n\t}\n\tasync function onAddFolder(name, parent) {\n\t\tif (!selectedDriveId) return;\n\t\treturn addFolder(selectedDriveId, name, resolveNode(selectedDriveId, parent)?.id);\n\t}\n\tasync function onRenameNode(newName, node) {\n\t\tif (!selectedDriveId) return;\n\t\tif (!resolveNode(selectedDriveId, node)) {\n\t\t\tconsole.error(`Node ${node.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\treturn await renameNode(selectedDriveId, node.id, newName);\n\t}\n\tasync function onCopyNode(src, target) {\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedSrc = resolveNode(selectedDriveId, src);\n\t\tif (!resolvedSrc) {\n\t\t\tconsole.error(`Node ${src.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\tawait copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, target));\n\t}\n\tasync function onMoveNode(src, target) {\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedSrc = resolveNode(selectedDriveId, src);\n\t\tif (!resolvedSrc) {\n\t\t\tconsole.error(`Node ${src.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\tconst resolvedTarget = resolveNode(selectedDriveId, target);\n\t\tif (!resolvedTarget?.id && !src.parentFolder || resolvedTarget?.id === src.parentFolder) return;\n\t\tawait moveNode$1(selectedDriveId, resolvedSrc, resolvedTarget);\n\t}\n\tasync function onDuplicateNode(src) {\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedSrc = resolveNode(selectedDriveId, src);\n\t\tif (!resolvedSrc) {\n\t\t\tconsole.error(`Node ${src.id} not found`);\n\t\t\treturn;\n\t\t}\n\t\tawait copyNode$1(selectedDriveId, resolvedSrc, resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder));\n\t}\n\tasync function onAddAndSelectNewFolder(name) {\n\t\tif (!name) return;\n\t\tif (!selectedDriveId) return;\n\t\tconst resolvedTarget = resolveNode(selectedDriveId, selectedFolder ?? selectedParentFolder);\n\t\tif (!resolvedTarget) return;\n\t\tconst newFolder = await onAddFolder(name, resolvedTarget);\n\t\tif (newFolder) setSelectedNode(newFolder);\n\t}\n\tasync function onRenameDriveNodes(newName, nodeId) {\n\t\tif (!drives) return;\n\t\tconst drivesWithNode = drives.filter((drive) => drive.state.global.nodes.some((n) => n.id === nodeId));\n\t\tawait Promise.all(drivesWithNode.map((drive) => renameDriveNode(drive.header.id, nodeId, newName)));\n\t}\n\treturn {\n\t\tonAddFile,\n\t\tonAddFolder,\n\t\tonRenameNode,\n\t\tonCopyNode,\n\t\tonMoveNode,\n\t\tonDuplicateNode,\n\t\tonAddAndSelectNewFolder,\n\t\tonRenameDriveNodes\n\t};\n}\n//#endregion\n//#region src/hooks/node-by-id.ts\n/** Returns a node in the selected drive by id. */\nfunction useNodeById(id) {\n\treturn useNodesInSelectedDrive()?.find((n) => n.id === id);\n}\n//#endregion\n//#region src/hooks/node-path.ts\n/** Returns the path to a node in the selected drive */\nfunction useNodePathById(id) {\n\tconst nodes = useNodesInSelectedDrive();\n\tif (!nodes) return [];\n\tconst path = [];\n\tlet current = nodes.find((n) => n.id === id);\n\twhile (current) {\n\t\tpath.push(current);\n\t\tif (!current.parentFolder) break;\n\t\tcurrent = nodes.find((n) => n.id === current?.parentFolder);\n\t}\n\treturn path.reverse();\n}\n/** Returns the path to the currently selected node in the selected drive. */\nfunction useSelectedNodePath() {\n\treturn useNodePathById(useSelectedNode()?.id);\n}\n//#endregion\n//#region src/hooks/parent-folder.ts\nfunction useNodeParentFolderById(id) {\n\treturn useFolderById(useNodeById(id)?.parentFolder);\n}\nfunction useParentFolderForSelectedNode() {\n\treturn useNodeParentFolderById(useSelectedNode()?.id);\n}\n//#endregion\n//#region src/hooks/subgraph-modules.ts\nfunction useSubgraphModules() {\n\treturn useVetraPackages().flatMap((pkg) => pkg.subgraphs || []);\n}\n//#endregion\n//#region src/hooks/theme.ts\nconst STORED_THEME_KEY = \"ph:theme\";\nconst UPDATE_STORED_THEME = \"ph:updateStoredTheme\";\nconst STORED_THEME_UPDATED = \"ph:storedThemeUpdated\";\nconst SYSTEM_THEME_UPDATED = \"ph:systemThemeUpdated\";\nconst isServer = typeof window === \"undefined\";\nfunction setStoredTheme(storedTheme) {\n\tif (isServer) return;\n\tlocalStorage.setItem(STORED_THEME_KEY, storedTheme);\n}\nfunction setTheme(storedTheme) {\n\tif (isServer) return;\n\tconst updateStoredThemeEvent = new CustomEvent(UPDATE_STORED_THEME, { detail: { storedTheme } });\n\twindow.dispatchEvent(updateStoredThemeEvent);\n}\nfunction handleUpdateStoredTheme(event) {\n\tif (isServer) return;\n\tconst storedTheme = event.detail.storedTheme;\n\tsetStoredTheme(storedTheme);\n\tconst storedThemeUpdatedEvent = new CustomEvent(STORED_THEME_UPDATED, { detail: { storedTheme } });\n\twindow.dispatchEvent(storedThemeUpdatedEvent);\n}\nfunction getStoredTheme() {\n\tif (isServer) return void 0;\n\treturn localStorage.getItem(STORED_THEME_KEY) ?? void 0;\n}\nfunction getPrefersDarkMediaQuery() {\n\tif (isServer) return;\n\treturn window.matchMedia(\"(prefers-color-scheme: dark)\");\n}\nfunction getPrefersDark() {\n\tif (isServer) return false;\n\tif (getPrefersDarkMediaQuery()?.matches) return true;\n\treturn false;\n}\nfunction getSystemTheme() {\n\tif (isServer) return \"light\";\n\tif (getPrefersDark()) return \"dark\";\n\treturn \"light\";\n}\nfunction handleSystemThemeChange(event) {\n\tconst systemTheme = event.matches ? \"dark\" : \"light\";\n\tconst systemThemeUpdatedEvent = new CustomEvent(SYSTEM_THEME_UPDATED, { detail: { systemTheme } });\n\twindow.dispatchEvent(systemThemeUpdatedEvent);\n}\nfunction toggleDark(isDark) {\n\tif (isServer) return;\n\tdocument.documentElement.classList.toggle(\"dark\", isDark);\n}\nfunction initTheme() {\n\tif (isServer) return;\n\tuseEffect(() => {\n\t\twindow.addEventListener(UPDATE_STORED_THEME, handleUpdateStoredTheme);\n\t\tconst prefersDarkMediaQuery = getPrefersDarkMediaQuery();\n\t\tprefersDarkMediaQuery?.addEventListener(\"change\", handleSystemThemeChange);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(UPDATE_STORED_THEME, handleUpdateStoredTheme);\n\t\t\tprefersDarkMediaQuery?.removeEventListener(\"change\", handleSystemThemeChange);\n\t\t};\n\t}, []);\n}\nfunction subscribeToStoredTheme(onStoreChange) {\n\tif (isServer) return () => {};\n\tconst handleStorage = (event) => {\n\t\tif (event.key === STORED_THEME_KEY || event.key === null) onStoreChange();\n\t};\n\twindow.addEventListener(STORED_THEME_UPDATED, onStoreChange);\n\twindow.addEventListener(\"storage\", handleStorage);\n\treturn () => {\n\t\twindow.removeEventListener(STORED_THEME_UPDATED, onStoreChange);\n\t\twindow.removeEventListener(\"storage\", handleStorage);\n\t};\n}\nfunction subscribeToSystemTheme(onStoreChange) {\n\tif (isServer) return () => {};\n\twindow.addEventListener(SYSTEM_THEME_UPDATED, onStoreChange);\n\treturn () => {\n\t\twindow.removeEventListener(SYSTEM_THEME_UPDATED, onStoreChange);\n\t};\n}\nfunction useTheme() {\n\tconst storedTheme = useSyncExternalStore(subscribeToStoredTheme, () => getStoredTheme(), () => \"system\");\n\tconst systemTheme = useSyncExternalStore(subscribeToSystemTheme, () => getSystemTheme(), () => \"light\");\n\tconst isSystem = storedTheme === void 0 || storedTheme === \"system\";\n\tconst theme = isSystem ? systemTheme : storedTheme;\n\tconst isDark = theme === \"dark\";\n\tuseEffect(() => {\n\t\ttoggleDark(isDark);\n\t}, [isDark]);\n\treturn {\n\t\ttheme,\n\t\tisSystem,\n\t\tsetTheme\n\t};\n}\n//#endregion\n//#region src/hooks/use-can-execute.ts\nconst IDLE = { status: \"idle\" };\nconst LOADING = { status: \"loading\" };\nconst UNSUPPORTED = { status: \"unsupported\" };\nfunction readyState(answer) {\n\treturn {\n\t\tstatus: \"ready\",\n\t\tevaluations: answer.evaluations,\n\t\tallAllowed: answer.allAllowed,\n\t\tanyAllowed: answer.anyAllowed,\n\t\tallDenied: answer.allDenied,\n\t\tanyDenied: answer.anyDenied\n\t};\n}\n/**\n* Whether the subject the reactor client would decide for now is the one it is\n* going to keep.\n*\n* Renown's login status is the signal. Only `checking` is transient --\n* mid-login, about to resolve -- and `authorized` without a user yet is still\n* mid-resolution. Everything else is a steady state: `initial` is the anonymous\n* subject for a user who never logged in or just logged out (a restored session\n* is `authorized` from construction, so `initial` is not a pre-login window),\n* and `not-authorized` is a failed login, anonymous too.\n*\n* An absent status counts as unsettled, which is one render in a host that wires\n* renown -- and forever in a host that does not. Such a host names its subject\n* through the `subject` parameter instead, which needs nothing to settle.\n*/\nfunction subjectSettled(loginStatus, user) {\n\tif (loginStatus === \"authorized\") return user !== void 0;\n\treturn loginStatus === \"initial\" || loginStatus === \"not-authorized\";\n}\n/**\n* Predicts whether the current subject may execute each of a set of candidate\n* operations on one document, so a UI can disable a control rather than offer an\n* action that fails on submit.\n*\n* The answer is a prediction and not a promise: the submit path is the only\n* authority, and this cannot reproduce the append condition real admission\n* compiles. Treat an allow as \"worth offering\", never as \"will succeed\", and\n* keep handling the submit's refusal.\n*\n* A candidate whose verdict depends on its input has to carry that input, since\n* a conditional grant reads it. A candidate standing for a form the user has not\n* filled in yet predicts the verdict an empty form earns.\n*\n* Deliberately reads the client off the reactor client module rather than\n* through `useReactorClient`: the latter hands back the minimal browser client\n* contract, which does not carry the preflight, and the plain-GraphQL setup that\n* implements it sets no module at all. No module therefore reports\n* `unsupported`.\n*\n* Re-evaluated when the document's revision moves, which covers a policy change\n* written to the document being asked about. Two gaps are known and accepted:\n*\n* - A group membership change is a write to the *group* document, so it fires no\n* change event for this one. A group-gated grant can therefore be stale here\n* until something else re-evaluates.\n* - A change event carries no scope, so any write to the document re-evaluates,\n* including one that cannot affect a verdict.\n*\n* @param documentId - The document the candidates target, or null/undefined to stay idle\n* @param candidates - Operations to predict a verdict for. Read by content, so an inline array is fine\n* @param branch - Branch to evaluate against, defaulting to main\n* @param subject - Optional subject to decide for instead of the client's signer\n*/\nfunction useCanExecute(documentId, candidates, branch = \"main\", subject) {\n\tconst client = useReactorClientModule()?.client;\n\tconst loginStatus = useLoginStatus();\n\tconst user = useUser();\n\tconst revision = useDocumentSafe(documentId).data?.header.revision;\n\tconst [nonce, setNonce] = useState(0);\n\tconst [state, setState] = useState(IDLE);\n\tconst candidateKey = JSON.stringify(candidates);\n\tconst subjectKey = JSON.stringify(subject);\n\tconst stableCandidates = useMemo(() => candidates, [candidateKey]);\n\tconst stableSubject = useMemo(() => subject, [subjectKey]);\n\tconst settled = subject !== void 0 || subjectSettled(loginStatus, user);\n\tconst subjectIdentity = subject !== void 0 ? subjectKey : `${loginStatus ?? \"\"}:${user?.address ?? \"\"}`;\n\tconst revisionKey = JSON.stringify(revision);\n\tconst refetch = useCallback(() => {\n\t\tsetNonce((count) => count + 1);\n\t}, []);\n\tuseEffect(() => {\n\t\tif (client === void 0) {\n\t\t\tsetState(UNSUPPORTED);\n\t\t\treturn;\n\t\t}\n\t\tif (!documentId) {\n\t\t\tsetState(IDLE);\n\t\t\treturn;\n\t\t}\n\t\tif (!settled) {\n\t\t\tsetState(LOADING);\n\t\t\treturn;\n\t\t}\n\t\tlet active = true;\n\t\tsetState(LOADING);\n\t\tconst evaluate = async () => {\n\t\t\tlet next;\n\t\t\ttry {\n\t\t\t\tnext = readyState(await client.evaluateActions(documentId, branch, stableCandidates, stableSubject));\n\t\t\t} catch (error) {\n\t\t\t\tnext = AuthEnforcementDisabledError.isError(error) ? UNSUPPORTED : {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\terror: Error.isError(error) ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (active) setState(next);\n\t\t};\n\t\tevaluate();\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t};\n\t}, [\n\t\tclient,\n\t\tdocumentId,\n\t\tbranch,\n\t\tstableCandidates,\n\t\tstableSubject,\n\t\tsettled,\n\t\tsubjectIdentity,\n\t\trevisionKey,\n\t\tnonce\n\t]);\n\treturn {\n\t\t...state,\n\t\trefetch\n\t};\n}\n//#endregion\n//#region src/hooks/use-drive-system-info.ts\nfunction deriveSystemUrl(channelUrl) {\n\ttry {\n\t\tconst url = new URL(channelUrl);\n\t\turl.search = \"\";\n\t\turl.hash = \"\";\n\t\tif (url.pathname.endsWith(\"/graphql/r\")) url.pathname = url.pathname.slice(0, -10) + \"/graphql/system\";\n\t\telse url.pathname = \"/graphql/system\";\n\t\treturn url.toString();\n\t} catch {\n\t\treturn null;\n\t}\n}\nconst cache = /* @__PURE__ */ new Map();\nfunction useDriveSystemInfo(drive) {\n\tconst remotes = useSyncList();\n\tconst driveId = drive?.header.id;\n\tconst systemUrl = useMemo(() => {\n\t\tif (!driveId) return null;\n\t\tconst channelUrl = (remotes.find((r) => r.meta.collectionId.equals(DriveCollectionId$1.forDrive(driveId)))?.channel)?.config.url;\n\t\tif (typeof channelUrl !== \"string\") return null;\n\t\treturn deriveSystemUrl(channelUrl);\n\t}, [remotes, driveId]);\n\tconst [state, setState] = useState(() => systemUrl ? cache.get(systemUrl) ?? { status: \"loading\" } : { status: \"local\" });\n\tuseEffect(() => {\n\t\tif (!systemUrl) {\n\t\t\tsetState({ status: \"local\" });\n\t\t\treturn;\n\t\t}\n\t\tconst cached = cache.get(systemUrl);\n\t\tif (cached && cached.status !== \"loading\") {\n\t\t\tsetState(cached);\n\t\t\treturn;\n\t\t}\n\t\tsetState({ status: \"loading\" });\n\t\tcache.set(systemUrl, { status: \"loading\" });\n\t\tconst controller = new AbortController();\n\t\tfetch(systemUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ query: \"{ system { version gitHash gitUrl } }\" }),\n\t\t\tsignal: controller.signal\n\t\t}).then(async (res) => {\n\t\t\tconst json = await res.json();\n\t\t\tif (json.errors?.length) throw new Error(json.errors.map((e) => e.message).join(\"; \"));\n\t\t\tconst sys = json.data?.system;\n\t\t\tif (!sys) throw new Error(\"Missing system in response\");\n\t\t\tconst next = {\n\t\t\t\tstatus: \"ready\",\n\t\t\t\tversion: sys.version,\n\t\t\t\tgitHash: sys.gitHash,\n\t\t\t\tgitUrl: sys.gitUrl ?? null,\n\t\t\t\thost: new URL(systemUrl).host\n\t\t\t};\n\t\t\tcache.set(systemUrl, next);\n\t\t\tsetState(next);\n\t\t}).catch((err) => {\n\t\t\tif (controller.signal.aborted) return;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tconsole.error(message);\n\t\t\tconst next = {\n\t\t\t\tstatus: \"error\",\n\t\t\t\tmessage\n\t\t\t};\n\t\t\tcache.set(systemUrl, next);\n\t\t\tsetState(next);\n\t\t});\n\t\treturn () => controller.abort();\n\t}, [systemUrl]);\n\treturn state;\n}\n//#endregion\n//#region src/hooks/use-editor-file-drop.ts\nconst hasFiles = (event) => event.dataTransfer.types.includes(\"Files\");\nconst filterByExtension = (files, accept) => {\n\tconst all = Array.from(files);\n\tif (!accept || accept.length === 0) return all;\n\tconst lowerAccept = accept.map((ext) => ext.toLowerCase());\n\treturn all.filter((file) => {\n\t\tconst lower = file.name.toLowerCase();\n\t\treturn lowerAccept.some((ext) => lower.endsWith(ext));\n\t});\n};\nfunction useEditorFileDrop(options) {\n\tconst { accept, onFiles } = options;\n\tconst [isDragOver, setIsDragOver] = useState(false);\n\tconst depthRef = useRef(0);\n\tconst onDragOver = useCallback((event) => {\n\t\tif (!hasFiles(event)) return;\n\t\tevent.preventDefault();\n\t}, []);\n\treturn {\n\t\tdragProps: {\n\t\t\tonDragEnter: useCallback((event) => {\n\t\t\t\tif (!hasFiles(event)) return;\n\t\t\t\tdepthRef.current += 1;\n\t\t\t\tif (depthRef.current === 1) setIsDragOver(true);\n\t\t\t}, []),\n\t\t\tonDragOver,\n\t\t\tonDragLeave: useCallback((event) => {\n\t\t\t\tif (!hasFiles(event)) return;\n\t\t\t\tdepthRef.current = Math.max(0, depthRef.current - 1);\n\t\t\t\tif (depthRef.current === 0) setIsDragOver(false);\n\t\t\t}, []),\n\t\t\tonDrop: useCallback((event) => {\n\t\t\t\tif (!hasFiles(event)) return;\n\t\t\t\tevent.preventDefault();\n\t\t\t\tdepthRef.current = 0;\n\t\t\t\tsetIsDragOver(false);\n\t\t\t\tconst accepted = filterByExtension(event.dataTransfer.files, accept);\n\t\t\t\tif (accepted.length === 0) return;\n\t\t\t\tonFiles(accepted);\n\t\t\t}, [accept, onFiles]),\n\t\t\t[EDITOR_FILE_DROP_OPT_OUT_ATTR]: \"\"\n\t\t},\n\t\tisDragOver\n\t};\n}\n//#endregion\n//#region src/utils/drives.ts\nconst syncStatusToUI = {\n\t[SyncStatus.Synced]: \"SUCCESS\",\n\t[SyncStatus.Outgoing]: \"SYNCING\",\n\t[SyncStatus.Incoming]: \"SYNCING\",\n\t[SyncStatus.OutgoingAndIncoming]: \"SYNCING\",\n\t[SyncStatus.Error]: \"ERROR\"\n};\nasync function getDrives(reactor) {\n\treturn (await Promise.all(DRIVE_DOCUMENT_TYPES.map((type) => reactor.find({ type })))).flatMap((r) => r.results);\n}\nfunction getSyncStatus(documentId, sharingType) {\n\treturn Promise.resolve(getSyncStatusSync(documentId, sharingType));\n}\nfunction getSyncStatusSync(documentId, sharingType) {\n\tif (sharingType === \"LOCAL\") return;\n\tconst syncManager = window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n\tif (!syncManager) return;\n\tconst status = syncManager.getSyncStatus(documentId);\n\tif (status === void 0) return;\n\treturn syncStatusToUI[status];\n}\n//#endregion\n//#region src/utils/get-revision-from-date.ts\nconst getRevisionFromDate = (startDate, endDate, operations = []) => {\n\tif (!startDate || !endDate) return 0;\n\tconst operation = operations.find((operation) => {\n\t\tconst operationDate = new Date(operation.timestampUtcMs);\n\t\treturn operationDate >= startDate && operationDate <= endDate;\n\t});\n\treturn operation ? operation.index : 0;\n};\n//#endregion\n//#region src/utils/switchboard.ts\nasync function getDriveIdBySlug(driveUrl, slug) {\n\tif (!driveUrl) return;\n\tconst urlParts = driveUrl.split(\"/\");\n\turlParts.pop();\n\turlParts.pop();\n\turlParts.push(\"drives\");\n\tconst drivesUrl = urlParts.join(\"/\");\n\treturn (await (await fetch(drivesUrl, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tbody: JSON.stringify({\n\t\t\tquery: `\n query getDriveIdBySlug($slug: String!) {\n driveIdBySlug(slug: $slug)\n }\n `,\n\t\t\tvariables: { slug }\n\t\t})\n\t})).json()).data.driveIdBySlug;\n}\nfunction getSlugFromDriveUrl(driveUrl) {\n\treturn driveUrl.split(\"/\").pop();\n}\nfunction getSwitchboardGatewayUrlFromDriveUrl(driveUrl) {\n\tconst urlParts = driveUrl.split(\"/\");\n\turlParts.pop();\n\turlParts.pop();\n\turlParts.push(\"graphql\");\n\treturn urlParts.join(\"/\");\n}\nfunction getDocumentGraphqlQuery() {\n\tconst loc = GetDocumentWithOperationsDocument.loc;\n\tif (!loc) throw new Error(\"GetDocumentWithOperationsDocument is misconfigured, loc is missing.\");\n\treturn loc.source.body;\n}\n/**\n* The base URL of the switchboard that serves a drive's GraphQL channel.\n*\n* The channel URL is `<origin>[<proxy-prefix>]/graphql/r`, so stripping the\n* suffix preserves any proxy prefix (e.g. `/api/reactor`). A URL that does\n* not end with the suffix is unexpected — fall back to its origin.\n*/\nfunction getSwitchboardBaseFromChannelUrl(channelUrl) {\n\tif (channelUrl.endsWith(\"/graphql/r\")) return channelUrl.slice(0, -GQL_CHANNEL_SUFFIX.length);\n\treturn new URL(channelUrl).origin;\n}\n/**\n* The GraphQL name the switchboard exposes a document model under. Mirrors\n* `getDocumentModelSchemaName` on the server (`create-schema.ts`): the root\n* query field and the state type names are all derived from the model's\n* `global.name`.\n*/\nfunction getDocumentModelSchemaName(model) {\n\treturn pascalCase(model.documentModel.global.name.replaceAll(\"/\", \" \"));\n}\nfunction buildStateTypeMap(definitions) {\n\tconst typeMap = /* @__PURE__ */ new Map();\n\tfor (const def of definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) typeMap.set(def.name.value, def);\n\treturn typeMap;\n}\n/**\n* Recursively expands the fields of a state object type into a GraphQL\n* selection. Objects expand their sub-selection (lists expand their item\n* type); enums, scalars, and built-ins are leaves.\n*/\nfunction expandStateFields(typeDef, typeMap) {\n\treturn (typeDef.fields ?? []).map((field) => {\n\t\tconst fieldName = field.name.value;\n\t\tlet typeNode = field.type;\n\t\tif (typeNode.kind === Kind.NON_NULL_TYPE) typeNode = typeNode.type;\n\t\tif (typeNode.kind === Kind.LIST_TYPE) {\n\t\t\tlet itemType = typeNode.type;\n\t\t\tif (itemType.kind === Kind.NON_NULL_TYPE) itemType = itemType.type;\n\t\t\tif (itemType.kind === Kind.LIST_TYPE) throw new Error(`Nested lists are not supported in state selections: ${fieldName}`);\n\t\t\tif (itemType.kind !== Kind.NAMED_TYPE) return fieldName;\n\t\t\tconst itemTypeDef = typeMap.get(itemType.name.value);\n\t\t\tif (!itemTypeDef) return fieldName;\n\t\t\treturn `${fieldName} { ${expandStateFields(itemTypeDef, typeMap)} }`;\n\t\t}\n\t\tif (typeNode.kind !== Kind.NAMED_TYPE) return fieldName;\n\t\tconst typeDef = typeMap.get(typeNode.name.value);\n\t\tif (!typeDef) return fieldName;\n\t\treturn `${fieldName} { ${expandStateFields(typeDef, typeMap)} }`;\n\t}).join(\" \");\n}\n/**\n* Finds the root state object type in a state SDL. Root state types follow\n* the `<Name>State` / `<Name>GlobalState` conventions, and are defined last\n* by convention — the same resolution order the server uses\n* (`extractRootTypeName` in `create-schema.ts`).\n*/\nfunction findRootStateType(definitions, candidates) {\n\tlet lastObjectType = null;\n\tfor (const def of definitions) {\n\t\tif (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;\n\t\tif (candidates.includes(def.name.value)) return def;\n\t\tlastObjectType = def;\n\t}\n\tif (!lastObjectType) throw new Error(\"No root state type found in the document model schema\");\n\treturn lastObjectType;\n}\n/**\n* Derives the subselection for the document's `global` state scope from the\n* model's state SDL (e.g. `name total`), expanding object fields\n* recursively. Throws when the schema is missing, unparseable, or has no\n* root object type — the caller falls back to the generic document query.\n*/\nfunction getDocumentStateSelection(model) {\n\tconst schema = model.documentModel.global.specifications.at(-1)?.state.global.schema;\n\tif (!schema || !schema.trim()) throw new Error(\"Document model has no global state schema\");\n\tconst ast = parse(schema);\n\tconst typeMap = buildStateTypeMap(ast.definitions);\n\tconst documentName = getDocumentModelSchemaName(model);\n\treturn expandStateFields(findRootStateType(ast.definitions, [`${documentName}State`, `${documentName}GlobalState`]), typeMap);\n}\nfunction getLocalStateSelection(localSchema, documentName) {\n\tconst ast = parse(localSchema);\n\tconst typeMap = buildStateTypeMap(ast.definitions);\n\treturn expandStateFields(findRootStateType(ast.definitions, [`${documentName}LocalState`]), typeMap);\n}\n/**\n* Builds a query scoped to a document type's own subgraph root field,\n* selecting the document and its full typed state. The shape mirrors what\n* the switchboard generates per model (`generateNewApiSchema` in\n* `create-schema.ts`): `<Name> { document(identifier:) { document { ...\n* state { auth document global local } } } childIds }`.\n*/\nfunction buildModelScopedQuery(model) {\n\tconst globalState = model.documentModel.global;\n\tconst documentName = getDocumentModelSchemaName(model);\n\tconst globalSelection = getDocumentStateSelection(model);\n\tconst localSchema = globalState.specifications.at(-1)?.state.local.schema ?? \"\";\n\tconst localSelection = localSchema.includes(`type ${documentName}LocalState`) ? getLocalStateSelection(localSchema, documentName) : null;\n\treturn [\n\t\t\"query GetDocument($identifier: String!) {\",\n\t\t` ${documentName} {`,\n\t\t\" document(identifier: $identifier) {\",\n\t\t\" document {\",\n\t\t\" id\",\n\t\t\" name\",\n\t\t\" documentType\",\n\t\t\" state {\",\n\t\t\" auth\",\n\t\t\" document { version hash { algorithm encoding } isDeleted deletedAtUtcIso deletedBy deletionReason }\",\n\t\t` global { ${globalSelection} }`,\n\t\t` ${localSelection ? `local { ${localSelection} }` : \"local\"}`,\n\t\t\" }\",\n\t\t\" }\",\n\t\t\" childIds\",\n\t\t\" }\",\n\t\t\" }\",\n\t\t\"}\"\n\t].join(\"\\n\");\n}\nfunction buildDocumentSubgraphQuery(documentType, identifier, model, authToken) {\n\tlet query;\n\tif (model && model.documentModel.global.id === documentType) try {\n\t\tquery = buildModelScopedQuery(model);\n\t} catch (error) {\n\t\tconsole.warn(\"Could not derive a document-scoped query from the document model, falling back to the generic document query:\", error);\n\t\tquery = getDocumentGraphqlQuery();\n\t}\n\telse query = getDocumentGraphqlQuery();\n\tconst variables = { identifier };\n\tconst headers = authToken ? { Authorization: `Bearer ${authToken}` } : void 0;\n\tconst payload = {\n\t\tdocument: query.trim(),\n\t\tvariables: JSON.stringify(variables, null, 2)\n\t};\n\tif (headers) payload.headers = JSON.stringify(headers);\n\treturn lzString.compressToEncodedURIComponent(JSON.stringify(payload));\n}\nfunction buildDocumentSubgraphUrl(channelUrl, documentType, identifier, model, authToken) {\n\tconst encodedQuery = buildDocumentSubgraphQuery(documentType, identifier, model, authToken);\n\treturn `${getSwitchboardBaseFromChannelUrl(channelUrl)}/explorer?explorerURLState=${encodedQuery}`;\n}\n//#endregion\n//#region src/utils/upgrade-preview.ts\nconst NON_DOMAIN_SCOPES = new Set([\"auth\", \"document\"]);\nfunction isPlainObject(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction walkShapes(before, after, path, added, removed) {\n\tif (isPlainObject(before) && isPlainObject(after)) {\n\t\tconst beforeKeys = Object.keys(before);\n\t\tconst afterKeys = Object.keys(after);\n\t\tfor (const key of afterKeys) {\n\t\t\tconst childPath = path ? `${path}.${key}` : key;\n\t\t\tif (!beforeKeys.includes(key)) {\n\t\t\t\tadded.push(childPath);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\twalkShapes(before[key], after[key], childPath, added, removed);\n\t\t}\n\t\tfor (const key of beforeKeys) if (!afterKeys.includes(key)) removed.push(path ? `${path}.${key}` : key);\n\t\treturn;\n\t}\n\tif (Array.isArray(before) && Array.isArray(after)) {\n\t\tif (before.length > 0 && after.length > 0) walkShapes(before[0], after[0], `${path}[]`, added, removed);\n\t}\n}\n/**\n* Recursively diffs the structural shape of two values, returning dot-paths\n* of keys present in `after` but not `before` (added) and vice versa\n* (removed). Array fields are compared by the shape of a representative\n* element (the first element on each side, when both sides have one) using\n* the `path[]` notation, e.g. `todos[].status`. Only key presence is\n* compared — array length and primitive values are ignored.\n*/\nfunction diffStateShapes(before, after) {\n\tconst added = [];\n\tconst removed = [];\n\twalkShapes(before, after, \"\", added, removed);\n\treturn {\n\t\tadded,\n\t\tremoved\n\t};\n}\n/**\n* Computes a dry-run preview of upgrading `document` to the latest\n* registered version of its document model: the version jump, the upgrade\n* steps that will run, and which state fields will be added or removed.\n* Applies the upgrade reducers against a deep clone of the document, so the\n* original is left untouched.\n*\n* Returns undefined when the registry is unavailable, the document is\n* already at (or above) the latest registered version, or the upgrade path\n* cannot be computed.\n*/\nfunction getDocumentUpgradePreview(document, registry) {\n\tif (!registry) return;\n\tconst documentType = document.header.documentType;\n\tconst fromVersion = document.state.document.version || 1;\n\tlet latestVersion;\n\ttry {\n\t\tlatestVersion = registry.getLatestVersion(documentType);\n\t} catch {\n\t\treturn;\n\t}\n\tif (fromVersion >= latestVersion) return;\n\tlet transitions;\n\ttry {\n\t\ttransitions = registry.computeUpgradePath(documentType, fromVersion, latestVersion);\n\t} catch {\n\t\treturn;\n\t}\n\tconst stubAction = {\n\t\tid: \"\",\n\t\ttype: \"UPGRADE_DOCUMENT\",\n\t\tscope: \"document\",\n\t\ttimestampUtcMs: \"\",\n\t\tinput: {\n\t\t\tdocumentId: document.header.id,\n\t\t\tmodel: documentType,\n\t\t\tfromVersion,\n\t\t\ttoVersion: latestVersion\n\t\t}\n\t};\n\tlet upgraded = structuredClone(document);\n\ttry {\n\t\tfor (const transition of transitions) upgraded = transition.upgradeReducer(upgraded, stubAction);\n\t} catch {\n\t\treturn;\n\t}\n\tconst addedFields = [];\n\tconst removedFields = [];\n\tconst scopes = new Set([...Object.keys(document.state), ...Object.keys(upgraded.state)]);\n\tfor (const scope of scopes) {\n\t\tif (NON_DOMAIN_SCOPES.has(scope)) continue;\n\t\tconst beforeScope = document.state[scope];\n\t\tconst afterScope = upgraded.state[scope];\n\t\tconst { added, removed } = diffStateShapes(beforeScope, afterScope);\n\t\tfor (const path of added) addedFields.push(`${scope}.${path}`);\n\t\tfor (const path of removed) removedFields.push(`${scope}.${path}`);\n\t}\n\treturn {\n\t\tfromVersion,\n\t\ttoVersion: latestVersion,\n\t\tsteps: transitions.map((transition) => ({\n\t\t\ttoVersion: transition.toVersion,\n\t\t\tdescription: transition.description ?? \"\"\n\t\t})),\n\t\taddedFields,\n\t\tremovedFields\n\t};\n}\n//#endregion\n//#region src/hooks/use-get-switchboard-link.ts\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*/\nfunction useGetSwitchboardLink(document) {\n\tconst [drive] = useSelectedDriveSafe();\n\tconst remotes = useSyncList();\n\tconst documentModelModule = useDocumentModelModuleById(document?.header.documentType);\n\tconst isRemoteDrive = useMemo(() => {\n\t\tif (!isDefined(drive)) return false;\n\t\treturn remotes.some((remote) => remote.meta.collectionId.equals(DriveCollectionId$1.forDrive(drive.header.id)));\n\t}, [remotes, drive]);\n\tconst remoteUrl = useMemo(() => {\n\t\tif (!isDefined(drive)) return null;\n\t\ttry {\n\t\t\tconst channelUrl = (remotes.find((remote) => remote.meta.collectionId.equals(DriveCollectionId$1.forDrive(drive.header.id)))?.channel)?.config.url;\n\t\t\tif (typeof channelUrl === \"string\") return channelUrl;\n\t\t\treturn null;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error determining remote URL:\", error);\n\t\t\treturn null;\n\t\t}\n\t}, [remotes, drive]);\n\tconst renown = useRenown();\n\tconst user = useUser();\n\treturn useMemo(() => {\n\t\tif (!isRemoteDrive || !document?.header.id || !remoteUrl) return null;\n\t\treturn async () => {\n\t\t\tconst token = user?.address ? await renown?.getBearerToken({\n\t\t\t\texpiresIn: 600,\n\t\t\t\taud: remoteUrl\n\t\t\t}) : void 0;\n\t\t\treturn buildDocumentSubgraphUrl(remoteUrl, document.header.documentType, document.header.id, documentModelModule, token);\n\t\t};\n\t}, [\n\t\tisRemoteDrive,\n\t\tremoteUrl,\n\t\tdocument,\n\t\tdocumentModelModule,\n\t\tuser,\n\t\trenown\n\t]);\n}\n//#endregion\n//#region src/hooks/use-on-drop-file.ts\nconst useOnDropFile = (documentTypesOverride) => {\n\tconst selectedDriveId = useSelectedDriveId();\n\tconst selectedFolder = useSelectedFolder();\n\tconst documentTypes = useDocumentTypes();\n\tconst onDropFile = async (file, targetFolder, onProgress, resolveConflict) => {\n\t\tif (!selectedDriveId) {\n\t\t\tconsole.warn(\"No selected drive - upload skipped\");\n\t\t\treturn;\n\t\t}\n\t\treturn await addFileWithProgress(file, selectedDriveId, file.name.replace(/\\..+/gim, \"\"), targetFolder?.id ?? selectedFolder?.id, onProgress, documentTypesOverride ?? documentTypes, resolveConflict);\n\t};\n\treturn onDropFile;\n};\n//#endregion\n//#region src/hooks/user-permissions.ts\nfunction useUserPermissions() {\n\tconst user = useUser();\n\tconst allowList = useAllowList();\n\tif (!allowList) return {\n\t\tisAllowedToCreateDocuments: true,\n\t\tisAllowedToEditDocuments: true\n\t};\n\treturn {\n\t\tisAllowedToCreateDocuments: allowList.includes(user?.address ?? \"\"),\n\t\tisAllowedToEditDocuments: allowList.includes(user?.address ?? \"\")\n\t};\n}\n//#endregion\n//#region src/hooks/attachment-progress.ts\nconst IDLE_PROGRESS = {\n\tpercent: 0,\n\tloaded: 0,\n\ttotal: void 0,\n\tindeterminate: false\n};\nfunction toProgressState(progress) {\n\treturn {\n\t\tpercent: toPercent(progress),\n\t\tloaded: progress.loaded,\n\t\ttotal: progress.total,\n\t\tindeterminate: progress.indeterminate\n\t};\n}\nfunction toPercent(progress) {\n\tif (progress.indeterminate) return 0;\n\tif (progress.total === void 0) return 0;\n\tif (progress.total === 0) return 100;\n\tconst percent = progress.loaded / progress.total * 100;\n\tif (percent < 0) return 0;\n\treturn percent > 100 ? 100 : percent;\n}\n/** Terminal frame for a transfer of `total` bytes, written on resolution. */\nfunction doneProgress(total) {\n\treturn {\n\t\tpercent: 100,\n\t\tloaded: total,\n\t\ttotal,\n\t\tindeterminate: false\n\t};\n}\n/**\n* Second coalescer, on top of the client's time throttle, keyed on what\n* actually changed for a UI rather than on elapsed time:\n*\n* - a determinate tick commits only when the whole percent changes, capping\n* commits at ~101 per transfer no matter how many byte events arrive;\n* - a tick with no position — indeterminate, or determinate with no\n* denominator — has no percent to change, so it falls back to a time\n* budget; otherwise a byte counter with no denominator would never update;\n* - gaining or losing a position always commits, since the UI switches between\n* a spinner and a bar. Stage entry is indeterminate at 0%, so without this\n* the first byte event of a stage reads as \"still 0%\" and is dropped, and a\n* 50 MB upload sits on the spinner until it crosses 1%;\n* - a stage change always commits, because the label changed.\n*\n* Uses `Date.now()` so tests can drive it with fake timers.\n*/\nfunction createProgressGate(options) {\n\tconst budget = options?.indeterminateCommitMs ?? 150;\n\tconst now = options?.now ?? (() => Date.now());\n\tlet lastStage;\n\tlet lastPercent = -1;\n\tlet lastIndeterminate;\n\tlet lastTotalKnown;\n\tlet lastCommitAt = Number.NEGATIVE_INFINITY;\n\treturn (progress) => {\n\t\tconst commit = () => {\n\t\t\tlastStage = progress.stage;\n\t\t\tlastPercent = Math.floor(toPercent(progress));\n\t\t\tlastIndeterminate = progress.indeterminate;\n\t\t\tlastTotalKnown = progress.total !== void 0;\n\t\t\tlastCommitAt = now();\n\t\t\treturn true;\n\t\t};\n\t\tif (progress.stage !== lastStage) return commit();\n\t\tif (progress.indeterminate !== lastIndeterminate) return commit();\n\t\tif (progress.total !== void 0 !== lastTotalKnown) return commit();\n\t\tif (progress.indeterminate || progress.total === void 0) return now() - lastCommitAt >= budget ? commit() : false;\n\t\treturn Math.floor(toPercent(progress)) !== lastPercent ? commit() : false;\n\t};\n}\n//#endregion\n//#region src/hooks/use-attachments.ts\n/**\n* One client per service, shared across every component.\n*\n* A per-component `useMemo` handed each caller its own wrapper, so nothing\n* client-scoped could ever be shared or cached. Keyed weakly so a replaced\n* service is collectable.\n*/\nconst clientsByService = /* @__PURE__ */ new WeakMap();\nfunction clientFor(service) {\n\tconst existing = clientsByService.get(service);\n\tif (existing) return existing;\n\tconst created = createAttachmentClient(service);\n\tclientsByService.set(service, created);\n\treturn created;\n}\n/** Returns an IAttachmentClient wrapping the current IAttachmentService, or undefined if none is set. */\nfunction useAttachments() {\n\tconst service = useAttachmentService();\n\treturn service ? clientFor(service) : void 0;\n}\nconst DEFAULT_PREVIEW_RETRIES = 3;\nconst DEFAULT_PREVIEW_RETRY_DELAY_MS = 3e3;\nconst IDLE_PREVIEW = {\n\turl: void 0,\n\theader: void 0,\n\tloading: false,\n\terror: void 0,\n\tstage: \"idle\",\n\tprogress: IDLE_PROGRESS,\n\tattempt: 0,\n\tmaxAttempts: 1,\n\tlastError: void 0\n};\n/**\n* Document-authorized inline preview of an attachment. Downloads the bytes\n* through the normal authorized flow, exposes them as an object URL, and\n* revokes it automatically on unmount and whenever documentId/ref change —\n* editors never touch blobs or URL lifecycles. Failed attempts are retried\n* (`retries` × `retryDelayMs`) so a preview requested right after attaching\n* appears as soon as the server's reference index catches up. Progress resets\n* per attempt; nothing resumes.\n*/\nfunction useAttachmentPreview({ documentId, ref, retries = DEFAULT_PREVIEW_RETRIES, retryDelayMs = DEFAULT_PREVIEW_RETRY_DELAY_MS }) {\n\tconst client = useAttachments();\n\tconst [state, setState] = useState(IDLE_PREVIEW);\n\tuseEffect(() => {\n\t\tif (!client || !ref) {\n\t\t\tsetState(IDLE_PREVIEW);\n\t\t\treturn;\n\t\t}\n\t\tconst maxAttempts = retries + 1;\n\t\tlet live = true;\n\t\tconst controller = new AbortController();\n\t\tlet revoke;\n\t\tlet timer;\n\t\tlet attempt = 0;\n\t\tsetState({\n\t\t\t...IDLE_PREVIEW,\n\t\t\tloading: true,\n\t\t\tattempt: 1,\n\t\t\tmaxAttempts\n\t\t});\n\t\tconst load = () => {\n\t\t\tattempt += 1;\n\t\t\tconst gate = createProgressGate();\n\t\t\tconst attemptNumber = attempt;\n\t\t\tclient.downloadObjectUrl({\n\t\t\t\tdocumentId,\n\t\t\t\tref,\n\t\t\t\tsignal: controller.signal\n\t\t\t}, { onProgress: (progress) => {\n\t\t\t\tif (!live) return;\n\t\t\t\tif (progress.stage === \"done\" || progress.stage === \"error\") return;\n\t\t\t\tif (!gate(progress)) return;\n\t\t\t\tsetState((prev) => ({\n\t\t\t\t\t...prev,\n\t\t\t\t\tstage: progress.stage,\n\t\t\t\t\tprogress: toProgressState(progress)\n\t\t\t\t}));\n\t\t\t} }).then((result) => {\n\t\t\t\tif (!live) {\n\t\t\t\t\tresult.revoke();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\trevoke = result.revoke;\n\t\t\t\tsetState((prev) => ({\n\t\t\t\t\t...prev,\n\t\t\t\t\turl: result.url,\n\t\t\t\t\theader: result.header,\n\t\t\t\t\tloading: false,\n\t\t\t\t\terror: void 0,\n\t\t\t\t\tstage: \"done\",\n\t\t\t\t\tprogress: doneProgress(result.header.sizeBytes),\n\t\t\t\t\tattempt: attemptNumber,\n\t\t\t\t\tmaxAttempts\n\t\t\t\t}));\n\t\t\t}).catch((err) => {\n\t\t\t\tif (!live) return;\n\t\t\t\tconst error = err instanceof Error ? err : new Error(String(err));\n\t\t\t\tif (attempt < maxAttempts) {\n\t\t\t\t\tsetState((prev) => ({\n\t\t\t\t\t\t...prev,\n\t\t\t\t\t\tlastError: error,\n\t\t\t\t\t\tattempt: attempt + 1,\n\t\t\t\t\t\tprogress: IDLE_PROGRESS,\n\t\t\t\t\t\tstage: \"idle\"\n\t\t\t\t\t}));\n\t\t\t\t\ttimer = setTimeout(load, retryDelayMs);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsetState((prev) => ({\n\t\t\t\t\t...prev,\n\t\t\t\t\turl: void 0,\n\t\t\t\t\theader: void 0,\n\t\t\t\t\tloading: false,\n\t\t\t\t\terror,\n\t\t\t\t\tlastError: error,\n\t\t\t\t\tstage: \"error\",\n\t\t\t\t\tattempt: attemptNumber,\n\t\t\t\t\tmaxAttempts\n\t\t\t\t}));\n\t\t\t});\n\t\t};\n\t\tload();\n\t\treturn () => {\n\t\t\tlive = false;\n\t\t\tif (timer !== void 0) clearTimeout(timer);\n\t\t\tcontroller.abort();\n\t\t\trevoke?.();\n\t\t};\n\t}, [\n\t\tclient,\n\t\tdocumentId,\n\t\tref,\n\t\tretries,\n\t\tretryDelayMs\n\t]);\n\treturn state;\n}\nconst IDLE_UPLOAD = {\n\tstage: \"idle\",\n\tprogress: IDLE_PROGRESS,\n\tresult: void 0,\n\terror: void 0\n};\n/**\n* Full attachment preprocess + upload lifecycle with byte-level progress.\n*\n* The two-call split is kept on purpose: the ref must reach the document\n* before the bytes are committed, so callers preprocess, dispatch the\n* operation, then upload. The second call routes through `client.upload`\n* rather than reimplementing the flow, which is what makes progress, dedup\n* reporting and cancellation identical to the non-React path.\n*/\nfunction useAttachmentUpload() {\n\tconst [state, setState] = useState(IDLE_UPLOAD);\n\tconst client = useAttachments();\n\tconst abortRef = useRef(void 0);\n\tconst mountedRef = useRef(true);\n\tconst runIdRef = useRef(0);\n\tuseEffect(() => {\n\t\tmountedRef.current = true;\n\t\treturn () => {\n\t\t\tmountedRef.current = false;\n\t\t};\n\t}, []);\n\treturn {\n\t\tpreprocess: useCallback(async (file) => {\n\t\t\tif (!client) throw new Error(\"AttachmentClient not available\");\n\t\t\tconst runId = ++runIdRef.current;\n\t\t\tsetState({\n\t\t\t\t...IDLE_UPLOAD,\n\t\t\t\tstage: \"hashing\"\n\t\t\t});\n\t\t\ttry {\n\t\t\t\treturn await client.preprocess(file);\n\t\t\t} catch (err) {\n\t\t\t\tconst error = err instanceof Error ? err : new Error(String(err));\n\t\t\t\tif (mountedRef.current && runId === runIdRef.current) setState((prev) => ({\n\t\t\t\t\t...prev,\n\t\t\t\t\tstage: \"error\",\n\t\t\t\t\terror\n\t\t\t\t}));\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}, [client]),\n\t\tupload: useCallback(async (results) => {\n\t\t\tif (!client) throw new Error(\"AttachmentClient not available\");\n\t\t\tconst runId = ++runIdRef.current;\n\t\t\tconst controller = new AbortController();\n\t\t\tabortRef.current = controller;\n\t\t\tconst gate = createProgressGate();\n\t\t\tconst isCurrent = () => mountedRef.current && runId === runIdRef.current;\n\t\t\tsetState({\n\t\t\t\t...IDLE_UPLOAD,\n\t\t\t\tstage: \"reserving\"\n\t\t\t});\n\t\t\tlet uploadResult;\n\t\t\ttry {\n\t\t\t\tuploadResult = await client.upload({\n\t\t\t\t\tpreprocessed: results,\n\t\t\t\t\tsignal: controller.signal\n\t\t\t\t}, { onProgress: (progress) => {\n\t\t\t\t\tif (!isCurrent()) return;\n\t\t\t\t\tif (progress.stage === \"done\" || progress.stage === \"error\") return;\n\t\t\t\t\tif (!gate(progress)) return;\n\t\t\t\t\tsetState((prev) => ({\n\t\t\t\t\t\t...prev,\n\t\t\t\t\t\tstage: progress.stage,\n\t\t\t\t\t\tprogress: toProgressState(progress)\n\t\t\t\t\t}));\n\t\t\t\t} });\n\t\t\t} catch (err) {\n\t\t\t\tconst error = err instanceof Error ? err : new Error(String(err));\n\t\t\t\tif (isCurrent()) setState((prev) => ({\n\t\t\t\t\t...prev,\n\t\t\t\t\tstage: \"error\",\n\t\t\t\t\terror\n\t\t\t\t}));\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\tif (isCurrent()) setState((prev) => ({\n\t\t\t\t...prev,\n\t\t\t\tstage: \"done\",\n\t\t\t\tprogress: doneProgress(results.sizeBytes),\n\t\t\t\tresult: uploadResult,\n\t\t\t\terror: void 0\n\t\t\t}));\n\t\t}, [client]),\n\t\tcancel: useCallback(() => {\n\t\t\tabortRef.current?.abort();\n\t\t}, []),\n\t\treset: useCallback(() => {\n\t\t\trunIdRef.current += 1;\n\t\t\tabortRef.current?.abort();\n\t\t\tabortRef.current = void 0;\n\t\t\tsetState(IDLE_UPLOAD);\n\t\t}, []),\n\t\tstage: state.stage,\n\t\tprogress: state.progress,\n\t\tresult: state.result,\n\t\terror: state.error\n\t};\n}\n//#endregion\n//#region src/pglite/drop.ts\nasync function dropTablesInSchema(pg, schema) {\n\tawait 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}\nasync function truncateAllTables(pg, schema = REACTOR_SCHEMA$1) {\n\tawait dropTablesInSchema(pg, schema);\n}\nasync function dropAllReactorStorage(pg) {\n\tawait dropTablesInSchema(pg, REACTOR_SCHEMA$1);\n\tawait dropTablesInSchema(pg, \"public\");\n}\n//#endregion\n//#region src/reactor.ts\nconst DEFAULT_DEBOUNCE_DELAY_MS = 200;\nconst DEFAULT_IMMEDIATE_THRESHOLD_MS = 1e3;\nasync function _refreshReactorData(reactor) {\n\tsetDrives(await getDrives(reactor));\n}\nasync function _refreshReactorDataClient(reactor) {\n\tif (!reactor) return;\n\tsetDrives(await getDrives(reactor));\n}\nfunction createDebouncedRefreshReactorData(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {\n\tlet timeout = null;\n\tlet lastRefreshTime = 0;\n\treturn (reactor, immediate = false) => {\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastRefresh = now - lastRefreshTime;\n\t\tif (timeout !== null) clearTimeout(timeout);\n\t\tif (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n\t\t\tlastRefreshTime = now;\n\t\t\treturn _refreshReactorData(reactor);\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tlastRefreshTime = Date.now();\n\t\t\t\t_refreshReactorData(reactor).then(resolve);\n\t\t\t}, debounceDelayMs);\n\t\t});\n\t};\n}\nfunction createDebouncedRefreshReactorDataClient(debounceDelayMs = DEFAULT_DEBOUNCE_DELAY_MS, immediateThresholdMs = DEFAULT_IMMEDIATE_THRESHOLD_MS) {\n\tlet timeout = null;\n\tlet lastRefreshTime = 0;\n\treturn (reactor, immediate = false) => {\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastRefresh = now - lastRefreshTime;\n\t\tif (timeout !== null) clearTimeout(timeout);\n\t\tif (immediate || timeSinceLastRefresh >= immediateThresholdMs) {\n\t\t\tlastRefreshTime = now;\n\t\t\treturn _refreshReactorDataClient(reactor);\n\t\t}\n\t\treturn new Promise((resolve) => {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tlastRefreshTime = Date.now();\n\t\t\t\t_refreshReactorDataClient(reactor).then(resolve);\n\t\t\t}, debounceDelayMs);\n\t\t});\n\t};\n}\nconst refreshReactorData = createDebouncedRefreshReactorData();\nconst refreshReactorDataClient = createDebouncedRefreshReactorDataClient();\n//#endregion\n//#region src/remote-controller/action-tracker.ts\n/**\n* Tracks pending actions with their operation context (prevOpHash, prevOpIndex).\n* Actions are accumulated until flushed (on push).\n*/\nvar ActionTracker = class {\n\tpending = [];\n\t/** Track a new action with its operation context. */\n\ttrack(action, prevOpHash, prevOpIndex) {\n\t\tthis.pending.push({\n\t\t\taction,\n\t\t\tprevOpHash,\n\t\t\tprevOpIndex\n\t\t});\n\t}\n\t/** Flush all pending actions and return them. Clears the internal queue. */\n\tflush() {\n\t\tconst actions = this.pending;\n\t\tthis.pending = [];\n\t\treturn actions;\n\t}\n\t/** Number of pending actions. */\n\tget count() {\n\t\treturn this.pending.length;\n\t}\n\t/** Prepend previously flushed actions back to the queue (for retry on failure). */\n\trestore(actions) {\n\t\tthis.pending = [...actions, ...this.pending];\n\t}\n\t/** Clear all pending actions without returning them. */\n\tclear() {\n\t\tthis.pending = [];\n\t}\n};\n//#endregion\n//#region src/remote-controller/remote-client.ts\n/**\n* Thin facade over the GraphQL SDK for remote document operations.\n*/\nconst DEFAULT_PAGE_SIZE = 100;\nvar RemoteClient = class {\n\tpageSize;\n\tconstructor(client, pageSize) {\n\t\tthis.client = client;\n\t\tthis.pageSize = pageSize ?? DEFAULT_PAGE_SIZE;\n\t}\n\t/** Fetch a document by identifier. Returns null if not found. */\n\tasync getDocument(identifier, branch) {\n\t\treturn (await this.client.GetDocument({\n\t\t\tidentifier,\n\t\t\tview: branch ? { branch } : void 0\n\t\t})).document ?? null;\n\t}\n\t/**\n\t* Fetch a document and its operations.\n\t*\n\t* When scopes are provided and BatchGetDocumentWithOperations is available,\n\t* fetches the document and per-scope operations in a single HTTP request.\n\t* Otherwise falls back to GetDocumentWithOperations for the first page,\n\t* then paginates remaining operations per scope.\n\t*/\n\tasync getDocumentWithOperations(identifier, branch, sinceRevision, scopes) {\n\t\tif (this.client.BatchGetDocumentWithOperations && scopes && scopes.length > 0) return this.batchGetDocumentWithOperations(identifier, branch, sinceRevision, scopes);\n\t\tconst result = await this.client.GetDocumentWithOperations({\n\t\t\tidentifier,\n\t\t\tview: branch ? { branch } : void 0,\n\t\t\toperationsPaging: {\n\t\t\t\tlimit: this.pageSize,\n\t\t\t\tcursor: null\n\t\t\t}\n\t\t});\n\t\tif (!result.document) return null;\n\t\tconst doc = result.document.document;\n\t\tconst opsPage = doc.operations;\n\t\tconst operationsByScope = {};\n\t\tif (opsPage) for (const op of opsPage.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\tconst expectedTotal = doc.revisionsList.reduce((sum, r) => sum + r.revision, 0);\n\t\tif ((opsPage?.items.length ?? 0) >= expectedTotal) return {\n\t\t\tdocument: doc,\n\t\t\tchildIds: result.document.childIds,\n\t\t\toperations: { operationsByScope }\n\t\t};\n\t\tconst allScopes = doc.revisionsList.map((r) => r.scope);\n\t\tconst allOps = await this.getAllOperations(doc.id, branch, sinceRevision, allScopes);\n\t\treturn {\n\t\t\tdocument: doc,\n\t\t\tchildIds: result.document.childIds,\n\t\t\toperations: allOps\n\t\t};\n\t}\n\t/**\n\t* Fetch document + per-scope operations in a single HTTP request\n\t* via BatchGetDocumentWithOperations, then paginate any remaining pages.\n\t*/\n\tasync batchGetDocumentWithOperations(identifier, branch, sinceRevision, scopes) {\n\t\tconst view = branch ? { branch } : void 0;\n\t\tconst filters = scopes.map((scope) => ({\n\t\t\tdocumentId: identifier,\n\t\t\tbranch: branch ?? null,\n\t\t\tsinceRevision: sinceRevision?.[scope] ?? 0,\n\t\t\tscopes: [scope]\n\t\t}));\n\t\tconst pagings = scopes.map(() => ({\n\t\t\tlimit: this.pageSize,\n\t\t\tcursor: null\n\t\t}));\n\t\tconst result = await this.client.BatchGetDocumentWithOperations(identifier, view, filters, pagings);\n\t\tif (!result.document) return null;\n\t\tconst operationsByScope = {};\n\t\tlet pending = [];\n\t\tfor (let i = 0; i < scopes.length; i++) {\n\t\t\tconst page = result.operations[i];\n\t\t\tfor (const op of page.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\t\tif (page.hasNextPage && page.cursor) pending.push({\n\t\t\t\tscope: scopes[i],\n\t\t\t\tfilter: filters[i],\n\t\t\t\tcursor: page.cursor\n\t\t\t});\n\t\t}\n\t\twhile (pending.length > 0) {\n\t\t\tconst pages = await this.fetchOperationPages(pending.map((p) => p.filter), pending.map((p) => ({\n\t\t\t\tlimit: this.pageSize,\n\t\t\t\tcursor: p.cursor\n\t\t\t})));\n\t\t\tconst nextPending = [];\n\t\t\tfor (let i = 0; i < pending.length; i++) {\n\t\t\t\tconst page = pages[i];\n\t\t\t\tfor (const op of page.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\t\t\tif (page.hasNextPage && page.cursor) nextPending.push({\n\t\t\t\t\t...pending[i],\n\t\t\t\t\tcursor: page.cursor\n\t\t\t\t});\n\t\t\t}\n\t\t\tpending = nextPending;\n\t\t}\n\t\treturn {\n\t\t\tdocument: result.document.document,\n\t\t\tchildIds: result.document.childIds,\n\t\t\toperations: { operationsByScope }\n\t\t};\n\t}\n\t/**\n\t* Fetch all operations for a document, paginating through all pages.\n\t* Each scope is queried individually because the API only returns\n\t* pagination cursors for single-scope queries.\n\t*/\n\tasync getAllOperations(documentId, branch, sinceRevision, scopes) {\n\t\tif (scopes && scopes.length > 0) {\n\t\t\tconst operationsByScope = {};\n\t\t\tlet pending = scopes.map((scope) => ({\n\t\t\t\tscope,\n\t\t\t\tfilter: {\n\t\t\t\t\tdocumentId,\n\t\t\t\t\tbranch: branch ?? null,\n\t\t\t\t\tsinceRevision: sinceRevision?.[scope] ?? 0,\n\t\t\t\t\tscopes: [scope]\n\t\t\t\t},\n\t\t\t\tcursor: null\n\t\t\t}));\n\t\t\twhile (pending.length > 0) {\n\t\t\t\tconst pages = await this.fetchOperationPages(pending.map((p) => p.filter), pending.map((p) => ({\n\t\t\t\t\tlimit: this.pageSize,\n\t\t\t\t\tcursor: p.cursor\n\t\t\t\t})));\n\t\t\t\tconst nextPending = [];\n\t\t\t\tfor (let i = 0; i < pending.length; i++) {\n\t\t\t\t\tconst page = pages[i];\n\t\t\t\t\tfor (const op of page.items) (operationsByScope[op.action.scope] ??= []).push(op);\n\t\t\t\t\tif (page.hasNextPage && page.cursor) nextPending.push({\n\t\t\t\t\t\t...pending[i],\n\t\t\t\t\t\tcursor: page.cursor\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tpending = nextPending;\n\t\t\t}\n\t\t\treturn { operationsByScope };\n\t\t}\n\t\treturn this.fetchOperationsForScope(documentId, branch);\n\t}\n\t/**\n\t* Fetch one page of operations per filter.\n\t* Uses the composed query (single HTTP request) when available,\n\t* otherwise falls back to parallel individual requests.\n\t*/\n\tasync fetchOperationPages(filters, pagings) {\n\t\tif (this.client.BatchGetDocumentOperations) return this.client.BatchGetDocumentOperations(filters, pagings);\n\t\treturn Promise.all(filters.map((filter, i) => this.client.GetDocumentOperations({\n\t\t\tfilter,\n\t\t\tpaging: pagings[i]\n\t\t}).then((r) => r.documentOperations)));\n\t}\n\t/** Fetch all pages of operations for a single scope (or all scopes if none specified). */\n\tasync fetchOperationsForScope(documentId, branch, sinceRevision, scope) {\n\t\tconst operationsByScope = {};\n\t\tlet cursor;\n\t\tlet hasNextPage = true;\n\t\twhile (hasNextPage) {\n\t\t\tconst page = (await this.client.GetDocumentOperations({\n\t\t\t\tfilter: {\n\t\t\t\t\tdocumentId,\n\t\t\t\t\tbranch: branch ?? null,\n\t\t\t\t\tsinceRevision: sinceRevision ?? 0,\n\t\t\t\t\tscopes: scope ? [scope] : null\n\t\t\t\t},\n\t\t\t\tpaging: {\n\t\t\t\t\tlimit: this.pageSize,\n\t\t\t\t\tcursor: cursor ?? null\n\t\t\t\t}\n\t\t\t})).documentOperations;\n\t\t\tfor (const op of page.items) {\n\t\t\t\tconst s = op.action.scope;\n\t\t\t\t(operationsByScope[s] ??= []).push(op);\n\t\t\t}\n\t\t\thasNextPage = page.hasNextPage;\n\t\t\tcursor = page.cursor;\n\t\t}\n\t\treturn { operationsByScope };\n\t}\n\t/**\n\t* Push actions to an existing document via MutateDocument.\n\t*\n\t* Takes the wire shape rather than an in-process `Action`: a signature is a\n\t* tuple in one and a string in the other, so the caller projects before it\n\t* gets here.\n\t*/\n\tasync pushActions(documentIdentifier, actions, branch) {\n\t\treturn (await this.client.MutateDocument({\n\t\t\tdocumentIdentifier,\n\t\t\tactions,\n\t\t\tbranch\n\t\t})).mutateDocument;\n\t}\n\t/** Create a new document on the remote. */\n\tasync createDocument(document, parentIdentifier) {\n\t\treturn (await this.client.CreateDocument({\n\t\t\tdocument,\n\t\t\tparentIdentifier: parentIdentifier ?? null\n\t\t})).createDocument;\n\t}\n\t/** Create an empty document of a given type on the remote. */\n\tasync createEmptyDocument(documentType, parentIdentifier) {\n\t\treturn (await this.client.CreateEmptyDocument({\n\t\t\tdocumentType,\n\t\t\tparentIdentifier: parentIdentifier ?? null\n\t\t})).createEmptyDocument;\n\t}\n\t/** Delete a document on the remote. Returns true if successful. */\n\tasync deleteDocument(identifier, propagate) {\n\t\treturn (await this.client.DeleteDocument({\n\t\t\tidentifier,\n\t\t\tpropagate\n\t\t})).deleteDocument;\n\t}\n};\n//#endregion\n//#region src/remote-controller/remote-controller.ts\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*/\nvar RemoteDocumentController = class RemoteDocumentController {\n\tinner;\n\tremoteClient;\n\ttracker = new ActionTracker();\n\toptions;\n\tdocumentId;\n\tremoteRevision = {};\n\thasPulled = false;\n\tpushScheduled = false;\n\tpushQueue = Promise.resolve();\n\tlisteners = [];\n\tconstructor(inner, options) {\n\t\tthis.inner = inner;\n\t\tthis.options = options;\n\t\tthis.documentId = options.documentId ?? \"\";\n\t\tthis.remoteClient = new RemoteClient(options.client, options.operationsPageSize);\n\t\tthis.setupActionInterceptors();\n\t}\n\tget header() {\n\t\treturn this.inner.header;\n\t}\n\tget state() {\n\t\treturn this.inner.state;\n\t}\n\tget operations() {\n\t\treturn this.inner.operations;\n\t}\n\tget document() {\n\t\treturn this.inner.document;\n\t}\n\tget status() {\n\t\treturn {\n\t\t\tpendingActionCount: this.tracker.count,\n\t\t\tconnected: this.documentId !== \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tremoteRevision: { ...this.remoteRevision }\n\t\t};\n\t}\n\t/** Register a listener for document changes. Returns an unsubscribe function. */\n\tonChange(listener) {\n\t\tthis.listeners.push(listener);\n\t\treturn () => {\n\t\t\tthis.listeners = this.listeners.filter((l) => l !== listener);\n\t\t};\n\t}\n\tnotifyListeners(source) {\n\t\tif (this.listeners.length === 0) return;\n\t\tconst event = {\n\t\t\tsource,\n\t\t\tdocument: this.document\n\t\t};\n\t\tfor (const listener of this.listeners) listener(event);\n\t}\n\t/** Push all pending actions to remote, then pull latest state. */\n\tasync push() {\n\t\tlet tracked = this.tracker.flush();\n\t\tif (tracked.length === 0 && this.documentId !== \"\") return {\n\t\t\tremoteDocument: await this.pull(),\n\t\t\tactionCount: 0,\n\t\t\toperations: []\n\t\t};\n\t\ttry {\n\t\t\tawait this.ensureRemoteDocument();\n\t\t\tif (this.options.onConflict && tracked.length > 0) tracked = await this.handleConflicts(tracked, this.options.onConflict);\n\t\t} catch (error) {\n\t\t\tthis.tracker.restore(tracked);\n\t\t\tthrow error;\n\t\t}\n\t\tlet pushedActions = [];\n\t\ttry {\n\t\t\tif (tracked.length > 0) {\n\t\t\t\tconst actions = await this.prepareActionsForPush(tracked);\n\t\t\t\tpushedActions = actions;\n\t\t\t\tawait this.remoteClient.pushActions(this.documentId, actions.map(toTransportAction), this.options.branch);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.tracker.restore(tracked);\n\t\t\tthrow error;\n\t\t}\n\t\treturn {\n\t\t\tremoteDocument: await this.pull(),\n\t\t\tactionCount: tracked.length,\n\t\t\toperations: pushedActions\n\t\t};\n\t}\n\t/** Delete the document on the remote. */\n\tasync delete(propagate) {\n\t\tif (this.documentId === \"\") throw new Error(\"Cannot delete: no document ID set\");\n\t\treturn await this.remoteClient.deleteDocument(this.documentId, propagate);\n\t}\n\t/** Pull latest state from remote, replacing local document. Returns the remote document data. */\n\tasync pull() {\n\t\tif (this.documentId === \"\") throw new Error(\"Cannot pull: no document ID set\");\n\t\tconst { remoteDoc, operations } = await this.fetchDocumentAndOperations();\n\t\tconst pulledDocument = buildPulledDocument(remoteDoc, operations, this.inner.module.utils.createDocument(), this.options.branch ?? \"main\");\n\t\tconst ControllerClass = this.inner.constructor;\n\t\tthis.inner = new ControllerClass(pulledDocument);\n\t\tthis.setupActionInterceptors();\n\t\tthis.tracker.clear();\n\t\tthis.remoteRevision = extractRevisionMap(remoteDoc.revisionsList);\n\t\tthis.notifyListeners(\"pull\");\n\t\treturn remoteDoc;\n\t}\n\t/**\n\t* Pull an existing document from remote and create a controller for it.\n\t*/\n\tstatic async pull(ControllerClass, options) {\n\t\tconst remote = new RemoteDocumentController(new ControllerClass(), options);\n\t\tif (options.documentId) await remote.pull();\n\t\treturn remote;\n\t}\n\t/**\n\t* Wrap an existing controller instance with remote capabilities.\n\t* Pending local actions on the inner controller are NOT tracked\n\t* (only new actions through the remote controller are tracked).\n\t*/\n\tstatic from(controller, options) {\n\t\treturn new RemoteDocumentController(controller, options);\n\t}\n\t/** Create the document on the remote if it doesn't exist yet. */\n\tasync ensureRemoteDocument() {\n\t\tif (this.documentId !== \"\") return;\n\t\tthis.documentId = (await this.remoteClient.createEmptyDocument(this.inner.header.documentType, this.options.parentIdentifier)).id;\n\t}\n\t/** Set up interceptors for all action methods on the inner controller. */\n\tsetupActionInterceptors() {\n\t\tconst module = this.inner[\"module\"];\n\t\tfor (const actionType in module.actions) {\n\t\t\tif (actionType in RemoteDocumentController.prototype) continue;\n\t\t\tObject.defineProperty(this, actionType, {\n\t\t\t\tvalue: (input) => {\n\t\t\t\t\tconst opCountsBefore = {};\n\t\t\t\t\tfor (const scope in this.inner.operations) opCountsBefore[scope] = this.inner.operations[scope].length;\n\t\t\t\t\tthis.inner[actionType](input);\n\t\t\t\t\tconst newOp = this.findNewOperation(opCountsBefore);\n\t\t\t\t\tconst prevOp = newOp ? this.getLastOperationInScope(newOp.action.scope, newOp) : void 0;\n\t\t\t\t\tconst prevOpHash = prevOp?.hash ?? \"\";\n\t\t\t\t\tconst prevOpIndex = prevOp?.index ?? -1;\n\t\t\t\t\tif (!newOp) return this;\n\t\t\t\t\tthis.tracker.track(newOp.action, prevOpHash, prevOpIndex);\n\t\t\t\t\tthis.notifyListeners(\"action\");\n\t\t\t\t\tif (this.options.mode === \"streaming\") this.schedulePush();\n\t\t\t\t\treturn this;\n\t\t\t\t},\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Find the new operation added after applying an action,\n\t* by comparing current operation counts against a previous snapshot.\n\t*/\n\tfindNewOperation(opCountsBefore) {\n\t\tconst ops = this.inner.operations;\n\t\tfor (const scope in ops) {\n\t\t\tconst scopeOps = ops[scope];\n\t\t\tconst prevCount = opCountsBefore[scope] ?? 0;\n\t\t\tif (scopeOps.length > prevCount) return scopeOps[scopeOps.length - 1];\n\t\t}\n\t}\n\t/**\n\t* Get the last operation in a specific scope, optionally excluding\n\t* a given operation (e.g. the one just added).\n\t*/\n\tgetLastOperationInScope(scope, excludeOp) {\n\t\tconst scopeOps = this.inner.operations[scope];\n\t\tif (scopeOps.length === 0) return void 0;\n\t\tfor (let i = scopeOps.length - 1; i >= 0; i--) if (scopeOps[i] !== excludeOp) return scopeOps[i];\n\t}\n\t/**\n\t* Detect and handle conflicts between local pending actions and remote state.\n\t* Returns the (possibly rebased) tracked actions to push.\n\t*/\n\tasync handleConflicts(localTracked, strategy) {\n\t\tconst remoteResult = await this.remoteClient.getDocument(this.documentId, this.options.branch);\n\t\tif (!remoteResult) throw new Error(`Document \"${this.documentId}\" not found on remote`);\n\t\tconst currentRevision = extractRevisionMap(remoteResult.document.revisionsList);\n\t\tconst localScopes = new Set(localTracked.map((t) => t.action.scope));\n\t\tif (!hasRevisionConflict(currentRevision, this.remoteRevision, localScopes)) return localTracked;\n\t\tconst conflictingScopes = [...localScopes].filter((scope) => (currentRevision[scope] ?? 0) > (this.remoteRevision[scope] ?? 0));\n\t\tconst { operationsByScope } = await this.remoteClient.getAllOperations(this.documentId, this.options.branch, this.remoteRevision, conflictingScopes);\n\t\tconst remoteOperations = {};\n\t\tfor (const [scope, ops] of Object.entries(operationsByScope)) remoteOperations[scope] = ops;\n\t\tconst conflictInfo = {\n\t\t\tremoteOperations,\n\t\t\tlocalActions: localTracked,\n\t\t\tknownRevision: { ...this.remoteRevision },\n\t\t\tcurrentRevision: { ...currentRevision }\n\t\t};\n\t\tif (strategy === \"reject\") throw new ConflictError(conflictInfo);\n\t\tif (strategy === \"rebase\") return this.pullAndReplay(localTracked.map((t) => t.action));\n\t\tconst mergedActions = await strategy(conflictInfo);\n\t\treturn this.pullAndReplay(mergedActions);\n\t}\n\t/**\n\t* Pull latest remote state and replay actions through interceptors.\n\t* Returns newly tracked actions with correct prevOpHash values.\n\t*/\n\tasync pullAndReplay(actions) {\n\t\tawait this.pull();\n\t\tfor (const action of actions) {\n\t\t\tconst methodName = screamingSnakeToCamel(action.type);\n\t\t\tconst method = this[methodName];\n\t\t\tif (typeof method === \"function\") method.call(this, action.input);\n\t\t}\n\t\treturn this.tracker.flush();\n\t}\n\t/** Prepare actions for push, optionally signing them. */\n\tasync prepareActionsForPush(tracked) {\n\t\tconst actions = [];\n\t\tfor (const { action, prevOpHash, prevOpIndex } of tracked) {\n\t\t\tlet prepared = {\n\t\t\t\t...action,\n\t\t\t\tcontext: {\n\t\t\t\t\t...action.context,\n\t\t\t\t\tprevOpHash,\n\t\t\t\t\tprevOpIndex\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (this.options.signer) prepared = await this.signAction(prepared);\n\t\t\tactions.push(prepared);\n\t\t}\n\t\treturn actions;\n\t}\n\t/** Sign an action using the configured signer, preserving existing signatures. */\n\tasync signAction(action) {\n\t\tconst signer = this.options.signer;\n\t\tconst signature = await signer.signAction(action);\n\t\tconst existingSignatures = action.context?.signer?.signatures ?? [];\n\t\treturn {\n\t\t\t...action,\n\t\t\tcontext: {\n\t\t\t\t...action.context,\n\t\t\t\tsigner: {\n\t\t\t\t\tuser: signer.user,\n\t\t\t\t\tapp: signer.app,\n\t\t\t\t\tsignatures: [...existingSignatures, signature]\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Fetch document and operations from the remote.\n\t*\n\t* On the first pull, uses the combined document+operations query.\n\t* On subsequent pulls, fetches only new operations per scope using\n\t* sinceRevision, then merges with existing local operations.\n\t* Falls back to a full fetch if the merge produces a count mismatch.\n\t*/\n\tasync fetchDocumentAndOperations() {\n\t\tif (this.hasPulled) return this.incrementalFetch();\n\t\tconst result = await this.remoteClient.getDocumentWithOperations(this.documentId, this.options.branch);\n\t\tif (!result) throw new Error(`Document \"${this.documentId}\" not found on remote`);\n\t\tthis.hasPulled = true;\n\t\treturn {\n\t\t\tremoteDoc: result.document,\n\t\t\toperations: convertRemoteOperations(result.operations.operationsByScope)\n\t\t};\n\t}\n\t/**\n\t* Incremental fetch: fetches the document and only new operations per scope\n\t* using sinceRevision in a single request when possible.\n\t* Falls back to a full fetch on count mismatch.\n\t*/\n\tasync incrementalFetch() {\n\t\tconst scopes = Object.keys(this.remoteRevision);\n\t\tconst result = await this.remoteClient.getDocumentWithOperations(this.documentId, this.options.branch, this.remoteRevision, scopes.length > 0 ? scopes : void 0);\n\t\tif (!result) throw new Error(`Document \"${this.documentId}\" not found on remote`);\n\t\tconst remoteDoc = result.document;\n\t\tconst expectedRevision = extractRevisionMap(remoteDoc.revisionsList);\n\t\tconst newOps = convertRemoteOperations(result.operations.operationsByScope);\n\t\tconst merged = this.mergeOperations(this.inner.operations, newOps);\n\t\tif (this.hasExpectedOperationCounts(merged, expectedRevision)) return {\n\t\t\tremoteDoc,\n\t\t\toperations: merged\n\t\t};\n\t\treturn this.fullFetch(remoteDoc);\n\t}\n\t/**\n\t* Full fetch fallback: fetches all operations from the beginning.\n\t* Used when an incremental fetch produces a count mismatch.\n\t*/\n\tasync fullFetch(remoteDoc) {\n\t\tconst { operationsByScope } = await this.remoteClient.getAllOperations(this.documentId, this.options.branch);\n\t\treturn {\n\t\t\tremoteDoc,\n\t\t\toperations: convertRemoteOperations(operationsByScope)\n\t\t};\n\t}\n\t/**\n\t* Validate that the merged operations match the expected revision per scope.\n\t* Each scope's operation count should equal its revision number.\n\t*/\n\thasExpectedOperationCounts(operations, expectedRevision) {\n\t\tfor (const [scope, revision] of Object.entries(expectedRevision)) if ((scope in operations ? operations[scope].length : 0) !== revision) return false;\n\t\treturn true;\n\t}\n\t/**\n\t* Merge existing local operations with newly fetched operations.\n\t* Appends new operations to existing ones per scope.\n\t*/\n\tmergeOperations(existingOps, newOps) {\n\t\tconst merged = {};\n\t\tfor (const [scope, ops] of Object.entries(existingOps)) if (ops.length > 0) merged[scope] = [...ops];\n\t\tfor (const [scope, ops] of Object.entries(newOps)) if (ops.length > 0) (merged[scope] ??= []).push(...ops);\n\t\treturn merged;\n\t}\n\t/** Schedule a push via microtask (for streaming mode coalescing). */\n\tschedulePush() {\n\t\tif (this.pushScheduled) return;\n\t\tthis.pushScheduled = true;\n\t\tqueueMicrotask(() => {\n\t\t\tthis.pushScheduled = false;\n\t\t\tthis.pushQueue = this.pushQueue.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.push();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.options.onPushError?.(error);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/storage/base-storage.ts\nvar BaseStorage = class {\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n\tforEach(callback) {\n\t\tfor (const [key, value] of this) callback(value, key, this);\n\t}\n};\n//#endregion\n//#region src/storage/local-storage.ts\nvar BrowserLocalStorage = class extends BaseStorage {\n\t#namespace;\n\t#storage = window.localStorage;\n\tconstructor(namespace) {\n\t\tsuper();\n\t\tthis.#namespace = namespace;\n\t}\n\t#readMap() {\n\t\tconst raw = this.#storage.getItem(this.#namespace);\n\t\tif (!raw) return /* @__PURE__ */ new Map();\n\t\treturn new Map(JSON.parse(raw));\n\t}\n\t#writeMap(map) {\n\t\tthis.#storage.setItem(this.#namespace, JSON.stringify(Array.from(map.entries())));\n\t}\n\tget(key) {\n\t\treturn this.#readMap().get(key);\n\t}\n\tset(key, value) {\n\t\tconst map = this.#readMap();\n\t\tmap.set(key, value);\n\t\tthis.#writeMap(map);\n\t}\n\tdelete(key) {\n\t\tconst map = this.#readMap();\n\t\tconst deleted = map.delete(key);\n\t\tif (deleted) this.#writeMap(map);\n\t\treturn deleted;\n\t}\n\thas(key) {\n\t\treturn this.#readMap().has(key);\n\t}\n\tclear() {\n\t\tthis.#storage.removeItem(this.#namespace);\n\t}\n\tentries() {\n\t\treturn this.#readMap().entries();\n\t}\n\tkeys() {\n\t\treturn this.#readMap().keys();\n\t}\n\tvalues() {\n\t\treturn this.#readMap().values();\n\t}\n\t[Symbol.iterator]() {\n\t\treturn this.#readMap().entries();\n\t}\n};\n//#endregion\nexport { ActionTracker, BaseStorage, BrowserLocalStorage, COMMON_PACKAGE_ID, CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChannelScheme, ChevronDownIcon, ConflictError, CopyIcon, DEFAULT_DRIVE_EDITOR_ID, DEFAULT_DRIVE_ID, DEFAULT_SWITCHBOARD_URL, DOMAIN_TYPE, DRIVE_DOCUMENT_TYPES, DisconnectIcon, DocumentCache, DocumentChangeType, DocumentIntegrityService, DocumentModelNotFoundError, DocumentTypeMismatchError, DriveCollectionId, EDITOR_FILE_DROP_OPT_OUT_ATTR, GqlRequestChannel, GraphQLClientDocumentCache, GraphQLReactorClient, GraphQLReactorProvider, ISSUER_TYPE, InMemoryQueue, IntervalPollTimer, MutateDocumentWithOperationsDocument, NoSelectedDocumentError, PollBehavior, PropagationMode, REACTOR_SCHEMA, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, RENOWN_RETURN_URL_STRIPPED_PARAMS, RENOWN_URL, ReactorBuilder, ReactorClientBuilder, ReactorOperationFieldsFragmentDoc, RegistryClient, RelationalDbProcessor, RemoteClient, RemoteDocumentController, Renown, RenownAuthButton, RenownInitialUserProvider, RenownLoginButton, RenownLogo, RenownProvider, RenownUserButton, RenownWalletProvider, SpinnerIcon, StaticPackageManager, SubgraphSdkRegistry, SyncOperationStatus, UnsupportedDocumentTypeError, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, addAllowListEventHandler, addAllowedDocumentTypesEventHandler, addAnalyticsDatabaseNameEventHandler, addAttachmentServiceEventHandler, addBasePathEventHandler, addCliVersionEventHandler, addDefaultDrivesUrlEventHandler, addDisabledEditorsEventHandler, addDocument, addDocumentCacheEventHandler, addDraggingNodeEventHandler, addDrive, addDrivesEventHandler, addDrivesPreserveStrategyEventHandler, addEnabledEditorsEventHandler, addFeaturesEventHandler, addFileUploadOperationsChunkSizeEventHandler, addFileWithProgress, addFolder, addGaTrackingIdEventHandler, addGraphQLReactorClientEventHandler, addIsAddCloudDrivesEnabledEventHandler, addIsAddDriveEnabledEventHandler, addIsAddLocalDrivesEnabledEventHandler, addIsAddPublicDrivesEnabledEventHandler, addIsAnalyticsDatabaseWorkerEnabledEventHandler, addIsAnalyticsEnabledEventHandler, addIsAnalyticsExternalProcessorsEnabledEventHandler, addIsCloudDrivesEnabledEventHandler, addIsDeleteCloudDrivesEnabledEventHandler, addIsDeleteLocalDrivesEnabledEventHandler, addIsDeletePublicDrivesEnabledEventHandler, addIsDiffAnalyticsEnabledEventHandler, addIsDocumentModelSelectionSettingsEnabledEventHandler, addIsDragAndDropEnabledEventHandler, addIsDriveAnalyticsEnabledEventHandler, addIsEditorDebugModeEnabledEventHandler, addIsEditorReadModeEnabledEventHandler, addIsExternalControlsEnabledEventHandler, addIsExternalPackagesEnabledEventHandler, addIsExternalProcessorsEnabledEventHandler, addIsExternalRelationalProcessorsEnabledEventHandler, addIsLocalDrivesEnabledEventHandler, addIsPublicDrivesEnabledEventHandler, addIsRelationalProcessorsEnabledEventHandler, addIsSentryTracingEnabledEventHandler, addLoadingEventHandler, addLocalDrivesEnabledEventHandler, addLogLevelEventHandler, addModalEventHandler, addPHEventHandlers, addPackageDiscoveryServiceEventHandler, addPromiseState, addReactorClientEventHandler, addReactorClientModuleEventHandler, addRemoteDrive, addRenownAdaptersEventHandler, addRenownChainIdEventHandler, addRenownEventHandler, addRenownNetworkIdEventHandler, addRenownUrlEventHandler, addRequiresHardRefreshEventHandler, addResetSelectedNodeEventHandler, addRevisionHistoryVisibleEventHandler, addRouterBasenameEventHandler, addSelectedDriveIdEventHandler, addSelectedNodeIdEventHandler, addSelectedTimelineItemEventHandler, addSelectedTimelineRevisionEventHandler, addSentryDsnEventHandler, addSentryEnvEventHandler, addSentryReleaseEventHandler, addSetSelectedDriveOnPopStateEventHandler, addSetSelectedNodeOnPopStateEventHandler, addStudioModeEventHandler, addSwitchboardUrlEventHandler, addToastEventHandler, addVersionCheckIntervalEventHandler, addVersionEventHandler, addVetraPackageManagerEventHandler, addWarnOutdatedAppEventHandler, ambientRenownTokenProvider, baseDocumentModels, baseDocumentModelsMap, buildDocumentSubgraphQuery, buildDocumentSubgraphUrl, buildFolderZip, callEventHandlerRegisterFunctions, callGlobalSetterForKey, clearGlobal, closePHModal, commonGlobalEventHandlerFunctions, convertRemoteOperations, createAnalyticsStore, createClient, createProcessorQuery, createUrlWithPreservedParams, deleteDrive, deleteNode, deriveSystemUrl, describeGraphQLDocument, diffStateShapes, dispatchActions, downloadDocument, downloadFolderZip, driveIdFromUrl, dropAllReactorStorage, ensurePHEventHandlers, expandBulkArchive, exportFile, extractDriveIdFromPath, extractDriveIdFromSlug, extractDriveSlugFromPath, extractNodeIdFromPath, extractNodeIdFromSlug, extractNodeSlugFromPath, fetchDriveInfo, findUuid, getAnalyticsStore, getDocumentExtension, getDocumentGraphqlQuery, getDocumentStateSelection, getDocumentUpgradePreview, getDocumentVersionStatus, getDriveIdBySlug, getDrives, getGlobal, getPackageInfo, getPackagePage, getPackages, getPackagesByDocumentType, getPackagesForDocumentType, getPathWithoutBase, getRevisionFromDate, getSlugFromDriveUrl, getSwitchboardBaseFromChannelUrl, getSwitchboardGatewayUrlFromDriveUrl, getSyncStatus, getSyncStatusSync, getUserPermissions, graphqlDocumentEvents, graphqlDocumentsEvents, graphqlEventsToSyncDrive, hasPreloadBandwidth, hideRevisionHistory, identifierFromMutateDocumentOperationVariables, initConnectCrypto, initRenownCrypto, initTheme, isAuthRefusalClose, isDocumentTypeSupported, isDriveAuthError, isExternalControlsEnabledEventFunctions, isFileNodeKind, isFolderNodeKind, isGraphQLReactorClient, loadFile, loading, login, logout, makeAuthConnectionParams, makeAuthMiddleware, makeDriveUrlComponent, makeNodeSlug, makePHEventFunctions, openRenown, packageFromDocumentModels, parseDriveUrl, phAppConfigHooks, phAppConfigSetters, phDocumentEditorConfigHooks, phDocumentEditorConfigSetters, phDocumentFromGetDocument, phDocumentFromMutation, phDocumentFromQuery, phDocumentsFromQuery, phGlobalConfigHooks, phGlobalConfigSetters, preloadEditorModule, prepareSignedActions, reactorGraphqlBatchFetchDocuments, reactorGraphqlCreateDocument, reactorGraphqlDeleteDocument, reactorGraphqlDeleteDocuments, reactorGraphqlFetchDocument, reactorGraphqlMutateDocument, readPromiseState, refreshReactorData, refreshReactorDataClient, renameDrive, renameDriveNode, resolveDocumentModelModule, resolveUrlPathname, revisionMapFromRevisionsList, setAllowList, setAllowedDocumentTypes, setAnalyticsDatabaseName, setAttachmentService, setBasePath, setCliVersion, setDefaultDrivesUrl, setDefaultPHGlobalConfig, setDisabledEditors, setDocumentCache, setDriveAvailableOffline, setDriveMetadata, setDriveSharingType, setDrives, setDrivesPreserveStrategy, setEnabledEditors, setFeatures, setFileUploadOperationsChunkSize, setGaTrackingId, setGlobal, setGraphQLReactorClient, setIsAddCloudDrivesEnabled, setIsAddDriveEnabled, setIsAddLocalDrivesEnabled, setIsAddPublicDrivesEnabled, setIsAnalyticsDatabaseWorkerEnabled, setIsAnalyticsEnabled, setIsAnalyticsExternalProcessorsEnabled, setIsCloudDrivesEnabled, setIsDeleteCloudDrivesEnabled, setIsDeleteLocalDrivesEnabled, setIsDeletePublicDrivesEnabled, setIsDiffAnalyticsEnabled, setIsDocumentModelSelectionSettingsEnabled, setIsDragAndDropEnabled, setIsDriveAnalyticsEnabled, setIsEditorDebugModeEnabled, setIsEditorReadModeEnabled, setIsExternalControlsEnabled, setIsExternalPackagesEnabled, setIsExternalProcessorsEnabled, setIsExternalRelationalProcessorsEnabled, setIsLocalDrivesEnabled, setIsPublicDrivesEnabled, setIsRelationalProcessorsEnabled, setIsSentryTracingEnabled, setLoading, setLocalDrivesEnabled, setLogLevel, setPGliteDB, setPHAppConfig, setPHAppConfigByKey, setPHDocumentEditorConfig, setPHDocumentEditorConfigByKey, setPHGlobalConfig, setPHGlobalConfigByKey, setPHModal, setPHToast, setPackageDiscoveryService, setPreferredEditorOnNode, setReactorClient, setReactorClientModule, setRenown, setRenownAdapters, setRenownChainId, setRenownNetworkId, setRenownUrl, setRequiresHardRefresh, setRevisionHistoryVisible, setRouterBasename, setSelectedDrive, setSelectedDriveId, setSelectedNode, setSelectedTimelineItem, setSelectedTimelineRevision, setSentryDsn, setSentryEnv, setSentryRelease, setStudioMode, setSwitchboardUrl, setVersion, setVersionCheckInterval, setVetraPackageManager, setWarnOutdatedApp, showCreateDocumentModal, showDeleteNodeModal, showPHModal, showRevisionHistory, signStampedAction, sortNodesByName, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscriptionsUrlFromGraphqlUrl, trimTrailingSlash, truncateAllTables, upgradeDocument, useAllowList, useAllowedDocumentModelModules, useAllowedDocumentTypes, useAnalyticsDatabaseName, useAppModuleById, useAppModules, useAttachmentPreview, useAttachmentService, useAttachmentUpload, useAttachments, useBasePath, useCanExecute, useCliVersion, useConnectionState, useConnectionStates, useDatabase, useDefaultAppModule, useDefaultDrivesUrl, useDid, useDisabledEditors, useDispatch, useDocument, useDocumentById, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOfType, useDocumentOperations, useDocumentSafe, useDocumentTypes, useDocumentTypesInSelectedDrive, useDocumentVersionStatus, useDocuments, useDocumentsByIds, useDocumentsInSelectedDrive, useDocumentsInSelectedFolder, useDownloadDocument, useDownloadFolder, useDragNode, useDriveById, useDriveSystemInfo, useDrives, useDrivesPreserveStrategy, useDropFile, useDropNode, useEditorFileDrop, useEditorModuleById, useEditorModules, useEditorModulesForDocumentType, useEditorPreloader, useEnabledEditors, useFallbackEditorModule, useFeatures, useFileNodesInSelectedDrive, useFileNodesInSelectedFolder, useFileUploadOperationsChunkSize, useFolderById, useFolderNodesInSelectedDrive, useFolderNodesInSelectedFolder, useGaTrackingId, useGetDocument, useGetDocumentAsync, useGetDocuments, useGetSwitchboardLink, useGraphQLReactorClient, useInitReactorGraphqlClient, useIsAddCloudDrivesEnabled, useIsAddDriveEnabled, useIsAddLocalDrivesEnabled, useIsAddPublicDrivesEnabled, useIsAnalyticsDatabaseWorkerEnabled, useIsAnalyticsEnabled, useIsAnalyticsExternalProcessorsEnabled, useIsCloudDrivesEnabled, useIsDeleteCloudDrivesEnabled, useIsDeleteLocalDrivesEnabled, useIsDeletePublicDrivesEnabled, useIsDiffAnalyticsEnabled, useIsDocumentModelSelectionSettingsEnabled, useIsDragAndDropEnabled, useIsDriveAnalyticsEnabled, useIsEditorDebugModeEnabled, useIsEditorReadModeEnabled, useIsExternalControlsEnabled, useIsExternalPackagesEnabled, useIsExternalProcessorsEnabled, useIsExternalRelationalProcessorsEnabled, useIsLocalDrivesEnabled, useIsPublicDrivesEnabled, useIsRelationalProcessorsEnabled, useIsSentryTracingEnabled, useLoading, useLocalDrivesEnabled, useLogLevel, useLoginStatus, useModelRegistry, useNodeActions, useNodeById, useNodeParentFolderById, useNodePathById, useNodesInSelectedDrive, useNodesInSelectedDriveOrFolder, useNodesInSelectedFolder, useOnDropFile, usePGlite, usePHAppConfigByKey, usePHDocumentEditorConfigByKey, usePHGlobalConfigByKey, usePHModal, usePHToast, usePackageDiscoveryService, useParentFolderForSelectedNode, useReactorClient, useReactorClientModule, useRelationalDb, useRelationalQuery, useRenown, useRenownAdapters, useRenownAuth, useRenownAuthAsync, useRenownChainId, useRenownInit, useRenownInitialAuth, useRenownInitialUser, useRenownLoginMethods, useRenownNetworkId, useRenownSessionCookie, useRenownSessionSynced, useRenownUrl, useRenownWalletAdapter, useRequiresHardRefresh, useResetPHGlobalConfig, useRevisionHistoryVisible, useRouterBasename, useSelectedDocument, useSelectedDocumentId, useSelectedDocumentOfType, useSelectedDocumentSafe, useSelectedDrive, useSelectedDriveId, useSelectedDriveSafe, useSelectedFolder, useSelectedNode, useSelectedNodePath, useSelectedTimelineItem, useSelectedTimelineRevision, useSentryDsn, useSentryEnv, useSentryRelease, useSetDefaultPHGlobalConfig, useSetPHAppConfig, useSetPHDocumentEditorConfig, useSetPHGlobalConfig, useStudioMode, useSubgraphModules, useSupportedDocumentTypesInReactor, useSwitchboardClient, useSwitchboardUrl, useSync, useSyncList, useTheme, useUser, useUserPermissions, useVersion, useVersionCheckInterval, useVetraPackageManager, useVetraPackages, useWarnOutdatedApp, validateDocument, viewFilterInputFromViewFilter, waitForDocumentReady };\n\n//# sourceMappingURL=index.js.map"],"x_google_ignoreList":[2,4,5,6,7,8,9,10,11,12,13,14,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,34,35,36,37,38,39,40,41,42,43,44,45,46],"mappings":";;;;;;;AAGA,MAAMA,aAAW,OAAO,WAAW;AACnC,SAAS,qBAAqB,KAAK;CAClC,MAAM,eAAe,SAAS,YAAY,IAAI;CAC9C,MAAM,kBAAkB,MAAM,IAAI;CAClC,SAAS,SAAS,OAAO;AACxB,MAAIA,WAAU;EACd,MAAM,QAAQ,IAAI,YAAY,cAAc,EAAE,QAAQ,GAAG,MAAM,OAAO,EAAE,CAAC;AACzE,SAAO,cAAc,MAAM;;CAE5B,SAAS,uBAAuB;AAC/B,MAAIA,WAAU;EACd,MAAM,QAAQ,IAAI,YAAY,gBAAgB;AAC9C,SAAO,cAAc,MAAM;;CAE5B,SAAS,oBAAoB,OAAO;AACnC,MAAIA,WAAU;EACd,MAAM,QAAQ,MAAM,OAAO;AAC3B,MAAI,CAAC,OAAO,GAAI,QAAO,KAAK,EAAE;AAC9B,SAAO,GAAG,OAAO;AACjB,wBAAsB;;CAEvB,SAAS,kBAAkB;AAC1B,MAAIA,WAAU;AACd,SAAO,iBAAiB,cAAc,oBAAoB;;CAE3D,SAAS,iBAAiB,eAAe;AACxC,MAAIA,WAAU,cAAa;AAC3B,SAAO,iBAAiB,iBAAiB,cAAc;AACvD,eAAa;AACZ,UAAO,oBAAoB,iBAAiB,cAAc;;;CAG5D,SAAS,cAAc;AACtB,MAAIA,WAAU;AACd,SAAO,OAAO,KAAK;;CAEpB,SAAS,oBAAoB;CAC7B,SAAS,WAAW;AACnB,SAAO,qBAAqB,kBAAkB,aAAa,kBAAkB;;AA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H,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CAEH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,G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