@xyo-network/sdk 8.1.0 → 8.1.2

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 (90) hide show
  1. package/README.md +25 -0
  2. package/dist/neutral/account-custody.d.ts +2 -0
  3. package/dist/neutral/account-custody.d.ts.map +1 -0
  4. package/dist/neutral/account-custody.mjs +542 -0
  5. package/dist/neutral/account-custody.mjs.map +7 -0
  6. package/dist/neutral/address-payload-plugin.mjs +3 -14
  7. package/dist/neutral/address-payload-plugin.mjs.map +4 -4
  8. package/dist/neutral/api-location-diviner.mjs +0 -2
  9. package/dist/neutral/api-location-diviner.mjs.map +2 -2
  10. package/dist/neutral/archivist-abstract.mjs +54 -11
  11. package/dist/neutral/archivist-abstract.mjs.map +3 -3
  12. package/dist/neutral/archivist-memory.mjs +1 -4
  13. package/dist/neutral/archivist-memory.mjs.map +2 -2
  14. package/dist/neutral/bridge-abstract.mjs +4 -7
  15. package/dist/neutral/bridge-abstract.mjs.map +2 -2
  16. package/dist/neutral/bridge-http.mjs +1 -1
  17. package/dist/neutral/bridge-http.mjs.map +2 -2
  18. package/dist/neutral/diviner-boundwitness.memory.mjs +1 -1
  19. package/dist/neutral/diviner-boundwitness.memory.mjs.map +2 -2
  20. package/dist/neutral/diviner-boundwitness.mjs +1 -1
  21. package/dist/neutral/diviner-boundwitness.mjs.map +2 -2
  22. package/dist/neutral/diviner-payload-generic.mjs +3 -3
  23. package/dist/neutral/diviner-payload-generic.mjs.map +2 -2
  24. package/dist/neutral/index.d.ts +1 -0
  25. package/dist/neutral/index.d.ts.map +1 -1
  26. package/dist/neutral/index.mjs +1 -0
  27. package/dist/neutral/index.mjs.map +2 -2
  28. package/dist/neutral/module-abstract.mjs +4 -4
  29. package/dist/neutral/module-abstract.mjs.map +3 -3
  30. package/dist/neutral/module-resolver.mjs +3 -6
  31. package/dist/neutral/module-resolver.mjs.map +2 -2
  32. package/dist/neutral/modules/account-custody/AccountCustody.d.ts +14 -0
  33. package/dist/neutral/modules/account-custody/AccountCustody.d.ts.map +1 -0
  34. package/dist/neutral/modules/account-custody/AccountCustodyClient.d.ts +4 -0
  35. package/dist/neutral/modules/account-custody/AccountCustodyClient.d.ts.map +1 -0
  36. package/dist/neutral/modules/account-custody/clientExecution.d.ts +11 -0
  37. package/dist/neutral/modules/account-custody/clientExecution.d.ts.map +1 -0
  38. package/dist/neutral/modules/account-custody/clientModel.d.ts +49 -0
  39. package/dist/neutral/modules/account-custody/clientModel.d.ts.map +1 -0
  40. package/dist/neutral/modules/account-custody/clientOwner.d.ts +7 -0
  41. package/dist/neutral/modules/account-custody/clientOwner.d.ts.map +1 -0
  42. package/dist/neutral/modules/account-custody/clientSignals.d.ts +4 -0
  43. package/dist/neutral/modules/account-custody/clientSignals.d.ts.map +1 -0
  44. package/dist/neutral/modules/account-custody/clientState.d.ts +31 -0
  45. package/dist/neutral/modules/account-custody/clientState.d.ts.map +1 -0
  46. package/dist/neutral/modules/account-custody/error.d.ts +8 -0
  47. package/dist/neutral/modules/account-custody/error.d.ts.map +1 -0
  48. package/dist/neutral/modules/account-custody/index.d.ts +7 -0
  49. package/dist/neutral/modules/account-custody/index.d.ts.map +1 -0
  50. package/dist/neutral/modules/account-custody/model.d.ts +65 -0
  51. package/dist/neutral/modules/account-custody/model.d.ts.map +1 -0
  52. package/dist/neutral/modules/account-custody/realmRegistry.d.ts +2 -0
  53. package/dist/neutral/modules/account-custody/realmRegistry.d.ts.map +1 -0
  54. package/dist/neutral/modules/address-payload-plugin/Plugin.d.ts.map +1 -1
  55. package/dist/neutral/modules/address-payload-plugin/index.d.ts +0 -1
  56. package/dist/neutral/modules/address-payload-plugin/index.d.ts.map +1 -1
  57. package/dist/neutral/modules/api-location-diviner/RemoteDivinerConfig.d.ts +0 -2
  58. package/dist/neutral/modules/api-location-diviner/RemoteDivinerConfig.d.ts.map +1 -1
  59. package/dist/neutral/modules/archivist-abstract/AbstractArchivist.d.ts +1 -0
  60. package/dist/neutral/modules/archivist-abstract/AbstractArchivist.d.ts.map +1 -1
  61. package/dist/neutral/modules/archivist-abstract/InsertSequencer.d.ts +25 -0
  62. package/dist/neutral/modules/archivist-abstract/InsertSequencer.d.ts.map +1 -0
  63. package/dist/neutral/modules/archivist-memory/MemoryDriver.d.ts.map +1 -1
  64. package/dist/neutral/modules/bridge-abstract/AbstractModuleProxy/ModuleProxyResolver.d.ts.map +1 -1
  65. package/dist/neutral/modules/bridge-http/HttpBridge.d.ts.map +1 -1
  66. package/dist/neutral/modules/diviner-boundwitness/applyBoundWitnessDivinerQueryPayload.d.ts.map +1 -1
  67. package/dist/neutral/modules/diviner-payload-generic/Diviner.d.ts.map +1 -1
  68. package/dist/neutral/modules/module-resolver/AbstractModuleResolver.d.ts.map +1 -1
  69. package/dist/neutral/modules/module-resolver/ResolverEventEmitter.d.ts.map +1 -1
  70. package/dist/neutral/modules/node-memory/MemoryNode.d.ts.map +1 -1
  71. package/dist/neutral/node-memory.mjs +1 -4
  72. package/dist/neutral/node-memory.mjs.map +2 -2
  73. package/dist/node/account-custody.d.ts +2 -0
  74. package/dist/node/account-custody.d.ts.map +1 -0
  75. package/dist/node/index.d.ts +1 -0
  76. package/dist/node/index.d.ts.map +1 -1
  77. package/dist/node/index.mjs +1 -0
  78. package/dist/node/index.mjs.map +2 -2
  79. package/dist/node/modules/account-custody/clientExecution.d.ts +11 -0
  80. package/dist/node/modules/account-custody/clientExecution.d.ts.map +1 -0
  81. package/dist/node/modules/account-custody/clientSignals.d.ts +4 -0
  82. package/dist/node/modules/account-custody/clientSignals.d.ts.map +1 -0
  83. package/dist/node/modules/account-custody/realmRegistry.d.ts +2 -0
  84. package/dist/node/modules/account-custody/realmRegistry.d.ts.map +1 -0
  85. package/dist/node/modules/archivist-abstract/InsertSequencer.d.ts +25 -0
  86. package/dist/node/modules/archivist-abstract/InsertSequencer.d.ts.map +1 -0
  87. package/dist/node/modules/archivist-memory/MemoryDriver.d.ts.map +1 -1
  88. package/package.json +19 -13
  89. package/dist/neutral/modules/address-payload-plugin/Template.d.ts +0 -3
  90. package/dist/neutral/modules/address-payload-plugin/Template.d.ts.map +0 -1
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/modules/account-custody/error.ts", "../../src/modules/account-custody/realmRegistry.ts", "../../src/modules/account-custody/AccountCustody.ts", "../../src/modules/account-custody/clientState.ts", "../../src/modules/account-custody/clientSignals.ts", "../../src/modules/account-custody/clientExecution.ts", "../../src/modules/account-custody/clientOwner.ts", "../../src/modules/account-custody/AccountCustodyClient.ts"],
4
+ "sourcesContent": ["import type { AccountCustodyErrorCode } from './model.ts'\n\n/** Classified failure with no private native exception, key material or request contents. */\nexport class AccountCustodyError extends Error {\n readonly code: AccountCustodyErrorCode\n override name = 'AccountCustodyError'\n\n constructor(code: AccountCustodyErrorCode) {\n super(`Account custody: ${code}`)\n this.code = code\n }\n}\n", "import { AccountCustodyError } from './error.ts'\n\ninterface RealmRegistry {\n readonly version: 1\n reserve(this: void, key: string, fence: object): boolean\n}\n\nfunction realmRegistry(): RealmRegistry {\n const key = Symbol.for('network.xyo.sdk.account-custody.in-realm.v1')\n const existing: unknown = Reflect.get(globalThis, key)\n if (existing === undefined) {\n const reservations = new Set<string>()\n const registry: RealmRegistry = Object.freeze({\n version: 1,\n reserve(key: string, _fence: object): boolean {\n if (reservations.has(key)) return false\n reservations.add(key)\n return true\n },\n })\n Object.defineProperty(globalThis, key, {\n value: registry, configurable: false, writable: false,\n })\n return registry\n }\n if (typeof existing !== 'object' || existing === null || !Object.isFrozen(existing)\n || !('version' in existing) || existing.version !== 1 || !('reserve' in existing)\n || typeof existing.reserve !== 'function') throw new AccountCustodyError('stopped')\n return existing as RealmRegistry\n}\n\n// One permanent address reservation shared by legacy/scoped modes and module copies.\nconst registry = realmRegistry()\n\nexport function reserveInRealmAccount(address: string, fence: object = Object.freeze({})): boolean {\n return registry.reserve(address.toLowerCase(), fence)\n}\n", "import type { AccountInstance } from '@xyo-network/sdk-protocol'\n\nimport { AccountCustodyError } from './error.ts'\nimport { reserveInRealmAccount } from './realmRegistry.ts'\n\nexport { AccountCustodyError } from './error.ts'\n\nimport type {\n AccountCustody,\n AccountCustodyAssurance,\n AccountCustodyExecuteOptions,\n AccountCustodyLimits,\n AccountCustodyOperationControl,\n AccountCustodyOptions,\n AccountCustodyOwner,\n AccountCustodyStatus,\n InRealmAccountCustodyOwnerOptions,\n} from './model.ts'\n\ninterface RealmFence {\n active?: AbortController\n executions: Set<Execution>\n isStopped: boolean\n reservation: object\n tail: Promise<void>\n}\n\ninterface OwnerState {\n account: AccountInstance\n fence: RealmFence\n limits: AccountCustodyLimits\n reservation: object\n}\n\ninterface Execution {\n controller: AbortController\n hasCompleted: boolean\n hasStarted: boolean\n}\n\ninterface ExecutionObserver<Result> {\n result: Promise<Result>\n cleanup(this: void): void\n reject(this: void, error: unknown): void\n resolve(this: void, result: Result): void\n}\n\n// Native intrinsics ignore caller-owned getters and shadowed event methods.\nfunction intrinsic(prototype: object, property: string, member: 'get' | 'value'): unknown {\n const descriptor: unknown = Object.getOwnPropertyDescriptor(prototype, property)\n return typeof descriptor !== 'object' || descriptor === null ? undefined : (descriptor as Record<string, unknown>)[member]\n}\n\nconst nativeAbortedGetter = intrinsic(AbortSignal.prototype, 'aborted', 'get')\nconst nativeAddListener = intrinsic(EventTarget.prototype, 'addEventListener', 'value')\nconst nativeRemoveListener = intrinsic(EventTarget.prototype, 'removeEventListener', 'value')\n\nfunction nativeCall(method: unknown, receiver: object, args: unknown[]): unknown {\n if (typeof method !== 'function') throw new AccountCustodyError('invalid-request')\n return Reflect.apply(method, receiver, args)\n}\n\nfunction isSignalAborted(signal: AbortSignal): boolean {\n const result = nativeCall(nativeAbortedGetter, signal, [])\n if (typeof result !== 'boolean') throw new AccountCustodyError('invalid-request')\n return result\n}\n\nfunction captureSignal(options: AccountCustodyExecuteOptions): AbortSignal | undefined {\n try {\n const signal = options.signal\n if (signal !== undefined) isSignalAborted(signal)\n return signal\n } catch {\n throw new AccountCustodyError('invalid-request')\n }\n}\n\nconst owners = new WeakMap<AccountCustodyOwner, OwnerState>()\nconst assurance: AccountCustodyAssurance = Object.freeze({\n profile: 'in-realm-exclusive-v1',\n scope: 'participating instances and module copies in one globalThis realm',\n physicalKeyIsolation: 'unqualified',\n crossHostOwnership: 'unqualified',\n})\n\n/**\n * Trusted provisioner entry. A live-state declaration is not cryptographic proof\n * of a never-used key, restart recovery, physical isolation or cross-host custody.\n * Unknown state reserves a stopped owner, and reservations never reset in this realm.\n */\nexport function createInRealmAccountCustodyOwner(options: InRealmAccountCustodyOwnerOptions): AccountCustodyOwner {\n const limits = finiteLimits(options.limits)\n const address = options.account.address\n const key = address.toLowerCase()\n const reservation = Object.freeze({})\n const fence: RealmFence = {\n executions: new Set(),\n reservation,\n isStopped: options.nativeState !== 'established-live',\n tail: Promise.resolve(),\n }\n if (!reserveInRealmAccount(key, fence)) throw new AccountCustodyError('account-reserved')\n const owner: AccountCustodyOwner = Object.freeze({\n address, assurance, limits,\n })\n owners.set(owner, {\n account: options.account, fence, limits, reservation,\n })\n return owner\n}\n\nfunction finiteLimits(selected: AccountCustodyLimits | undefined): AccountCustodyLimits {\n const maxQueuedOperations = selected?.maxQueuedOperations ?? 8\n const maxOperationMilliseconds = selected?.maxOperationMilliseconds ?? 30_000\n if (!Number.isSafeInteger(maxQueuedOperations) || maxQueuedOperations < 0 || maxQueuedOperations > 1024\n || !Number.isSafeInteger(maxOperationMilliseconds) || maxOperationMilliseconds <= 0 || maxOperationMilliseconds > 2_147_483_647) {\n throw new AccountCustodyError('invalid-limits')\n }\n return Object.freeze({ maxQueuedOperations, maxOperationMilliseconds })\n}\n\nfunction stopOwner(state: OwnerState): void {\n if (state.fence.isStopped) return\n state.fence.isStopped = true\n for (const execution of state.fence.executions) execution.controller.abort()\n}\n\nfunction assertReady(state: OwnerState, owner: AccountCustodyOwner): void {\n if (!state.fence.isStopped && state.fence.reservation === state.reservation && state.account.address === owner.address) return\n stopOwner(state)\n throw new AccountCustodyError('stopped')\n}\n\nfunction operationControl(state: OwnerState, execution: Execution, deadline: number): AccountCustodyOperationControl {\n return Object.freeze({\n signal: execution.controller.signal,\n assertActive(): void {\n assertWithinDeadline(deadline)\n if (execution.controller.signal.aborted || state.fence.isStopped) throw new AccountCustodyError('uncertain-operation')\n },\n })\n}\n\nfunction assertWithinDeadline(deadline: number): void {\n if (performance.now() >= deadline) throw new AccountCustodyError('uncertain-operation')\n}\n\nasync function perform<Request, Result>(\n state: OwnerState,\n options: AccountCustodyOptions<Request, Result>,\n execution: Execution,\n request: Request,\n): Promise<Result> {\n if (execution.controller.signal.aborted) throw new AccountCustodyError('cancelled-before-operation')\n assertReady(state, options.owner)\n execution.hasStarted = true\n state.fence.active = execution.controller\n const deadline = performance.now() + state.limits.maxOperationMilliseconds\n const timer = setTimeout(() => execution.controller.abort(), state.limits.maxOperationMilliseconds)\n try {\n const control = operationControl(state, execution, deadline)\n const operation = options.createOperation(state.account, control)\n const result = await operation(request)\n const cloned = structuredClone(result)\n assertWithinDeadline(deadline)\n control.assertActive()\n execution.hasCompleted = true\n return cloned\n } catch {\n stopOwner(state)\n throw new AccountCustodyError('uncertain-operation')\n } finally {\n clearTimeout(timer)\n if (state.fence.active === execution.controller) state.fence.active = undefined\n }\n}\n\nfunction prepareExecution<Result>(\n state: OwnerState,\n execution: Execution,\n signal: AbortSignal | undefined,\n): ExecutionObserver<Result> {\n const deferred = Promise.withResolvers<Result>()\n const local = execution.controller.signal\n const abort = () => execution.controller.abort()\n const aborted = () => {\n if (execution.hasCompleted) return\n if (execution.hasStarted) stopOwner(state)\n const code = execution.hasStarted ? 'uncertain-operation' : state.fence.isStopped ? 'stopped' : 'cancelled-before-operation'\n deferred.reject(new AccountCustodyError(code))\n }\n const cleanup = () => {\n try {\n if (signal !== undefined) nativeCall(nativeRemoveListener, signal, ['abort', abort])\n nativeCall(nativeRemoveListener, local, ['abort', aborted])\n } catch {\n // Cleanup cannot expose native diagnostics or orphan an unhandled rejection.\n }\n }\n try {\n nativeCall(nativeAddListener, local, ['abort', aborted, { once: true }])\n if (signal !== undefined) nativeCall(nativeAddListener, signal, ['abort', abort, { once: true }])\n if (signal !== undefined && isSignalAborted(signal)) abort()\n } catch {\n cleanup()\n throw new AccountCustodyError('invalid-request')\n }\n return {\n result: deferred.promise, resolve: deferred.resolve, reject: deferred.reject, cleanup,\n }\n}\n\nasync function settleExecution<Result>(\n pending: Promise<Result>,\n resolve: (result: Result) => void,\n reject: (error: unknown) => void,\n cleanup: () => void,\n): Promise<void> {\n try {\n resolve(await pending)\n } catch (error) {\n reject(error)\n } finally {\n cleanup()\n }\n}\n\nasync function afterQueue<Request, Result>(\n before: Promise<void>,\n state: OwnerState,\n options: AccountCustodyOptions<Request, Result>,\n execution: Execution,\n request: Request,\n): Promise<Result> {\n try {\n await before\n return await perform(state, options, execution, request)\n } finally {\n state.fence.executions.delete(execution)\n }\n}\n\nasync function drainPending(pending: Promise<unknown>): Promise<void> {\n try {\n await pending\n } catch {\n // Failure is delivered to its caller and does not break queue draining.\n }\n}\n\n/**\n * Wraps a trusted, fixed operation builder. The complete native operation is\n * serialized across all contexts sharing the owner; only content is caller input.\n */\nexport function createAccountCustody<Request, Result>(options: AccountCustodyOptions<Request, Result>): AccountCustody<Request, Result> {\n const state = owners.get(options.owner)\n if (state === undefined) throw new AccountCustodyError('unissued-owner')\n const binding = Object.freeze({ address: options.binding.address, domain: options.binding.domain })\n if (binding.address !== options.owner.address || binding.domain.length === 0) throw new AccountCustodyError('binding-mismatch')\n // Capture immutable composition; later host/caller option mutation cannot retarget work.\n const captured: AccountCustodyOptions<Request, Result> = {\n owner: options.owner, binding, createOperation: options.createOperation, snapshot: options.snapshot,\n }\n return Object.freeze({\n assurance,\n binding,\n get outstandingOperations(): number {\n return state.fence.executions.size\n },\n get status(): AccountCustodyStatus {\n return state.fence.isStopped ? 'stopped' : state.fence.active === undefined ? 'ready' : 'running'\n },\n async execute(request: Request, executionOptions: AccountCustodyExecuteOptions = {}): Promise<Result> {\n assertReady(state, captured.owner)\n if (state.fence.executions.size >= state.limits.maxQueuedOperations + 1) throw new AccountCustodyError('capacity-exhausted')\n const signal = captureSignal(executionOptions)\n if (signal !== undefined && isSignalAborted(signal)) throw new AccountCustodyError('cancelled-before-operation')\n let original: Request\n try {\n original = structuredClone(captured.snapshot(request))\n } catch {\n throw new AccountCustodyError('invalid-request')\n }\n const execution: Execution = {\n controller: new AbortController(), hasCompleted: false, hasStarted: false,\n }\n const observer = prepareExecution<Result>(state, execution, signal)\n state.fence.executions.add(execution)\n const pending = afterQueue(state.fence.tail, state, captured, execution, original)\n state.fence.tail = drainPending(pending)\n void settleExecution(pending, observer.resolve, observer.reject, observer.cleanup)\n return await observer.result\n },\n stop(): void {\n stopOwner(state)\n },\n async drain(): Promise<void> {\n await state.fence.tail\n },\n })\n}\n", "import type { AccountInstance, XyoAddress } from '@xyo-network/sdk-protocol'\n\nimport type { AccountCustodyClientErrorCode } from './clientModel.ts'\nimport type { AccountCustodyLimits } from './model.ts'\n\nexport interface ClientExecution {\n controller: AbortController\n hasCompleted: boolean\n hasStarted: boolean\n}\n\nexport interface ClientState {\n closed: boolean\n executions: Set<ClientExecution>\n tail: Promise<void>\n}\n\nexport interface ClientOwnerState {\n account: AccountInstance\n address: XyoAddress\n current?: ClientState\n executions: Set<ClientExecution>\n limits: AccountCustodyLimits\n stopped: boolean\n tail: Promise<void>\n}\n\nexport class AccountCustodyClientError extends Error {\n readonly code: AccountCustodyClientErrorCode\n override name = 'AccountCustodyClientError'\n\n constructor(code: AccountCustodyClientErrorCode) {\n super(`Account custody client: ${code}`)\n this.code = code\n }\n}\n\nexport function stopClientOwner(state: ClientOwnerState): void {\n state.stopped = true\n for (const execution of state.executions) execution.controller.abort()\n}\n\nexport function assertClientOwnerReady(state: ClientOwnerState): void {\n try {\n if (!state.stopped && state.account.address === state.address) return\n } catch {\n // Trusted account failure cannot expose private diagnostics or establish state.\n }\n stopClientOwner(state)\n throw new AccountCustodyClientError('stopped')\n}\n\nexport async function settleClientTail(pending: Promise<unknown>): Promise<void> {\n try {\n await pending\n } catch {\n // The operation caller observes failure; this promise retains genuine settlement.\n }\n}\n", "import { AccountCustodyClientError } from './clientState.ts'\n\nfunction intrinsic(prototype: object, property: string, member: 'get' | 'value'): unknown {\n const descriptor: unknown = Object.getOwnPropertyDescriptor(prototype, property)\n return typeof descriptor !== 'object' || descriptor === null ? undefined : (descriptor as Record<string, unknown>)[member]\n}\nconst abortedGetter = intrinsic(AbortSignal.prototype, 'aborted', 'get')\nconst addListener = intrinsic(EventTarget.prototype, 'addEventListener', 'value')\nconst removeListener = intrinsic(EventTarget.prototype, 'removeEventListener', 'value')\n\nfunction nativeCall(method: unknown, receiver: object, args: unknown[]): unknown {\n if (typeof method !== 'function') throw new AccountCustodyClientError('invalid-request')\n return Reflect.apply(method, receiver, args)\n}\n\nexport function clientSignalAborted(signal: AbortSignal): boolean {\n const result = nativeCall(abortedGetter, signal, [])\n if (typeof result !== 'boolean') throw new AccountCustodyClientError('invalid-request')\n return result\n}\n\nexport function listenClientSignal(signal: AbortSignal, listener: () => void): void {\n nativeCall(addListener, signal, ['abort', listener, { once: true }])\n}\n\nexport function removeClientSignal(signal: AbortSignal, listener: () => void): void {\n try {\n nativeCall(removeListener, signal, ['abort', listener])\n } catch {\n // Cleanup cannot leak native diagnostics; actual callback settlement owns capacity.\n }\n}\n", "import type { AccountCustodyClientOptions } from './clientModel.ts'\nimport {\n clientSignalAborted, listenClientSignal, removeClientSignal,\n} from './clientSignals.ts'\nimport {\n AccountCustodyClientError, assertClientOwnerReady, type ClientExecution, type ClientOwnerState, type ClientState, stopClientOwner,\n} from './clientState.ts'\nimport type { AccountCustodyOperationControl } from './model.ts'\n\nfunction operationControl(owner: ClientOwnerState, execution: ClientExecution, deadline: number): AccountCustodyOperationControl {\n return Object.freeze({\n signal: execution.controller.signal,\n assertActive() {\n assertClientOwnerReady(owner)\n if (performance.now() >= deadline || execution.controller.signal.aborted || owner.stopped)\n throw new AccountCustodyClientError('uncertain-operation')\n },\n })\n}\n\nasync function perform<Request, Result>(\n owner: ClientOwnerState,\n client: ClientState,\n options: AccountCustodyClientOptions<Request, Result>,\n execution: ClientExecution,\n request: Request,\n): Promise<Result> {\n if (client.closed || execution.controller.signal.aborted) throw new AccountCustodyClientError('cancelled-before-operation')\n assertClientOwnerReady(owner)\n execution.hasStarted = true\n const deadline = performance.now() + owner.limits.maxOperationMilliseconds\n const timer = setTimeout(() => execution.controller.abort(), owner.limits.maxOperationMilliseconds)\n try {\n const control = operationControl(owner, execution, deadline)\n const result = structuredClone(await options.createOperation(owner.account, control)(request))\n control.assertActive()\n execution.hasCompleted = true\n return result\n } catch {\n stopClientOwner(owner)\n throw new AccountCustodyClientError('uncertain-operation')\n } finally {\n clearTimeout(timer)\n }\n}\n\nexport async function afterClientQueue<Request, Result>(\n before: Promise<void>,\n owner: ClientOwnerState,\n client: ClientState,\n options: AccountCustodyClientOptions<Request, Result>,\n execution: ClientExecution,\n request: Request,\n): Promise<Result> {\n try {\n await before\n return await perform(owner, client, options, execution, request)\n } finally {\n owner.executions.delete(execution)\n client.executions.delete(execution)\n }\n}\n\nexport function observeClientExecution<Result>(owner: ClientOwnerState, execution: ClientExecution, caller?: AbortSignal) {\n const deferred = Promise.withResolvers<Result>()\n const local = execution.controller.signal\n const abort = () => execution.controller.abort()\n const aborted = () => {\n if (execution.hasCompleted) return\n if (execution.hasStarted) stopClientOwner(owner)\n deferred.reject(new AccountCustodyClientError(execution.hasStarted ? 'uncertain-operation' : owner.stopped ? 'stopped' : 'cancelled-before-operation'))\n }\n const cleanup = () => {\n removeClientSignal(local, aborted)\n if (caller !== undefined) removeClientSignal(caller, abort)\n }\n try {\n listenClientSignal(local, aborted)\n if (caller !== undefined) listenClientSignal(caller, abort)\n if (caller !== undefined && clientSignalAborted(caller)) abort()\n } catch {\n cleanup()\n throw new AccountCustodyClientError('invalid-request')\n }\n return {\n result: deferred.promise, resolve: deferred.resolve, reject: deferred.reject, cleanup,\n }\n}\n\nexport async function settleClientExecution<Result>(pending: Promise<Result>, observer: ReturnType<typeof observeClientExecution<Result>>): Promise<void> {\n try {\n observer.resolve(await pending)\n } catch (error) {\n observer.reject(error)\n } finally {\n observer.cleanup()\n }\n}\n", "import type {\n AccountCustodyClientAssurance, AccountCustodyClientOwner, InRealmAccountCustodyClientOwnerOptions,\n} from './clientModel.ts'\nimport {\n AccountCustodyClientError, type ClientOwnerState, stopClientOwner,\n} from './clientState.ts'\nimport type { AccountCustodyLimits } from './model.ts'\nimport { reserveInRealmAccount } from './realmRegistry.ts'\n\nexport const scopedClientAssurance: AccountCustodyClientAssurance = Object.freeze({\n profile: 'in-realm-exclusive-scoped-client-v1',\n scope: 'participating instances and module copies in one globalThis realm',\n physicalKeyIsolation: 'unqualified',\n crossHostOwnership: 'unqualified',\n})\nconst owners = new WeakMap<AccountCustodyClientOwner, ClientOwnerState>()\n\nfunction finiteLimits(selected?: AccountCustodyLimits): AccountCustodyLimits {\n const maxQueuedOperations = selected?.maxQueuedOperations ?? 8\n const maxOperationMilliseconds = selected?.maxOperationMilliseconds ?? 30_000\n if (!Number.isSafeInteger(maxQueuedOperations) || maxQueuedOperations < 0 || maxQueuedOperations > 1024\n || !Number.isSafeInteger(maxOperationMilliseconds) || maxOperationMilliseconds <= 0 || maxOperationMilliseconds > 2_147_483_647)\n throw new AccountCustodyClientError('invalid-limits')\n return Object.freeze({ maxQueuedOperations, maxOperationMilliseconds })\n}\n\n/** Resident owner with no restoration/remint. Shares legacy's permanent account reservation. */\nexport function createInRealmAccountCustodyClientOwner(options: InRealmAccountCustodyClientOwnerOptions): AccountCustodyClientOwner {\n const limits = finiteLimits(options.limits)\n const account = options.account\n const address = account.address\n if (!reserveInRealmAccount(address)) throw new AccountCustodyClientError('account-reserved')\n const state: ClientOwnerState = {\n account, address, limits, stopped: options.nativeState !== 'established-live', executions: new Set(), tail: Promise.resolve(),\n }\n const owner: AccountCustodyClientOwner = Object.freeze({\n address,\n limits,\n assurance: scopedClientAssurance,\n get outstandingOperations() { return state.executions.size },\n get status() { return state.stopped ? 'stopped' : state.executions.size > 0 ? 'running' : 'ready' },\n drain: async () => { await state.tail },\n stop: () => { stopClientOwner(state) },\n })\n owners.set(owner, state)\n return owner\n}\n\nexport function getClientOwnerState(owner: AccountCustodyClientOwner): ClientOwnerState {\n const state = owners.get(owner)\n if (state === undefined) throw new AccountCustodyClientError('unissued-owner')\n return state\n}\n", "import {\n afterClientQueue, observeClientExecution, settleClientExecution,\n} from './clientExecution.ts'\nimport type { AccountCustodyClient, AccountCustodyClientOptions } from './clientModel.ts'\nimport { getClientOwnerState, scopedClientAssurance } from './clientOwner.ts'\nimport { clientSignalAborted } from './clientSignals.ts'\nimport {\n AccountCustodyClientError, assertClientOwnerReady, type ClientExecution, type ClientOwnerState, type ClientState, settleClientTail,\n} from './clientState.ts'\nimport type { AccountCustodyExecuteOptions } from './model.ts'\n\nfunction captureSignal(options: AccountCustodyExecuteOptions): AbortSignal | undefined {\n try {\n const signal = options.signal\n if (signal !== undefined) clientSignalAborted(signal)\n return signal\n } catch {\n throw new AccountCustodyClientError('invalid-request')\n }\n}\n\nfunction claimClient(owner: ClientOwnerState): ClientState {\n assertClientOwnerReady(owner)\n if (owner.current !== undefined && !owner.current.closed) throw new AccountCustodyClientError('client-active')\n if (owner.executions.size > 0 || (owner.current?.executions.size ?? 0) > 0) throw new AccountCustodyClientError('client-not-drained')\n const client: ClientState = {\n closed: false, executions: new Set(), tail: Promise.resolve(),\n }\n owner.current = client\n return client\n}\n\nfunction closeClient(client: ClientState): void {\n client.closed = true\n for (const execution of client.executions) {\n if (!execution.hasStarted) execution.controller.abort()\n }\n}\n\nasync function execute<Request, Result>(\n owner: ClientOwnerState,\n client: ClientState,\n options: AccountCustodyClientOptions<Request, Result>,\n request: Request,\n executeOptions: AccountCustodyExecuteOptions,\n): Promise<Result> {\n if (client.closed) throw new AccountCustodyClientError('stopped')\n assertClientOwnerReady(owner)\n if (owner.executions.size >= owner.limits.maxQueuedOperations + 1) throw new AccountCustodyClientError('capacity-exhausted')\n const signal = captureSignal(executeOptions)\n if (signal !== undefined && clientSignalAborted(signal)) throw new AccountCustodyClientError('cancelled-before-operation')\n let original: Request\n try {\n original = structuredClone(options.snapshot(request))\n } catch {\n throw new AccountCustodyClientError('invalid-request')\n }\n // Snapshot/getters may reenter public lifecycle methods; recheck actual admission.\n if (client.closed || owner.current !== client) throw new AccountCustodyClientError('stopped')\n assertClientOwnerReady(owner)\n if (owner.executions.size >= owner.limits.maxQueuedOperations + 1) throw new AccountCustodyClientError('capacity-exhausted')\n const execution: ClientExecution = {\n controller: new AbortController(), hasCompleted: false, hasStarted: false,\n }\n const observer = observeClientExecution<Result>(owner, execution, signal)\n owner.executions.add(execution)\n client.executions.add(execution)\n const pending = afterClientQueue(owner.tail, owner, client, options, execution, original)\n owner.tail = client.tail = settleClientTail(pending)\n void settleClientExecution(pending, observer)\n return await observer.result\n}\n\n/** Trusted issuer creates a single fenced client; clean close preserves its resident owner. */\nexport function createAccountCustodyClient<Request, Result>(input: AccountCustodyClientOptions<Request, Result>): AccountCustodyClient<Request, Result> {\n const ownerRef = input.owner\n const owner = getClientOwnerState(ownerRef)\n const bindingRef = input.binding\n const binding = Object.freeze({ address: bindingRef.address, domain: bindingRef.domain })\n if (binding.address !== owner.address || typeof binding.domain !== 'string' || binding.domain.length === 0)\n throw new AccountCustodyClientError('binding-mismatch')\n const options = Object.freeze({\n owner: ownerRef, binding, snapshot: input.snapshot, createOperation: input.createOperation,\n })\n if (typeof options.snapshot !== 'function' || typeof options.createOperation !== 'function') throw new AccountCustodyClientError('invalid-request')\n const client = claimClient(owner)\n return Object.freeze({\n binding,\n assurance: scopedClientAssurance,\n get outstandingOperations() { return client.executions.size },\n get status() { return client.closed || owner.stopped ? 'stopped' : client.executions.size > 0 ? 'running' : 'ready' },\n execute: async (request: Request, executeOptions: AccountCustodyExecuteOptions = {}) => await execute(owner, client, options, request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AQ,SAAS,SAAS,cAAc;AAAA,IACrJ,MAAM,MAAM;AAAE,kBAAY,MAAM;AAAA,IAAE;AAAA,IAClC,OAAO,YAAY;AAAE,YAAM,OAAO;AAAA,IAAK;AAAA,EACzC,CAAC;AACH;",
6
+ "names": ["registry", "key", "intrinsic", "nativeCall", "operationControl", "perform", "owners", "finiteLimits", "captureSignal"]
7
+ }
@@ -1,23 +1,12 @@
1
1
  // src/modules/address-payload-plugin/Plugin.ts
2
2
  import { createPayloadPlugin } from "@xyo-network/sdk-protocol";
3
- import { AddressSchema as AddressSchema2 } from "#module-model";
4
-
5
- // src/modules/address-payload-plugin/Template.ts
6
- import { ZERO_ADDRESS } from "@ariestools/sdk";
7
- import { AddressSchema } from "#module-model";
8
- var addressPayloadTemplate = () => ({
9
- address: ZERO_ADDRESS,
10
- schema: AddressSchema
11
- });
12
-
13
- // src/modules/address-payload-plugin/Plugin.ts
3
+ import { AddressPayloadZod, AddressSchema } from "#module-model";
14
4
  var AddressPayloadPlugin = () => createPayloadPlugin({
15
- schema: AddressSchema2,
16
- template: addressPayloadTemplate
5
+ schema: AddressSchema,
6
+ zod: AddressPayloadZod
17
7
  });
18
8
  export {
19
9
  AddressPayloadPlugin,
20
- addressPayloadTemplate,
21
10
  AddressPayloadPlugin as default
22
11
  };
23
12
  //# sourceMappingURL=address-payload-plugin.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/modules/address-payload-plugin/Plugin.ts", "../../src/modules/address-payload-plugin/Template.ts"],
4
- "sourcesContent": ["import type { PayloadPlugin } from '@xyo-network/sdk-protocol'\nimport { createPayloadPlugin } from '@xyo-network/sdk-protocol'\n\nimport type { AddressPayload } from '#module-model'\nimport { AddressSchema } from '#module-model'\n\nimport { addressPayloadTemplate } from './Template.ts'\n\nexport const AddressPayloadPlugin = (): PayloadPlugin<AddressPayload> =>\n createPayloadPlugin<AddressPayload>({\n schema: AddressSchema,\n template: addressPayloadTemplate,\n })\n", "import { ZERO_ADDRESS } from '@ariestools/sdk'\n\nimport type { AddressPayload } from '#module-model'\nimport { AddressSchema } from '#module-model'\n\nexport const addressPayloadTemplate = (): AddressPayload => ({\n address: ZERO_ADDRESS,\n schema: AddressSchema,\n})\n"],
5
- "mappings": ";AACA,SAAS,2BAA2B;AAGpC,SAAS,iBAAAA,sBAAqB;;;ACJ9B,SAAS,oBAAoB;AAG7B,SAAS,qBAAqB;AAEvB,IAAM,yBAAyB,OAAuB;AAAA,EAC3D,SAAS;AAAA,EACT,QAAQ;AACV;;;ADAO,IAAM,uBAAuB,MAClC,oBAAoC;AAAA,EAClC,QAAQC;AAAA,EACR,UAAU;AACZ,CAAC;",
6
- "names": ["AddressSchema", "AddressSchema"]
3
+ "sources": ["../../src/modules/address-payload-plugin/Plugin.ts"],
4
+ "sourcesContent": ["import type { PayloadPlugin } from '@xyo-network/sdk-protocol'\nimport { createPayloadPlugin } from '@xyo-network/sdk-protocol'\n\nimport type { AddressPayload } from '#module-model'\nimport { AddressPayloadZod, AddressSchema } from '#module-model'\n\nexport const AddressPayloadPlugin = (): PayloadPlugin<AddressPayload> =>\n createPayloadPlugin<AddressPayload>({\n schema: AddressSchema,\n zod: AddressPayloadZod,\n })\n"],
5
+ "mappings": ";AACA,SAAS,2BAA2B;AAGpC,SAAS,mBAAmB,qBAAqB;AAE1C,IAAM,uBAAuB,MAClC,oBAAoC;AAAA,EAClC,QAAQ;AAAA,EACR,KAAK;AACP,CAAC;",
6
+ "names": []
7
7
  }
@@ -131,8 +131,6 @@ import * as z6 from "zod/mini";
131
131
  import { DivinerConfigZod } from "#diviner-model";
132
132
  var RemoteDivinerConfigSchema = asSchema6("network.xyo.diviner.remote.config", true);
133
133
  var RemoteDivinerConfigZod = z6.extend(DivinerConfigZod, {
134
- /** @deprecated use in params instead */
135
- api: z6.optional(z6.custom()),
136
134
  archive: z6.optional(z6.string()),
137
135
  schema: z6.literal(RemoteDivinerConfigSchema)
138
136
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/modules/api-location-diviner/LocationDiviner/LocationDivinerApi.ts", "../../src/modules/api-location-diviner/LocationDiviner/Queries/LocationHeatmapQuery/LocationHeatmapQuery.ts", "../../src/modules/api-location-diviner/LocationDiviner/Witnesses/CurrentLocationWitness.ts", "../../src/modules/api-location-diviner/LocationDiviner/Witnesses/LocationWitness.ts", "../../src/modules/api-location-diviner/LocationDiviner/Queries/LocationQuadkeyHeatmapQuery/LocationQuadkeyHeatmapQuery.ts", "../../src/modules/api-location-diviner/LocationDiviner/Queries/LocationQuerySchema.ts", "../../src/modules/api-location-diviner/LocationDiviner/Queries/LocationTimeRangeQuery/LocationTimeRangeQuery.ts", "../../src/modules/api-location-diviner/RemoteDivinerConfig.ts", "../../src/modules/api-location-diviner/RemoteDivinerError.ts"],
4
- "sourcesContent": ["import { assertEx, fetchJsonClient } from '@ariestools/sdk'\n\nimport type { GetLocationQueryResponse } from './models.ts'\nimport type { LocationQueryCreationResponse, SupportedLocationQueryCreationRequest } from './Queries/index.ts'\n\ninterface LocationDivinerApiConfig {\n apiDomain: string\n}\n\ninterface JsonDataEnvelope<T> {\n data?: T\n}\n\nclass LocationDivinerApi {\n config: LocationDivinerApiConfig\n constructor(config: LocationDivinerApiConfig) {\n this.config = config\n }\n\n async getLocationQuery(hash: string): Promise<GetLocationQueryResponse> {\n const response = await fetchJsonClient.get<JsonDataEnvelope<GetLocationQueryResponse>>(`${this.config.apiDomain}/location/query/${hash}`)\n return assertEx(response.data?.data, () => 'LocationDivinerApi.getLocationQuery: missing response data')\n }\n\n async postLocationQuery(request: SupportedLocationQueryCreationRequest): Promise<LocationQueryCreationResponse> {\n const response = await fetchJsonClient.post<JsonDataEnvelope<LocationQueryCreationResponse>>(`${this.config.apiDomain}/location/query`, { ...request })\n return assertEx(response.data?.data, () => 'LocationDivinerApi.postLocationQuery: missing response data')\n }\n}\n\nexport { LocationDivinerApi }\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { LocationWitnessSchema } from '../../Witnesses/index.ts'\n\nexport const LocationHeatmapQuerySchema: 'network.xyo.location.heatmap.query' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.query', true)\nexport type LocationHeatmapQuerySchema = typeof LocationHeatmapQuerySchema\n\nexport const LocationHeatmapAnswerSchema: 'network.xyo.location.heatmap.answer' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.answer', true)\nexport type LocationHeatmapAnswerSchema = typeof LocationHeatmapAnswerSchema\n\nexport const LocationHeatmapQueryZod: z.ZodMiniObject<{\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n startTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n stopTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n}, z.core.$strip> = z.object({\n schema: z.literal(LocationWitnessSchema),\n startTime: z.optional(z.string()),\n stopTime: z.optional(z.string()),\n})\n\nexport type LocationHeatmapQuery = z.infer<typeof LocationHeatmapQueryZod>\n\nexport const isLocationHeatmapQuery: ReturnType<typeof zodIsFactory<LocationHeatmapQuery>> = zodIsFactory(LocationHeatmapQueryZod)\nexport const asLocationHeatmapQuery: ReturnType<typeof zodAsFactory<LocationHeatmapQuery>> = zodAsFactory(LocationHeatmapQueryZod, 'asLocationHeatmapQuery')\nexport const toLocationHeatmapQuery: ReturnType<typeof zodToFactory<LocationHeatmapQuery>> = zodToFactory(LocationHeatmapQueryZod, 'toLocationHeatmapQuery')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema, PayloadZodOfSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nexport const CurrentLocationWitnessSchema: 'co.coinapp.currentlocationwitness' & {\n readonly __schema: true\n} = asSchema('co.coinapp.currentlocationwitness', true)\nexport type CurrentLocationWitnessSchema = typeof CurrentLocationWitnessSchema\n\nexport const CurrentLocationWitnessPayloadZod: z.ZodMiniObject<{\n altitudeMeters: z.ZodMiniNumber<number>\n directionDegrees: z.ZodMiniNumber<number>\n latitude: z.ZodMiniNumber<number>\n longitude: z.ZodMiniNumber<number>\n quadkey: z.ZodMiniString<string>\n schema: z.ZodMiniLiteral<CurrentLocationWitnessSchema>\n speedKph: z.ZodMiniNumber<number>\n}, z.core.$strip> = z.extend(PayloadZodOfSchema(CurrentLocationWitnessSchema), {\n altitudeMeters: z.number(),\n directionDegrees: z.number(),\n latitude: z.number(),\n longitude: z.number(),\n quadkey: z.string(),\n speedKph: z.number(),\n})\n\nexport type CurrentLocationWitnessPayload = z.infer<typeof CurrentLocationWitnessPayloadZod>\n\nexport const isCurrentLocationWitnessPayload: ReturnType<typeof zodIsFactory<CurrentLocationWitnessPayload>>\n = zodIsFactory(CurrentLocationWitnessPayloadZod)\nexport const asCurrentLocationWitnessPayload: ReturnType<typeof zodAsFactory<CurrentLocationWitnessPayload>>\n = zodAsFactory(CurrentLocationWitnessPayloadZod, 'asCurrentLocationWitnessPayload')\nexport const toCurrentLocationWitnessPayload: ReturnType<typeof zodToFactory<CurrentLocationWitnessPayload>>\n = zodToFactory(CurrentLocationWitnessPayloadZod, 'toCurrentLocationWitnessPayload')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema, PayloadZodOfSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nexport const LocationWitnessSchema: 'network.xyo.location' & {\n readonly __schema: true\n} = asSchema('network.xyo.location', true)\nexport type LocationWitnessSchema = typeof LocationWitnessSchema\n\nexport interface Coordinates {\n accuracy: number | null\n altitude: number | null\n altitudeAccuracy: number | null\n heading: number | null\n latitude: number\n longitude: number\n speed: number | null\n}\nexport interface CurrentLocation {\n coords: Coordinates\n timestamp: number\n}\n\nexport const LocationWitnessPayloadZod: z.ZodMiniObject<{\n currentLocation: z.ZodMiniCustom<CurrentLocation, CurrentLocation>\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n}, z.core.$strip> = z.extend(PayloadZodOfSchema(LocationWitnessSchema), { currentLocation: z.custom<CurrentLocation>() })\n\nexport type LocationWitnessPayload = z.infer<typeof LocationWitnessPayloadZod>\n\nexport const isLocationWitnessPayload: ReturnType<typeof zodIsFactory<LocationWitnessPayload>> = zodIsFactory(LocationWitnessPayloadZod)\nexport const asLocationWitnessPayload: ReturnType<typeof zodAsFactory<LocationWitnessPayload>> = zodAsFactory(LocationWitnessPayloadZod, 'asLocationWitnessPayload')\nexport const toLocationWitnessPayload: ReturnType<typeof zodToFactory<LocationWitnessPayload>> = zodToFactory(LocationWitnessPayloadZod, 'toLocationWitnessPayload')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { LocationWitnessSchema } from '../../Witnesses/index.ts'\n\nexport const LocationQuadkeyHeatmapQuerySchema: 'network.xyo.location.heatmap.quadkey.query' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.quadkey.query', true)\nexport type LocationQuadkeyHeatmapQuerySchema = typeof LocationQuadkeyHeatmapQuerySchema\n\nexport const LocationQuadkeyHeatmapAnswerSchema: 'network.xyo.location.heatmap.quadkey.answer' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.quadkey.answer', true)\nexport type LocationQuadkeyHeatmapAnswerSchema = typeof LocationQuadkeyHeatmapAnswerSchema\n\nexport const LocationQuadkeyHeatmapQueryZod: z.ZodMiniObject<{\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n startTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n stopTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n}, z.core.$strip> = z.object({\n schema: z.literal(LocationWitnessSchema),\n startTime: z.optional(z.string()),\n stopTime: z.optional(z.string()),\n})\n\nexport type LocationQuadkeyHeatmapQuery = z.infer<typeof LocationQuadkeyHeatmapQueryZod>\n\nexport const isLocationQuadkeyHeatmapQuery: ReturnType<typeof zodIsFactory<LocationQuadkeyHeatmapQuery>>\n = zodIsFactory(LocationQuadkeyHeatmapQueryZod)\nexport const asLocationQuadkeyHeatmapQuery: ReturnType<typeof zodAsFactory<LocationQuadkeyHeatmapQuery>>\n = zodAsFactory(LocationQuadkeyHeatmapQueryZod, 'asLocationQuadkeyHeatmapQuery')\nexport const toLocationQuadkeyHeatmapQuery: ReturnType<typeof zodToFactory<LocationQuadkeyHeatmapQuery>>\n = zodToFactory(LocationQuadkeyHeatmapQueryZod, 'toLocationQuadkeyHeatmapQuery')\n", "import type { Schema } from '@xyo-network/sdk-protocol'\n\nimport type { LocationHeatmapQuerySchema } from './LocationHeatmapQuery/index.ts'\nimport type { LocationQuadkeyHeatmapQuerySchema } from './LocationQuadkeyHeatmapQuery/index.ts'\nimport type { LocationTimeRangeQuerySchema } from './LocationTimeRangeQuery/index.ts'\n\nexport type LocationQuerySchema = LocationQuadkeyHeatmapQuerySchema | LocationHeatmapQuerySchema | LocationTimeRangeQuerySchema\n\nconst locationQuerySchemas: Record<string, true> = {\n 'network.xyo.location.heatmap.quadkey.query': true,\n 'network.xyo.location.heatmap.query': true,\n 'network.xyo.location.range.query': true,\n}\n\nexport const isSupportedLocationQuerySchema = (schema: Schema): schema is LocationQuerySchema => {\n return locationQuerySchemas[schema as LocationQuerySchema]\n}\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { LocationWitnessSchema } from '../../Witnesses/index.ts'\n\nexport const LocationTimeRangeQuerySchema: 'network.xyo.location.range.query' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.range.query', true)\nexport type LocationTimeRangeQuerySchema = typeof LocationTimeRangeQuerySchema\n\nexport const LocationTimeRangeAnswerSchema: 'network.xyo.location.range.answer' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.range.answer', true)\nexport type LocationTimeRangeAnswerSchema = typeof LocationTimeRangeAnswerSchema\n\nexport const LocationTimeRangeQueryZod: z.ZodMiniObject<{\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n startTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n stopTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n}, z.core.$strip> = z.object({\n schema: z.literal(LocationWitnessSchema),\n startTime: z.optional(z.string()),\n // TODO: Bounding rectangle, etc.\n stopTime: z.optional(z.string()),\n})\n\nexport type LocationTimeRangeQuery = z.infer<typeof LocationTimeRangeQueryZod>\n\nexport const isLocationTimeRangeQuery: ReturnType<typeof zodIsFactory<LocationTimeRangeQuery>> = zodIsFactory(LocationTimeRangeQueryZod)\nexport const asLocationTimeRangeQuery: ReturnType<typeof zodAsFactory<LocationTimeRangeQuery>> = zodAsFactory(LocationTimeRangeQueryZod, 'asLocationTimeRangeQuery')\nexport const toLocationTimeRangeQuery: ReturnType<typeof zodToFactory<LocationTimeRangeQuery>> = zodToFactory(LocationTimeRangeQueryZod, 'toLocationTimeRangeQuery')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { DivinerConfigZod } from '#diviner-model'\n\nexport const RemoteDivinerConfigSchema: 'network.xyo.diviner.remote.config' & {\n readonly __schema: true\n} = asSchema('network.xyo.diviner.remote.config', true)\nexport type RemoteDivinerConfigSchema = typeof RemoteDivinerConfigSchema\n\nexport const RemoteDivinerConfigZod: z.ZodMiniObject<\n Omit<(typeof DivinerConfigZod)['shape'], 'schema'> & {\n /** @deprecated use in params instead */\n api: z.ZodMiniOptional<z.ZodMiniCustom<object, object>>\n archive: z.ZodMiniOptional<z.ZodMiniString<string>>\n schema: z.ZodMiniLiteral<RemoteDivinerConfigSchema>\n },\n z.core.$strip\n> = z.extend(DivinerConfigZod, {\n /** @deprecated use in params instead */\n api: z.optional(z.custom<object>()),\n archive: z.optional(z.string()),\n schema: z.literal(RemoteDivinerConfigSchema),\n})\n\nexport type RemoteDivinerConfig = z.infer<typeof RemoteDivinerConfigZod>\n\nexport const isRemoteDivinerConfig: ReturnType<typeof zodIsFactory<RemoteDivinerConfig>> = zodIsFactory(RemoteDivinerConfigZod)\nexport const asRemoteDivinerConfig: ReturnType<typeof zodAsFactory<RemoteDivinerConfig>> = zodAsFactory(RemoteDivinerConfigZod, 'asRemoteDivinerConfig')\nexport const toRemoteDivinerConfig: ReturnType<typeof zodToFactory<RemoteDivinerConfig>> = zodToFactory(RemoteDivinerConfigZod, 'toRemoteDivinerConfig')\n", "import { isString } from '@ariestools/sdk'\n\nexport class RemoteDivinerError extends Error {\n isRemoteDivinerError = true\n constructor(action: string, error: Error['cause'], message?: string) {\n const messageString = isString(message) ? ` (${message})` : ''\n super(`Remote Diviner [${action}] failed${messageString}`, { cause: error })\n }\n\n static isRemoteDivinerError(error: unknown): RemoteDivinerError | undefined {\n return (error as RemoteDivinerError).isRemoteDivinerError ? (error as RemoteDivinerError) : undefined\n }\n}\n"],
5
- "mappings": ";AAAA,SAAS,UAAU,uBAAuB;AAa1C,IAAM,qBAAN,MAAyB;AAAA,EACvB;AAAA,EACA,YAAY,QAAkC;AAC5C,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAM,iBAAiB,MAAiD;AACtE,UAAM,WAAW,MAAM,gBAAgB,IAAgD,GAAG,KAAK,OAAO,SAAS,mBAAmB,IAAI,EAAE;AACxI,WAAO,SAAS,SAAS,MAAM,MAAM,MAAM,4DAA4D;AAAA,EACzG;AAAA,EAEA,MAAM,kBAAkB,SAAwF;AAC9G,UAAM,WAAW,MAAM,gBAAgB,KAAsD,GAAG,KAAK,OAAO,SAAS,mBAAmB,EAAE,GAAG,QAAQ,CAAC;AACtJ,WAAO,SAAS,SAAS,MAAM,MAAM,MAAM,6DAA6D;AAAA,EAC1G;AACF;;;AC5BA;AA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0B;;;ACjCnK;AAAA,EACE,gBAAAC;AAAA,EAAc,gBAAAC;AAAA,EAAc,gBAAAC;AAAA,OACvB;AACP,SAAS,YAAAC,iBAAgB;AACzB,YAAYC,QAAO;AAEnB,SAAS,wBAAwB;AAE1B,IAAM,4BAETD,UAAS,qCAAqC,IAAI;AAG/C,IAAM,yBAQP,UAAO,kBAAkB;AAAA;AAAA,EAE7B,KAAO,YAAW,UAAe,CAAC;AAAA,EAClC,SAAW,YAAW,UAAO,CAAC;AAAA,EAC9B,QAAU,WAAQ,yBAAyB;AAC7C,CAAC;AAIM,IAAM,wBAA8EF,cAAa,sBAAsB;AACvH,IAAM,wBAA8ED,cAAa,wBAAwB,uBAAuB;AAChJ,IAAM,wBAA8EE,cAAa,wBAAwB,uBAAuB;;;AChCvJ,SAAS,gBAAgB;AAElB,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,uBAAuB;AAAA,EACvB,YAAY,QAAgB,OAAuB,SAAkB;AACnE,UAAM,gBAAgB,SAAS,OAAO,IAAI,KAAK,OAAO,MAAM;AAC5D,UAAM,mBAAmB,MAAM,WAAW,aAAa,IAAI,EAAE,OAAO,MAAM,CAAC;AAAA,EAC7E;AAAA,EAEA,OAAO,qBAAqB,OAAgD;AAC1E,WAAQ,MAA6B,uBAAwB,QAA+B;AAAA,EAC9F;AACF;",
4
+ "sourcesContent": ["import { assertEx, fetchJsonClient } from '@ariestools/sdk'\n\nimport type { GetLocationQueryResponse } from './models.ts'\nimport type { LocationQueryCreationResponse, SupportedLocationQueryCreationRequest } from './Queries/index.ts'\n\ninterface LocationDivinerApiConfig {\n apiDomain: string\n}\n\ninterface JsonDataEnvelope<T> {\n data?: T\n}\n\nclass LocationDivinerApi {\n config: LocationDivinerApiConfig\n constructor(config: LocationDivinerApiConfig) {\n this.config = config\n }\n\n async getLocationQuery(hash: string): Promise<GetLocationQueryResponse> {\n const response = await fetchJsonClient.get<JsonDataEnvelope<GetLocationQueryResponse>>(`${this.config.apiDomain}/location/query/${hash}`)\n return assertEx(response.data?.data, () => 'LocationDivinerApi.getLocationQuery: missing response data')\n }\n\n async postLocationQuery(request: SupportedLocationQueryCreationRequest): Promise<LocationQueryCreationResponse> {\n const response = await fetchJsonClient.post<JsonDataEnvelope<LocationQueryCreationResponse>>(`${this.config.apiDomain}/location/query`, { ...request })\n return assertEx(response.data?.data, () => 'LocationDivinerApi.postLocationQuery: missing response data')\n }\n}\n\nexport { LocationDivinerApi }\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { LocationWitnessSchema } from '../../Witnesses/index.ts'\n\nexport const LocationHeatmapQuerySchema: 'network.xyo.location.heatmap.query' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.query', true)\nexport type LocationHeatmapQuerySchema = typeof LocationHeatmapQuerySchema\n\nexport const LocationHeatmapAnswerSchema: 'network.xyo.location.heatmap.answer' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.answer', true)\nexport type LocationHeatmapAnswerSchema = typeof LocationHeatmapAnswerSchema\n\nexport const LocationHeatmapQueryZod: z.ZodMiniObject<{\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n startTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n stopTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n}, z.core.$strip> = z.object({\n schema: z.literal(LocationWitnessSchema),\n startTime: z.optional(z.string()),\n stopTime: z.optional(z.string()),\n})\n\nexport type LocationHeatmapQuery = z.infer<typeof LocationHeatmapQueryZod>\n\nexport const isLocationHeatmapQuery: ReturnType<typeof zodIsFactory<LocationHeatmapQuery>> = zodIsFactory(LocationHeatmapQueryZod)\nexport const asLocationHeatmapQuery: ReturnType<typeof zodAsFactory<LocationHeatmapQuery>> = zodAsFactory(LocationHeatmapQueryZod, 'asLocationHeatmapQuery')\nexport const toLocationHeatmapQuery: ReturnType<typeof zodToFactory<LocationHeatmapQuery>> = zodToFactory(LocationHeatmapQueryZod, 'toLocationHeatmapQuery')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema, PayloadZodOfSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nexport const CurrentLocationWitnessSchema: 'co.coinapp.currentlocationwitness' & {\n readonly __schema: true\n} = asSchema('co.coinapp.currentlocationwitness', true)\nexport type CurrentLocationWitnessSchema = typeof CurrentLocationWitnessSchema\n\nexport const CurrentLocationWitnessPayloadZod: z.ZodMiniObject<{\n altitudeMeters: z.ZodMiniNumber<number>\n directionDegrees: z.ZodMiniNumber<number>\n latitude: z.ZodMiniNumber<number>\n longitude: z.ZodMiniNumber<number>\n quadkey: z.ZodMiniString<string>\n schema: z.ZodMiniLiteral<CurrentLocationWitnessSchema>\n speedKph: z.ZodMiniNumber<number>\n}, z.core.$strip> = z.extend(PayloadZodOfSchema(CurrentLocationWitnessSchema), {\n altitudeMeters: z.number(),\n directionDegrees: z.number(),\n latitude: z.number(),\n longitude: z.number(),\n quadkey: z.string(),\n speedKph: z.number(),\n})\n\nexport type CurrentLocationWitnessPayload = z.infer<typeof CurrentLocationWitnessPayloadZod>\n\nexport const isCurrentLocationWitnessPayload: ReturnType<typeof zodIsFactory<CurrentLocationWitnessPayload>>\n = zodIsFactory(CurrentLocationWitnessPayloadZod)\nexport const asCurrentLocationWitnessPayload: ReturnType<typeof zodAsFactory<CurrentLocationWitnessPayload>>\n = zodAsFactory(CurrentLocationWitnessPayloadZod, 'asCurrentLocationWitnessPayload')\nexport const toCurrentLocationWitnessPayload: ReturnType<typeof zodToFactory<CurrentLocationWitnessPayload>>\n = zodToFactory(CurrentLocationWitnessPayloadZod, 'toCurrentLocationWitnessPayload')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema, PayloadZodOfSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nexport const LocationWitnessSchema: 'network.xyo.location' & {\n readonly __schema: true\n} = asSchema('network.xyo.location', true)\nexport type LocationWitnessSchema = typeof LocationWitnessSchema\n\nexport interface Coordinates {\n accuracy: number | null\n altitude: number | null\n altitudeAccuracy: number | null\n heading: number | null\n latitude: number\n longitude: number\n speed: number | null\n}\nexport interface CurrentLocation {\n coords: Coordinates\n timestamp: number\n}\n\nexport const LocationWitnessPayloadZod: z.ZodMiniObject<{\n currentLocation: z.ZodMiniCustom<CurrentLocation, CurrentLocation>\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n}, z.core.$strip> = z.extend(PayloadZodOfSchema(LocationWitnessSchema), { currentLocation: z.custom<CurrentLocation>() })\n\nexport type LocationWitnessPayload = z.infer<typeof LocationWitnessPayloadZod>\n\nexport const isLocationWitnessPayload: ReturnType<typeof zodIsFactory<LocationWitnessPayload>> = zodIsFactory(LocationWitnessPayloadZod)\nexport const asLocationWitnessPayload: ReturnType<typeof zodAsFactory<LocationWitnessPayload>> = zodAsFactory(LocationWitnessPayloadZod, 'asLocationWitnessPayload')\nexport const toLocationWitnessPayload: ReturnType<typeof zodToFactory<LocationWitnessPayload>> = zodToFactory(LocationWitnessPayloadZod, 'toLocationWitnessPayload')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { LocationWitnessSchema } from '../../Witnesses/index.ts'\n\nexport const LocationQuadkeyHeatmapQuerySchema: 'network.xyo.location.heatmap.quadkey.query' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.quadkey.query', true)\nexport type LocationQuadkeyHeatmapQuerySchema = typeof LocationQuadkeyHeatmapQuerySchema\n\nexport const LocationQuadkeyHeatmapAnswerSchema: 'network.xyo.location.heatmap.quadkey.answer' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.heatmap.quadkey.answer', true)\nexport type LocationQuadkeyHeatmapAnswerSchema = typeof LocationQuadkeyHeatmapAnswerSchema\n\nexport const LocationQuadkeyHeatmapQueryZod: z.ZodMiniObject<{\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n startTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n stopTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n}, z.core.$strip> = z.object({\n schema: z.literal(LocationWitnessSchema),\n startTime: z.optional(z.string()),\n stopTime: z.optional(z.string()),\n})\n\nexport type LocationQuadkeyHeatmapQuery = z.infer<typeof LocationQuadkeyHeatmapQueryZod>\n\nexport const isLocationQuadkeyHeatmapQuery: ReturnType<typeof zodIsFactory<LocationQuadkeyHeatmapQuery>>\n = zodIsFactory(LocationQuadkeyHeatmapQueryZod)\nexport const asLocationQuadkeyHeatmapQuery: ReturnType<typeof zodAsFactory<LocationQuadkeyHeatmapQuery>>\n = zodAsFactory(LocationQuadkeyHeatmapQueryZod, 'asLocationQuadkeyHeatmapQuery')\nexport const toLocationQuadkeyHeatmapQuery: ReturnType<typeof zodToFactory<LocationQuadkeyHeatmapQuery>>\n = zodToFactory(LocationQuadkeyHeatmapQueryZod, 'toLocationQuadkeyHeatmapQuery')\n", "import type { Schema } from '@xyo-network/sdk-protocol'\n\nimport type { LocationHeatmapQuerySchema } from './LocationHeatmapQuery/index.ts'\nimport type { LocationQuadkeyHeatmapQuerySchema } from './LocationQuadkeyHeatmapQuery/index.ts'\nimport type { LocationTimeRangeQuerySchema } from './LocationTimeRangeQuery/index.ts'\n\nexport type LocationQuerySchema = LocationQuadkeyHeatmapQuerySchema | LocationHeatmapQuerySchema | LocationTimeRangeQuerySchema\n\nconst locationQuerySchemas: Record<string, true> = {\n 'network.xyo.location.heatmap.quadkey.query': true,\n 'network.xyo.location.heatmap.query': true,\n 'network.xyo.location.range.query': true,\n}\n\nexport const isSupportedLocationQuerySchema = (schema: Schema): schema is LocationQuerySchema => {\n return locationQuerySchemas[schema as LocationQuerySchema]\n}\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { LocationWitnessSchema } from '../../Witnesses/index.ts'\n\nexport const LocationTimeRangeQuerySchema: 'network.xyo.location.range.query' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.range.query', true)\nexport type LocationTimeRangeQuerySchema = typeof LocationTimeRangeQuerySchema\n\nexport const LocationTimeRangeAnswerSchema: 'network.xyo.location.range.answer' & {\n readonly __schema: true\n} = asSchema('network.xyo.location.range.answer', true)\nexport type LocationTimeRangeAnswerSchema = typeof LocationTimeRangeAnswerSchema\n\nexport const LocationTimeRangeQueryZod: z.ZodMiniObject<{\n schema: z.ZodMiniLiteral<LocationWitnessSchema>\n startTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n stopTime: z.ZodMiniOptional<z.ZodMiniString<string>>\n}, z.core.$strip> = z.object({\n schema: z.literal(LocationWitnessSchema),\n startTime: z.optional(z.string()),\n // TODO: Bounding rectangle, etc.\n stopTime: z.optional(z.string()),\n})\n\nexport type LocationTimeRangeQuery = z.infer<typeof LocationTimeRangeQueryZod>\n\nexport const isLocationTimeRangeQuery: ReturnType<typeof zodIsFactory<LocationTimeRangeQuery>> = zodIsFactory(LocationTimeRangeQueryZod)\nexport const asLocationTimeRangeQuery: ReturnType<typeof zodAsFactory<LocationTimeRangeQuery>> = zodAsFactory(LocationTimeRangeQueryZod, 'asLocationTimeRangeQuery')\nexport const toLocationTimeRangeQuery: ReturnType<typeof zodToFactory<LocationTimeRangeQuery>> = zodToFactory(LocationTimeRangeQueryZod, 'toLocationTimeRangeQuery')\n", "import {\n zodAsFactory, zodIsFactory, zodToFactory,\n} from '@ariestools/sdk'\nimport { asSchema } from '@xyo-network/sdk-protocol'\nimport * as z from 'zod/mini'\n\nimport { DivinerConfigZod } from '#diviner-model'\n\nexport const RemoteDivinerConfigSchema: 'network.xyo.diviner.remote.config' & {\n readonly __schema: true\n} = asSchema('network.xyo.diviner.remote.config', true)\nexport type RemoteDivinerConfigSchema = typeof RemoteDivinerConfigSchema\n\nexport const RemoteDivinerConfigZod: z.ZodMiniObject<\n Omit<(typeof DivinerConfigZod)['shape'], 'schema'> & {\n archive: z.ZodMiniOptional<z.ZodMiniString<string>>\n schema: z.ZodMiniLiteral<RemoteDivinerConfigSchema>\n },\n z.core.$strip\n> = z.extend(DivinerConfigZod, {\n archive: z.optional(z.string()),\n schema: z.literal(RemoteDivinerConfigSchema),\n})\n\nexport type RemoteDivinerConfig = z.infer<typeof RemoteDivinerConfigZod>\n\nexport const isRemoteDivinerConfig: ReturnType<typeof zodIsFactory<RemoteDivinerConfig>> = zodIsFactory(RemoteDivinerConfigZod)\nexport const asRemoteDivinerConfig: ReturnType<typeof zodAsFactory<RemoteDivinerConfig>> = zodAsFactory(RemoteDivinerConfigZod, 'asRemoteDivinerConfig')\nexport const toRemoteDivinerConfig: ReturnType<typeof zodToFactory<RemoteDivinerConfig>> = zodToFactory(RemoteDivinerConfigZod, 'toRemoteDivinerConfig')\n", "import { isString } from '@ariestools/sdk'\n\nexport class RemoteDivinerError extends Error {\n isRemoteDivinerError = true\n constructor(action: string, error: Error['cause'], message?: string) {\n const messageString = isString(message) ? ` (${message})` : ''\n super(`Remote Diviner [${action}] failed${messageString}`, { cause: error })\n }\n\n static isRemoteDivinerError(error: unknown): RemoteDivinerError | undefined {\n return (error as RemoteDivinerError).isRemoteDivinerError ? (error as RemoteDivinerError) : undefined\n }\n}\n"],
5
+ "mappings": ";AAAA,SAAS,UAAU,uBAAuB;AAa1C,IAAM,qBAAN,MAAyB;AAAA,EACvB;AAAA,EACA,YAAY,QAAkC;AAC5C,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,MAAM,iBAAiB,MAAiD;AACtE,UAAM,WAAW,MAAM,gBAAgB,IAAgD,GAAG,KAAK,OAAO,SAAS,mBAAmB,IAAI,EAAE;AACxI,WAAO,SAAS,SAAS,MAAM,MAAM,MAAM,4DAA4D;AAAA,EACzG;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AAAA,EACvC,WAAa,YAAW,UAAO,CAAC;AAAA;AAAA,EAEhC,UAAY,YAAW,UAAO,CAAC;AACjC,CAAC;AAIM,IAAM,2BAAoFC,cAAa,yBAAyB;AAChI,IAAM,2BAAoFC,cAAa,2BAA2B,0BAA0B;AAC5J,IAAM,2BAAoFC,cAAa,2BAA2B,0BAA0B;;;ACjCnK;AAAA,EACE,gBAAAC;AAAA,EAAc,gBAAAC;AAAA,EAAc,gBAAAC;AAAA,OACvB;AACP,SAAS,YAAAC,iBAAgB;AACzB,YAAYC,QAAO;AAEnB,SAAS,wBAAwB;AAE1B,IAAM,4BAETD,UAAS,qCAAqC,IAAI;AAG/C,IAAM,yBAMP,UAAO,kBAAkB;AAAA,EAC7B,SAAW,YAAW,UAAO,CAAC;AAAA,EAC9B,QAAU,WAAQ,yBAAyB;AAC7C,CAAC;AAIM,IAAM,wBAA8EF,cAAa,sBAAsB;AACvH,IAAM,wBAA8ED,cAAa,wBAAwB,uBAAuB;AAChJ,IAAM,wBAA8EE,cAAa,wBAAwB,uBAAuB;;;AC5BvJ,SAAS,gBAAgB;AAElB,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,uBAAuB;AAAA,EACvB,YAAY,QAAgB,OAAuB,SAAkB;AACnE,UAAM,gBAAgB,SAAS,OAAO,IAAI,KAAK,OAAO,MAAM;AAC5D,UAAM,mBAAmB,MAAM,WAAW,aAAa,IAAI,EAAE,OAAO,MAAM,CAAC;AAAA,EAC7E;AAAA,EAEA,OAAO,qBAAqB,OAAgD;AAC1E,WAAQ,MAA6B,uBAAwB,QAA+B;AAAA,EAC9F;AACF;",
6
6
  "names": ["zodAsFactory", "zodIsFactory", "zodToFactory", "asSchema", "z", "zodAsFactory", "zodIsFactory", "zodToFactory", "asSchema", "PayloadZodOfSchema", "z", "asSchema", "zodIsFactory", "zodAsFactory", "zodToFactory", "zodAsFactory", "zodIsFactory", "zodToFactory", "asSchema", "z", "asSchema", "zodIsFactory", "zodAsFactory", "zodToFactory", "zodAsFactory", "zodIsFactory", "zodToFactory", "asSchema", "z", "asSchema", "zodIsFactory", "zodAsFactory", "zodToFactory", "zodAsFactory", "zodIsFactory", "zodToFactory", "asSchema", "z"]
7
7
  }
@@ -24,6 +24,46 @@ import {
24
24
  import { AbstractModuleInstance } from "#module-abstract";
25
25
  import { duplicateModules } from "#module-model";
26
26
 
27
+ // src/modules/archivist-abstract/InsertSequencer.ts
28
+ import { SequenceConstants, SequenceParser } from "@xyo-network/sdk-protocol";
29
+ import { Mutex } from "async-mutex";
30
+ var INDEXES_PER_EPOCH = 2 ** (SequenceConstants.nonceIndexBytes * 8);
31
+ var InsertSequencer = class {
32
+ epoch = 0;
33
+ index = 0;
34
+ mutex = new Mutex();
35
+ /** Sequence a batch in input order and write it before the next batch is sequenced. */
36
+ async write(payloads, write) {
37
+ return await this.mutex.runExclusive(async () => await write(this.sequence(payloads)));
38
+ }
39
+ /**
40
+ * Reserve consecutive slots that sort after every slot reserved before. The
41
+ * epoch is the wall clock. Within one millisecond, or while the clock is
42
+ * behind the last epoch used, the nonce index keeps counting instead of
43
+ * restarting, so the hash tail never decides the order of two inserts.
44
+ */
45
+ reserve(count) {
46
+ const now = Date.now();
47
+ if (now > this.epoch) {
48
+ this.epoch = now;
49
+ this.index = 0;
50
+ } else if (this.index + count > INDEXES_PER_EPOCH) {
51
+ this.epoch += 1;
52
+ this.index = 0;
53
+ }
54
+ const index = this.index;
55
+ this.index += count;
56
+ return { epoch: this.epoch, index };
57
+ }
58
+ sequence(payloads) {
59
+ const { epoch, index } = this.reserve(payloads.length);
60
+ return payloads.map((payload, offset) => ({
61
+ ...payload,
62
+ _sequence: SequenceParser.from(epoch, payload._hash, index + offset).localSequence
63
+ }));
64
+ }
65
+ };
66
+
27
67
  // src/modules/archivist-abstract/StorageClassLabel.ts
28
68
  var StorageClassLabel = "network.xyo.storage.class";
29
69
 
@@ -36,6 +76,7 @@ var AbstractArchivist = class _AbstractArchivist extends AbstractModuleInstance
36
76
  // override this if a specialized archivist should have a different default next limit
37
77
  static defaultNextLimitSetting = 100;
38
78
  _getCache;
79
+ _insertSequencer = new InsertSequencer();
39
80
  _parentArchivists;
40
81
  _payloadCountGauge;
41
82
  _payloadCountMeter;
@@ -370,18 +411,20 @@ var AbstractArchivist = class _AbstractArchivist extends AbstractModuleInstance
370
411
  const emitEvents = config?.emitEvents ?? true;
371
412
  const writeToParents = config?.writeToParents ?? true;
372
413
  await this.validateInsertPayloads(sanitizedPayloads);
373
- const withStorageMeta = await PayloadBuilder.addStorageMeta(sanitizedPayloads);
374
- const hashes = [...new Set(withStorageMeta.map((payload) => payload._hash))];
375
- const { existingPayloads, insertedPayloads } = await this.withStorageMutation(async () => {
376
- const existingPayloads2 = await this.getExistingLocalPayloads(hashes);
377
- await this.repairExistingPayloads(existingPayloads2);
378
- const existingHashes = new Set(existingPayloads2.map((payload) => payload._hash));
379
- const payloadsToInsert = withStorageMeta.filter((payload) => {
380
- if (existingHashes.has(payload._hash)) return false;
381
- existingHashes.add(payload._hash);
382
- return true;
414
+ const withHashMeta = await PayloadBuilder.addHashMeta(sanitizedPayloads);
415
+ const hashes = [...new Set(withHashMeta.map((payload) => payload._hash))];
416
+ const { existingPayloads, insertedPayloads } = await this._insertSequencer.write(withHashMeta, async (withStorageMeta) => {
417
+ return await this.withStorageMutation(async () => {
418
+ const existingPayloads2 = await this.getExistingLocalPayloads(hashes);
419
+ await this.repairExistingPayloads(existingPayloads2);
420
+ const existingHashes = new Set(existingPayloads2.map((payload) => payload._hash));
421
+ const payloadsToInsert = withStorageMeta.filter((payload) => {
422
+ if (existingHashes.has(payload._hash)) return false;
423
+ existingHashes.add(payload._hash);
424
+ return true;
425
+ });
426
+ return { existingPayloads: existingPayloads2, insertedPayloads: await this.insertHandler(payloadsToInsert) };
383
427
  });
384
- return { existingPayloads: existingPayloads2, insertedPayloads: await this.insertHandler(payloadsToInsert) };
385
428
  });
386
429
  if (writeToParents) {
387
430
  await this.writeToParents([...existingPayloads, ...insertedPayloads]);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/modules/archivist-abstract/AbstractArchivist.ts", "../../src/modules/archivist-abstract/StorageClassLabel.ts", "../../src/modules/archivist-abstract/payloadAdmission.ts"],
4
- "sourcesContent": ["/* eslint-disable max-lines */\nimport type {\n Hash, Promisable, PromisableArray,\n} from '@ariestools/sdk'\nimport {\n assertEx,\n exists,\n isNull, isUndefined,\n} from '@ariestools/sdk'\nimport type {\n Attributes, Gauge, Meter,\n} from '@opentelemetry/api'\nimport type {\n AccountInstance, BoundWitness, Payload, QueryBoundWitness,\n Schema, WithStorageMeta, XyoAddress,\n} from '@xyo-network/sdk-protocol'\nimport { PayloadBuilder, QueryBoundWitnessWrapper } from '@xyo-network/sdk-protocol'\nimport { LRUCache } from 'lru-cache'\n\nimport type {\n ArchivistAllQuery,\n ArchivistClearQuery,\n ArchivistCommitQuery,\n ArchivistDeleteQuery,\n ArchivistGetQuery,\n ArchivistInsertQuery,\n ArchivistInstance,\n ArchivistModuleEventData,\n ArchivistNextOptions,\n ArchivistNextQuery,\n ArchivistParams,\n ArchivistQueries,\n ArchivistSnapshotPayload,\n ArchivistSnapshotQuery,\n ArchivistStatsPayload,\n AttachableArchivistInstance,\n ReadArchivist,\n} from '#archivist-model'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistCommitQuerySchema,\n ArchivistConfigSchema,\n ArchivistDeleteQuerySchema,\n ArchivistGetQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistNextQuerySchema,\n ArchivistSnapshotQuerySchema,\n ArchivistStatsPayloadSchema,\n asArchivistInstance,\n isArchivistInstance,\n} from '#archivist-model'\nimport { AbstractModuleInstance } from '#module-abstract'\nimport type {\n ModuleConfig, ModuleIdentifier, ModuleQueryHandlerResult, ModuleQueryResult,\n} from '#module-model'\nimport { duplicateModules } from '#module-model'\n\nimport { StorageClassLabel } from './StorageClassLabel.ts'\n\nconst NOT_IMPLEMENTED = 'Not implemented' as const\n\nexport interface ActionConfig {\n emitEvents?: boolean\n}\n\nexport interface InsertConfig extends ActionConfig {\n writeToParents?: boolean\n}\n\ninterface ArchivistParentInstanceMap {\n commit?: Partial<Record<ModuleIdentifier, ArchivistInstance>>\n read?: Partial<Record<ModuleIdentifier, ArchivistInstance>>\n write?: Partial<Record<ModuleIdentifier, ArchivistInstance>>\n}\n\nexport abstract class AbstractArchivist<\n TParams extends ArchivistParams = ArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n>\n extends AbstractModuleInstance<TParams, TEventData>\n implements AttachableArchivistInstance<TParams, TEventData, Payload> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, ArchivistConfigSchema]\n static override readonly defaultConfigSchema: Schema = ArchivistConfigSchema\n static override readonly labels: {\n 'network.xyo.storage.class': string\n } = { ...super.labels, [StorageClassLabel]: 'unknown' }\n\n // override this if a specialized archivist should have a different default next limit\n protected static defaultNextLimitSetting = 100\n\n private _getCache?: LRUCache<Hash, WithStorageMeta<Payload>>\n private _parentArchivists?: ArchivistParentInstanceMap\n private _payloadCountGauge?: Gauge | null\n private _payloadCountMeter?: Meter | null\n\n private activeCacheMutations = 0\n private cacheGeneration = 0\n\n // do not override this! It is meant to get the this.defaultNextLimitSetting and work if it is overridden\n static get defaultNextLimit(): number {\n return this.defaultNextLimitSetting\n }\n\n override get queries(): Schema[] {\n return [ArchivistGetQuerySchema, ...super.queries]\n }\n\n get requireAllParents(): boolean {\n return this.config.requireAllParents ?? false\n }\n\n protected get payloadCountGauge(): Gauge<Attributes> | null | undefined {\n const meter = this.payloadCountMeter\n if (!isNull(meter)) {\n this._payloadCountGauge = meter?.createGauge('payloadCount', { description: 'Payloads in the archivist' })\n }\n return this._payloadCountGauge\n }\n\n protected get payloadCountMeter(): Meter | null {\n if (isUndefined(this._payloadCountMeter)) {\n this._payloadCountMeter = this.params?.meterProvider?.getMeter(this.id) ?? null\n }\n return this._payloadCountMeter ?? null\n }\n\n protected get storeParentReads(): boolean {\n return this.config?.storeParentReads === true\n }\n\n /** @deprecated use next or snapshot instead */\n async all(): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('all')\n this.isSupportedQuery(ArchivistAllQuerySchema, 'all')\n return await this.spanAsync(`${this.id}|all`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return PayloadBuilder.omitPrivateStorageMeta(await this.allHandler()) as WithStorageMeta<Payload>[]\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n /** deprecated use nextQuery or snapshotQuery instead */\n async allQuery(account: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('allQuery')\n const queryPayload: ArchivistAllQuery = { schema: ArchivistAllQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async clear(): Promise<void> {\n this._noOverride('clear')\n this.isSupportedQuery(ArchivistClearQuerySchema, 'clear')\n return await this.spanAsync(`${this.id}|clear`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n await this.clearWithConfig()\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async clearQuery(account: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('clearQuery')\n const queryPayload: ArchivistClearQuery = { schema: ArchivistClearQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async commit(): Promise<BoundWitness[]> {\n this._noOverride('commit')\n this.isSupportedQuery(ArchivistCommitQuerySchema, 'commit')\n return await this.spanAsync(`${this.id}commit`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.commitHandler()\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async commitQuery(account: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('commitQuery')\n const queryPayload: ArchivistCommitQuery = { schema: ArchivistCommitQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async delete(hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('delete')\n this.isSupportedQuery(ArchivistDeleteQuerySchema, 'delete')\n return await this.spanAsync(`${this.id}|delete`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.deleteWithConfig(hashes)\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async deleteQuery(hashes: Hash[], account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('deleteQuery')\n const queryPayload: ArchivistDeleteQuery = { hashes, schema: ArchivistDeleteQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async get(hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('get')\n this.isSupportedQuery(ArchivistGetQuerySchema, 'get')\n return await this.spanAsync(`${this.id}|get`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.getWithConfig(hashes)\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async getQuery(hashes: Hash[], account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('getQuery')\n const queryPayload: ArchivistGetQuery = { hashes, schema: ArchivistGetQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async insert(payloads: Payload[]): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('insert')\n this.isSupportedQuery(ArchivistInsertQuerySchema, 'insert')\n const snapshot = this.snapshotPayloads(payloads)\n return await this.spanAsync(`${this.id}|insert`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.insertWithConfig(snapshot)\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async insertQuery(payloads: Payload[], account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('insertQuery')\n const queryPayload: ArchivistInsertQuery = { schema: ArchivistInsertQuerySchema }\n return await this.sendQueryRaw(queryPayload, this.snapshotPayloads(payloads), account)\n }\n\n async next(options?: ArchivistNextOptions): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('next')\n this.isSupportedQuery(ArchivistNextQuerySchema, 'next')\n return await this.spanAsync(`${this.id}|next`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n const { limit = AbstractArchivist.defaultNextLimit, ...otherOptions } = options ?? {}\n return await this.nextWithConfig({ limit, ...otherOptions })\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async nextQuery(options?: ArchivistNextOptions, account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('nextQuery')\n const queryPayload: ArchivistNextQuery = { schema: ArchivistNextQuerySchema, ...options }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async snapshot(): Promise<ArchivistSnapshotPayload<WithStorageMeta<Payload>, Hash>[]> {\n this._noOverride('snapshot')\n this.isSupportedQuery(ArchivistSnapshotQuerySchema, 'snapshot')\n return await this.spanAsync(`${this.id}|snapshot`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n throw new Error('Cannot take snapshot while in a global reentrancy lock')\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.snapshotHandler()\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async snapshotQuery(account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('snapshotQuery')\n const queryPayload: ArchivistSnapshotQuery = { schema: ArchivistSnapshotQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n protected allHandler(): PromisableArray<WithStorageMeta<Payload>> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected clearHandler(): Promisable<void> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async clearWithConfig(config?: ActionConfig): Promise<void> {\n await this.withCacheMutation(async () => {\n await this.withStorageMutation(async () => await this.clearHandler())\n this.reportPayloadCount()\n if (config?.emitEvents ?? true) await this.emit('cleared', { mod: this })\n })\n }\n\n protected commitHandler(): Promisable<BoundWitness[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected deleteHandler(_hashes: Hash[]): PromisableArray<WithStorageMeta<Payload>> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async deleteWithConfig(hashes: Hash[], config?: ActionConfig): Promise<WithStorageMeta<Payload>[]> {\n return await this.withCacheMutation(async () => {\n const emitEvents = config?.emitEvents ?? true\n\n const payloads = await this.withStorageMutation(async () => await this.deleteHandler(hashes))\n const hashesDeleted = payloads.map(p => p._hash)\n\n if (emitEvents) {\n await this.emit('deleted', {\n hashes: hashesDeleted, payloads, mod: this,\n })\n }\n this.reportPayloadCount()\n return payloads\n })\n }\n\n protected generateStats(): Promisable<ArchivistStatsPayload> {\n return {\n payloadCount: this.payloadCountHandler(),\n schema: ArchivistStatsPayloadSchema,\n }\n }\n\n /**\n * Inspect local stored roots without consulting public projections, caches or\n * parents. Backends whose getHandler synthesizes views must override this hook\n * to read their primary record keys directly.\n */\n protected async getExistingLocalPayloads(hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n return await this.exactRepresentations(await this.getHandler(hashes), hashes)\n }\n\n protected async getFromParent(hashes: Hash[], archivist: ReadArchivist): Promise<[WithStorageMeta<Payload>[], Hash[]]> {\n const foundPayloads = await this.requestedRepresentations(await archivist.get(hashes), hashes)\n const foundHashes = new Set(foundPayloads.map(payload => payload._hash))\n return [foundPayloads, hashes.filter(hash => !foundHashes.has(hash))]\n }\n\n protected async getFromParents(hashes: Hash[]): Promise<[WithStorageMeta<Payload>[], Hash[]]> {\n const parentArchivists = await this.parentArchivists()\n const parents = Object.values(parentArchivists?.read ?? {})\n let remainingHashes = [...hashes]\n let parentIndex = 0\n let result: WithStorageMeta<Payload>[] = []\n\n // Intentionally doing this serially\n while (parentIndex < parents.length && remainingHashes.length > 0) {\n const parent = parents[parentIndex]\n if (parent) {\n const [found, notfound] = await this.getFromParent(remainingHashes, parent)\n result = [...result, ...found]\n remainingHashes = notfound\n }\n parentIndex++\n }\n return [result, remainingHashes]\n }\n\n protected getHandler(_hashes: Hash[]): Promisable<WithStorageMeta<Payload>[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async getWithConfig(hashes: Hash[], _config?: InsertConfig): Promise<WithStorageMeta<Payload>[]> {\n const requestedHashes = [...new Set(hashes)]\n const generation = this.cacheGeneration\n const cache = this.activeCacheMutations === 0 ? this._getCache : undefined\n const fromCache = await this.requestedRepresentations(requestedHashes.map(hash => cache?.get(hash)).filter(exists), requestedHashes)\n const cachedHashes = new Set(fromCache.map(payload => payload._hash))\n const remainingHashes = requestedHashes.filter(hash => !cachedHashes.has(hash))\n const fromGet = await this.requestedRepresentations(await this.getHandler(remainingHashes), remainingHashes)\n const foundHashes = new Set([...fromCache, ...fromGet].map(payload => payload._hash))\n const [parentFoundPayloads] = await this.getFromParents(requestedHashes.filter(hash => !foundHashes.has(hash)))\n\n if (this.storeParentReads && parentFoundPayloads.length > 0) {\n await this.insertWithConfig(parentFoundPayloads)\n }\n // Cache only verified, requested representations. A data-only view must not\n // replace the root representation under its different full hash.\n if (this.activeCacheMutations === 0 && generation === this.cacheGeneration) {\n for (const payload of [...fromGet, ...parentFoundPayloads]) cache?.set(payload._hash, payload)\n }\n return PayloadBuilder.omitPrivateStorageMeta(\n [...fromCache, ...fromGet, ...parentFoundPayloads].toSorted(PayloadBuilder.compareStorageMeta),\n ) as WithStorageMeta<Payload>[]\n }\n\n protected insertHandler(_payloads: WithStorageMeta<Payload>[]): Promisable<WithStorageMeta<Payload>[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async insertQueryHandler<T extends QueryBoundWitnessWrapper = QueryBoundWitnessWrapper>(query: T, payloads?: Payload[]): Promise<WithStorageMeta<Payload>[]> {\n assertEx(payloads, () => `Missing payloads: ${JSON.stringify(query.payload, null, 2)}`)\n const resolvedPayloads = await PayloadBuilder.filterIncludeByEitherHash(payloads, query.payloadHashes)\n assertEx(\n resolvedPayloads.length === query.payloadHashes.length,\n () => `Could not find some passed hashes [${resolvedPayloads.length} != ${query.payloadHashes.length}]`,\n )\n const queryPayload = await query.getQuery()\n const payloadsWithoutQuery = await PayloadBuilder.filterExclude(resolvedPayloads, await PayloadBuilder.dataHash(queryPayload))\n const result = await this.insertWithConfig(payloadsWithoutQuery)\n return result\n }\n\n protected async insertWithConfig(payloads: Payload[], config?: InsertConfig): Promise<WithStorageMeta<Payload>[]> {\n const sanitizedPayloads = this.snapshotPayloads(payloads)\n return await this.withCacheMutation(async () => {\n const emitEvents = config?.emitEvents ?? true\n const writeToParents = config?.writeToParents ?? true\n\n await this.validateInsertPayloads(sanitizedPayloads)\n const withStorageMeta = await PayloadBuilder.addStorageMeta(sanitizedPayloads)\n const hashes = [...new Set(withStorageMeta.map(payload => payload._hash))]\n const { existingPayloads, insertedPayloads } = await this.withStorageMutation(async () => {\n const existingPayloads = await this.getExistingLocalPayloads(hashes)\n await this.repairExistingPayloads(existingPayloads)\n const existingHashes = new Set(existingPayloads.map(payload => payload._hash))\n const payloadsToInsert = withStorageMeta.filter((payload) => {\n if (existingHashes.has(payload._hash)) return false\n existingHashes.add(payload._hash)\n return true\n })\n return { existingPayloads, insertedPayloads: await this.insertHandler(payloadsToInsert) }\n })\n\n if (writeToParents) {\n // A previous attempt may have stored locally before a parent failed.\n // Retry the current request's existing roots as well as its new roots.\n await this.writeToParents([...existingPayloads, ...insertedPayloads])\n }\n if (emitEvents) {\n await this.emit('inserted', {\n mod: this, payloads: insertedPayloads, outPayloads: insertedPayloads, inPayloads: payloads,\n })\n }\n this.reportPayloadCount()\n return PayloadBuilder.omitPrivateStorageMeta(insertedPayloads) as WithStorageMeta<Payload>[]\n })\n }\n\n protected nextHandler(_options?: ArchivistNextOptions): Promisable<WithStorageMeta<Payload>[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async nextWithConfig(options?: ArchivistNextOptions, _config?: InsertConfig): Promise<WithStorageMeta<Payload>[]> {\n const foundPayloads = await this.nextHandler(options)\n return PayloadBuilder.omitPrivateStorageMeta(foundPayloads) as WithStorageMeta<Payload>[]\n }\n\n protected async parentArchivists(): Promise<ArchivistParentInstanceMap> {\n this._parentArchivists ??= {\n commit: { ...await this.resolveArchivists(this.config?.parents?.commit, this.params.parents?.commit) },\n read: { ...await this.resolveArchivists(this.config?.parents?.read) },\n write: { ...await this.resolveArchivists(this.config?.parents?.write) },\n }\n return assertEx(this._parentArchivists)\n }\n\n // the number of payloads in the archivist, -1 if not implemented\n // the implementations of these must be fast, so they may not be promises and should read an auto updated value\n protected payloadCountHandler() {\n return -1\n }\n\n // eslint-disable-next-line max-statements\n protected override async queryHandler<T extends QueryBoundWitness = QueryBoundWitness, TConfig extends ModuleConfig = ModuleConfig>(\n query: T,\n payloads: Payload[],\n queryConfig?: TConfig,\n ): Promise<ModuleQueryHandlerResult> {\n const sanitizedQuery = PayloadBuilder.omitStorageMeta(query) as T\n const sanitizedPayloads = this.snapshotPayloads(payloads)\n const wrappedQuery = QueryBoundWitnessWrapper.parseQuery<ArchivistQueries>(sanitizedQuery, sanitizedPayloads)\n const queryPayload = await wrappedQuery.getQuery()\n assertEx(await this.queryable(sanitizedQuery, sanitizedPayloads, queryConfig))\n const resultPayloads: Payload[] = []\n\n switch (queryPayload.schema) {\n case ArchivistAllQuerySchema: {\n resultPayloads.push(...(await this.allHandler()))\n break\n }\n case ArchivistClearQuerySchema: {\n await this.clearWithConfig()\n break\n }\n case ArchivistCommitQuerySchema: {\n resultPayloads.push(...(await this.commitHandler()))\n break\n }\n case ArchivistDeleteQuerySchema: {\n const typedQueryPayload = queryPayload as ArchivistDeleteQuery\n resultPayloads.push(...(await this.deleteWithConfig(typedQueryPayload.hashes)))\n break\n }\n case ArchivistGetQuerySchema: {\n const typedQueryPayload = queryPayload as ArchivistGetQuery\n resultPayloads.push(...(await this.getWithConfig(typedQueryPayload.hashes ?? [])))\n break\n }\n case ArchivistInsertQuerySchema: {\n resultPayloads.push(...(await this.insertQueryHandler(wrappedQuery, sanitizedPayloads)))\n break\n }\n case ArchivistNextQuerySchema: {\n const typedQueryPayload = queryPayload as ArchivistNextQuery\n resultPayloads.push(...(await this.nextHandler(typedQueryPayload)))\n break\n }\n case ArchivistSnapshotQuerySchema: {\n resultPayloads.push(...(await this.snapshotHandler()))\n break\n }\n default: {\n const result = await super.queryHandler(sanitizedQuery, sanitizedPayloads)\n if (this.config.storeQueries === true) {\n await this.insertWithConfig([sanitizedQuery])\n }\n return PayloadBuilder.omitPrivateStorageMeta(result)\n }\n }\n if (this.config.storeQueries === true) {\n await this.insertWithConfig([sanitizedQuery])\n }\n return PayloadBuilder.omitPrivateStorageMeta(resultPayloads)\n }\n\n /** Restore derived indexes for a stored root without rewriting its body. */\n protected repairExistingPayloads(_payloads: WithStorageMeta<Payload>[]): Promisable<void> {\n return undefined\n }\n\n protected reportPayloadCount(): void {\n this._noOverride('reportPayloadCount')\n const gauge = this.payloadCountGauge\n if (gauge) {\n gauge.record(this.payloadCountHandler())\n }\n }\n\n protected snapshotHandler(): PromisableArray<ArchivistSnapshotPayload<WithStorageMeta<Payload>, Hash>> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected override async startHandler(): Promise<void> {\n if (this.config.getCache?.enabled === true) {\n this._getCache = new LRUCache({\n max: this.config.getCache?.maxEntries ?? 10_000,\n allowStale: true,\n noDisposeOnSet: false,\n updateAgeOnGet: true,\n })\n }\n const result = await super.startHandler()\n this.reportPayloadCount()\n return result\n }\n\n protected override async stateHandler(): Promise<Payload[]> {\n return [...await super.stateHandler(), await this.generateStats()]\n }\n\n /** Enforce backend admission before lookup, repair, insertion or parent writes. */\n protected validateInsertPayloads(_payloads: Payload[]): Promisable<void> {\n return undefined\n }\n\n /** Serialize local storage changes without holding a lock across callbacks or parents. */\n protected async withStorageMutation<T>(operation: () => Promise<T>): Promise<T> {\n return await operation()\n }\n\n protected async writeToParent(parent: ArchivistInstance, payloads: Payload[]): Promise<Payload[]> {\n if (payloads.length === 0) return []\n const sanitized = PayloadBuilder.omitStorageMeta(payloads)\n const hashes = [...new Set(await Promise.all(sanitized.map(payload => PayloadBuilder.hash(payload))))]\n const inserted = await this.exactRepresentations(await parent.insert(sanitized), hashes)\n const insertedHashes = new Set(inserted.map(payload => payload._hash))\n const missing = hashes.filter(hash => !insertedHashes.has(hash))\n const existing = missing.length > 0 ? await this.exactRepresentations(await parent.get(missing), missing) : []\n const acknowledged = new Set([...inserted, ...existing].map(payload => payload._hash))\n if (hashes.some(hash => !acknowledged.has(hash))) {\n throw new Error('Write parent did not acknowledge all requested payloads')\n }\n return [...inserted, ...existing]\n }\n\n protected async writeToParents(payloads: Payload[]): Promise<Payload[]> {\n const parents = await this.parentArchivists()\n const results = await Promise.all(\n Object.values(parents.write ?? {}).map(async (parent) => {\n return parent ? await this.writeToParent(parent, payloads) : undefined\n }),\n )\n return results.filter(exists).flat()\n }\n\n private async exactRepresentations(payloads: WithStorageMeta<Payload>[], hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n const requested = new Set(hashes)\n const found = new Map<Hash, WithStorageMeta<Payload>>()\n for (const payload of payloads) {\n await this.verifyPayloadIdentity(payload)\n if (requested.has(payload._hash)) found.set(payload._hash, payload)\n }\n return found.values().toArray()\n }\n\n private async requestedRepresentations(payloads: WithStorageMeta<Payload>[], hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n const requested = new Set(hashes)\n const result = new Map<Hash, WithStorageMeta<Payload>>()\n const sorted = payloads.toSorted(PayloadBuilder.compareStorageMeta)\n // Prefer actual stored roots (including their original sequence) before\n // constructing data-only views from a different client-metadata variant.\n for (const payload of sorted) {\n await this.verifyPayloadIdentity(payload)\n if (requested.has(payload._hash) && !result.has(payload._hash)) result.set(payload._hash, payload)\n }\n for (const payload of sorted) {\n if (!requested.has(payload._dataHash) || result.has(payload._dataHash)) {\n continue\n }\n\n const dataOnly = PayloadBuilder.omitClientMeta(payload) as WithStorageMeta<Payload>\n result.set(payload._dataHash, { ...dataOnly, _hash: payload._dataHash })\n }\n return result.values().toArray()\n }\n\n private async resolveArchivists(archivists: ModuleIdentifier[] = [], archivistInstances?: ArchivistInstance[]) {\n const resolvedArchivists = await Promise.all(archivists.map(archivist => this.resolve(archivist)))\n const archivistModules = resolvedArchivists.filter(exists).filter(duplicateModules)\n\n assertEx(\n !this.requireAllParents || (archivistModules.length === archivists.length),\n () =>\n `Failed to find some archivists for ${this.modName} (set allRequired to false if ok)]`,\n )\n\n const archivistInstancesMap: Record<XyoAddress, ArchivistInstance> = {}\n const resolvedInstances = archivistInstances ?? []\n for (const archivistInstance of resolvedInstances) {\n archivistInstancesMap[archivistInstance.address] = archivistInstance\n }\n\n for (const mod of archivistModules) {\n archivistInstancesMap[mod.address] = asArchivistInstance(mod, () => {\n isArchivistInstance(mod, { log: console })\n return `Unable to cast resolved module to an archivist: [${mod.address}, ${mod.modName}, ${mod.config.schema})}]`\n }, { required: true })\n }\n return archivistInstancesMap\n }\n\n private snapshotPayloads(payloads: Payload[]): Payload[] {\n // Payloads are JSON values. Capture their bytes before asynchronous work so\n // admission, identity computation and the backend see the same input.\n // JSON normalization is intentional; structuredClone preserves non-JSON values.\n // eslint-disable-next-line unicorn/prefer-structured-clone\n return JSON.parse(JSON.stringify(PayloadBuilder.omitStorageMeta(payloads))) as Payload[]\n }\n\n private async verifyPayloadIdentity(payload: WithStorageMeta<Payload>): Promise<void> {\n const canonicalPayload = PayloadBuilder.omitStorageMeta(payload)\n const [hash, dataHash] = await Promise.all([\n PayloadBuilder.hash(canonicalPayload), PayloadBuilder.dataHash(canonicalPayload),\n ])\n if (hash !== payload._hash || dataHash !== payload._dataHash) {\n throw new Error('Archivist returned payload with invalid hash metadata')\n }\n }\n\n private async withCacheMutation<T>(operation: () => Promise<T>): Promise<T> {\n this.activeCacheMutations++\n this.cacheGeneration++\n this._getCache?.clear()\n try {\n return await operation()\n } finally {\n // Even a failed mutation can have changed persistent state. In-flight reads\n // may finish, but their old generation must never repopulate the cache.\n this.activeCacheMutations--\n this.cacheGeneration++\n this._getCache?.clear()\n }\n }\n}\n", "export const StorageClassLabel = 'network.xyo.storage.class'\nexport type StorageClassLabelValue = 'memory' | 'disk' | 'network' | 'proxy' | 'unknown'\n", "import type { Payload } from '@xyo-network/sdk-protocol'\nimport { PayloadBuilder } from '@xyo-network/sdk-protocol'\n\n/** Exact schema admission and limits on UTF-8 JSON bytes before compression. */\nexport interface PayloadAdmissionPolicy {\n /** An empty allowlist admits nothing. */\n allowedSchemas: string[]\n maxPayloadBytes: number\n /** Per-schema limits can only tighten the global limit. */\n schemaMaxPayloadBytes?: Record<string, number>\n}\n\nfunction validByteLimit(value: number): boolean {\n return Number.isSafeInteger(value) && value > 0\n}\n\nexport function validatePayloadAdmissionPolicy(policy: PayloadAdmissionPolicy): void {\n if (!Array.isArray(policy?.allowedSchemas)\n || policy.allowedSchemas.some(schema => typeof schema !== 'string' || schema.length === 0 || schema.trim() !== schema)\n || !validByteLimit(policy.maxPayloadBytes)) {\n throw new TypeError('Invalid payload admission policy')\n }\n if (policy.schemaMaxPayloadBytes === undefined) {\n return\n }\n\n if (policy.schemaMaxPayloadBytes === null || typeof policy.schemaMaxPayloadBytes !== 'object' || Array.isArray(policy.schemaMaxPayloadBytes)) {\n throw new TypeError('Invalid schema payload byte limits')\n }\n for (const [schema, limit] of Object.entries(policy.schemaMaxPayloadBytes)) {\n if (!policy.allowedSchemas.includes(schema) || !validByteLimit(limit)) {\n throw new TypeError('Invalid schema payload byte limits')\n }\n }\n}\n\n/** Reject the entire batch before any storage action if one payload is ineligible. */\nexport function validatePayloadAdmission(payloads: Payload[], policy: PayloadAdmissionPolicy): void {\n validatePayloadAdmissionPolicy(policy)\n const allowed = new Set(policy.allowedSchemas)\n for (const payload of payloads) {\n if (!allowed.has(payload.schema)) throw new Error('Payload schema is not admitted by this archivist')\n const schemaLimit = policy.schemaMaxPayloadBytes && Object.hasOwn(policy.schemaMaxPayloadBytes, payload.schema)\n ? policy.schemaMaxPayloadBytes[payload.schema]\n : policy.maxPayloadBytes\n const limit = Math.min(policy.maxPayloadBytes, schemaLimit)\n const json = JSON.stringify(PayloadBuilder.omitStorageMeta(payload))\n const textEncoder = new TextEncoder()\n if (textEncoder.encode(json).byteLength > limit) {\n throw new Error('Payload exceeds this archivist byte limit')\n }\n }\n}\n"],
5
- "mappings": ";AAIA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EAAQ;AAAA,OACH;AAQP,SAAS,gBAAgB,gCAAgC;AACzD,SAAS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AAgB,OAAO,CAAC;AACnE,UAAM,cAAc,IAAI,YAAY;AACpC,QAAI,YAAY,OAAO,IAAI,EAAE,aAAa,OAAO;AAC/C,YAAM,IAAI,MAAM,2CAA2C;AAAA,IAC7D;AAAA,EACF;AACF;",
3
+ "sources": ["../../src/modules/archivist-abstract/AbstractArchivist.ts", "../../src/modules/archivist-abstract/InsertSequencer.ts", "../../src/modules/archivist-abstract/StorageClassLabel.ts", "../../src/modules/archivist-abstract/payloadAdmission.ts"],
4
+ "sourcesContent": ["/* eslint-disable max-lines */\nimport type {\n Hash, Promisable, PromisableArray,\n} from '@ariestools/sdk'\nimport {\n assertEx,\n exists,\n isNull, isUndefined,\n} from '@ariestools/sdk'\nimport type {\n Attributes, Gauge, Meter,\n} from '@opentelemetry/api'\nimport type {\n AccountInstance, BoundWitness, Payload, QueryBoundWitness,\n Schema, WithStorageMeta, XyoAddress,\n} from '@xyo-network/sdk-protocol'\nimport { PayloadBuilder, QueryBoundWitnessWrapper } from '@xyo-network/sdk-protocol'\nimport { LRUCache } from 'lru-cache'\n\nimport type {\n ArchivistAllQuery,\n ArchivistClearQuery,\n ArchivistCommitQuery,\n ArchivistDeleteQuery,\n ArchivistGetQuery,\n ArchivistInsertQuery,\n ArchivistInstance,\n ArchivistModuleEventData,\n ArchivistNextOptions,\n ArchivistNextQuery,\n ArchivistParams,\n ArchivistQueries,\n ArchivistSnapshotPayload,\n ArchivistSnapshotQuery,\n ArchivistStatsPayload,\n AttachableArchivistInstance,\n ReadArchivist,\n} from '#archivist-model'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistCommitQuerySchema,\n ArchivistConfigSchema,\n ArchivistDeleteQuerySchema,\n ArchivistGetQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistNextQuerySchema,\n ArchivistSnapshotQuerySchema,\n ArchivistStatsPayloadSchema,\n asArchivistInstance,\n isArchivistInstance,\n} from '#archivist-model'\nimport { AbstractModuleInstance } from '#module-abstract'\nimport type {\n ModuleConfig, ModuleIdentifier, ModuleQueryHandlerResult, ModuleQueryResult,\n} from '#module-model'\nimport { duplicateModules } from '#module-model'\n\nimport { InsertSequencer } from './InsertSequencer.ts'\nimport { StorageClassLabel } from './StorageClassLabel.ts'\n\nconst NOT_IMPLEMENTED = 'Not implemented' as const\n\nexport interface ActionConfig {\n emitEvents?: boolean\n}\n\nexport interface InsertConfig extends ActionConfig {\n writeToParents?: boolean\n}\n\ninterface ArchivistParentInstanceMap {\n commit?: Partial<Record<ModuleIdentifier, ArchivistInstance>>\n read?: Partial<Record<ModuleIdentifier, ArchivistInstance>>\n write?: Partial<Record<ModuleIdentifier, ArchivistInstance>>\n}\n\nexport abstract class AbstractArchivist<\n TParams extends ArchivistParams = ArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n>\n extends AbstractModuleInstance<TParams, TEventData>\n implements AttachableArchivistInstance<TParams, TEventData, Payload> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, ArchivistConfigSchema]\n static override readonly defaultConfigSchema: Schema = ArchivistConfigSchema\n static override readonly labels: {\n 'network.xyo.storage.class': string\n } = { ...super.labels, [StorageClassLabel]: 'unknown' }\n\n // override this if a specialized archivist should have a different default next limit\n protected static defaultNextLimitSetting = 100\n\n private _getCache?: LRUCache<Hash, WithStorageMeta<Payload>>\n private readonly _insertSequencer = new InsertSequencer()\n private _parentArchivists?: ArchivistParentInstanceMap\n private _payloadCountGauge?: Gauge | null\n private _payloadCountMeter?: Meter | null\n\n private activeCacheMutations = 0\n private cacheGeneration = 0\n\n // do not override this! It is meant to get the this.defaultNextLimitSetting and work if it is overridden\n static get defaultNextLimit(): number {\n return this.defaultNextLimitSetting\n }\n\n override get queries(): Schema[] {\n return [ArchivistGetQuerySchema, ...super.queries]\n }\n\n get requireAllParents(): boolean {\n return this.config.requireAllParents ?? false\n }\n\n protected get payloadCountGauge(): Gauge<Attributes> | null | undefined {\n const meter = this.payloadCountMeter\n if (!isNull(meter)) {\n this._payloadCountGauge = meter?.createGauge('payloadCount', { description: 'Payloads in the archivist' })\n }\n return this._payloadCountGauge\n }\n\n protected get payloadCountMeter(): Meter | null {\n if (isUndefined(this._payloadCountMeter)) {\n this._payloadCountMeter = this.params?.meterProvider?.getMeter(this.id) ?? null\n }\n return this._payloadCountMeter ?? null\n }\n\n protected get storeParentReads(): boolean {\n return this.config?.storeParentReads === true\n }\n\n /** @deprecated use next or snapshot instead */\n async all(): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('all')\n this.isSupportedQuery(ArchivistAllQuerySchema, 'all')\n return await this.spanAsync(`${this.id}|all`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return PayloadBuilder.omitPrivateStorageMeta(await this.allHandler()) as WithStorageMeta<Payload>[]\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n /** deprecated use nextQuery or snapshotQuery instead */\n async allQuery(account: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('allQuery')\n const queryPayload: ArchivistAllQuery = { schema: ArchivistAllQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async clear(): Promise<void> {\n this._noOverride('clear')\n this.isSupportedQuery(ArchivistClearQuerySchema, 'clear')\n return await this.spanAsync(`${this.id}|clear`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n await this.clearWithConfig()\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async clearQuery(account: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('clearQuery')\n const queryPayload: ArchivistClearQuery = { schema: ArchivistClearQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async commit(): Promise<BoundWitness[]> {\n this._noOverride('commit')\n this.isSupportedQuery(ArchivistCommitQuerySchema, 'commit')\n return await this.spanAsync(`${this.id}commit`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.commitHandler()\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async commitQuery(account: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('commitQuery')\n const queryPayload: ArchivistCommitQuery = { schema: ArchivistCommitQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async delete(hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('delete')\n this.isSupportedQuery(ArchivistDeleteQuerySchema, 'delete')\n return await this.spanAsync(`${this.id}|delete`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.deleteWithConfig(hashes)\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async deleteQuery(hashes: Hash[], account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('deleteQuery')\n const queryPayload: ArchivistDeleteQuery = { hashes, schema: ArchivistDeleteQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async get(hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('get')\n this.isSupportedQuery(ArchivistGetQuerySchema, 'get')\n return await this.spanAsync(`${this.id}|get`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.getWithConfig(hashes)\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async getQuery(hashes: Hash[], account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('getQuery')\n const queryPayload: ArchivistGetQuery = { hashes, schema: ArchivistGetQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async insert(payloads: Payload[]): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('insert')\n this.isSupportedQuery(ArchivistInsertQuerySchema, 'insert')\n const snapshot = this.snapshotPayloads(payloads)\n return await this.spanAsync(`${this.id}|insert`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.insertWithConfig(snapshot)\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async insertQuery(payloads: Payload[], account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('insertQuery')\n const queryPayload: ArchivistInsertQuery = { schema: ArchivistInsertQuerySchema }\n return await this.sendQueryRaw(queryPayload, this.snapshotPayloads(payloads), account)\n }\n\n async next(options?: ArchivistNextOptions): Promise<WithStorageMeta<Payload>[]> {\n this._noOverride('next')\n this.isSupportedQuery(ArchivistNextQuerySchema, 'next')\n return await this.spanAsync(`${this.id}|next`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n return []\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n const { limit = AbstractArchivist.defaultNextLimit, ...otherOptions } = options ?? {}\n return await this.nextWithConfig({ limit, ...otherOptions })\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async nextQuery(options?: ArchivistNextOptions, account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('nextQuery')\n const queryPayload: ArchivistNextQuery = { schema: ArchivistNextQuerySchema, ...options }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n async snapshot(): Promise<ArchivistSnapshotPayload<WithStorageMeta<Payload>, Hash>[]> {\n this._noOverride('snapshot')\n this.isSupportedQuery(ArchivistSnapshotQuerySchema, 'snapshot')\n return await this.spanAsync(`${this.id}|snapshot`, async () => {\n if (this.reentrancy?.scope === 'global' && this.reentrancy.action === 'skip' && this.globalReentrancyMutex?.isLocked() === true) {\n throw new Error('Cannot take snapshot while in a global reentrancy lock')\n }\n try {\n await this.globalReentrancyMutex?.acquire()\n return await this.busy(async () => {\n await this.startedAsync('throw')\n return await this.snapshotHandler()\n })\n } finally {\n this.globalReentrancyMutex?.release()\n }\n }, { timeBudgetLimit: this.timeBudget })\n }\n\n async snapshotQuery(account?: AccountInstance): Promise<ModuleQueryResult> {\n this._noOverride('snapshotQuery')\n const queryPayload: ArchivistSnapshotQuery = { schema: ArchivistSnapshotQuerySchema }\n return await this.sendQueryRaw(queryPayload, undefined, account)\n }\n\n protected allHandler(): PromisableArray<WithStorageMeta<Payload>> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected clearHandler(): Promisable<void> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async clearWithConfig(config?: ActionConfig): Promise<void> {\n await this.withCacheMutation(async () => {\n await this.withStorageMutation(async () => await this.clearHandler())\n this.reportPayloadCount()\n if (config?.emitEvents ?? true) await this.emit('cleared', { mod: this })\n })\n }\n\n protected commitHandler(): Promisable<BoundWitness[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected deleteHandler(_hashes: Hash[]): PromisableArray<WithStorageMeta<Payload>> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async deleteWithConfig(hashes: Hash[], config?: ActionConfig): Promise<WithStorageMeta<Payload>[]> {\n return await this.withCacheMutation(async () => {\n const emitEvents = config?.emitEvents ?? true\n\n const payloads = await this.withStorageMutation(async () => await this.deleteHandler(hashes))\n const hashesDeleted = payloads.map(p => p._hash)\n\n if (emitEvents) {\n await this.emit('deleted', {\n hashes: hashesDeleted, payloads, mod: this,\n })\n }\n this.reportPayloadCount()\n return payloads\n })\n }\n\n protected generateStats(): Promisable<ArchivistStatsPayload> {\n return {\n payloadCount: this.payloadCountHandler(),\n schema: ArchivistStatsPayloadSchema,\n }\n }\n\n /**\n * Inspect local stored roots without consulting public projections, caches or\n * parents. Backends whose getHandler synthesizes views must override this hook\n * to read their primary record keys directly.\n */\n protected async getExistingLocalPayloads(hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n return await this.exactRepresentations(await this.getHandler(hashes), hashes)\n }\n\n protected async getFromParent(hashes: Hash[], archivist: ReadArchivist): Promise<[WithStorageMeta<Payload>[], Hash[]]> {\n const foundPayloads = await this.requestedRepresentations(await archivist.get(hashes), hashes)\n const foundHashes = new Set(foundPayloads.map(payload => payload._hash))\n return [foundPayloads, hashes.filter(hash => !foundHashes.has(hash))]\n }\n\n protected async getFromParents(hashes: Hash[]): Promise<[WithStorageMeta<Payload>[], Hash[]]> {\n const parentArchivists = await this.parentArchivists()\n const parents = Object.values(parentArchivists?.read ?? {})\n let remainingHashes = [...hashes]\n let parentIndex = 0\n let result: WithStorageMeta<Payload>[] = []\n\n // Intentionally doing this serially\n while (parentIndex < parents.length && remainingHashes.length > 0) {\n const parent = parents[parentIndex]\n if (parent) {\n const [found, notfound] = await this.getFromParent(remainingHashes, parent)\n result = [...result, ...found]\n remainingHashes = notfound\n }\n parentIndex++\n }\n return [result, remainingHashes]\n }\n\n protected getHandler(_hashes: Hash[]): Promisable<WithStorageMeta<Payload>[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async getWithConfig(hashes: Hash[], _config?: InsertConfig): Promise<WithStorageMeta<Payload>[]> {\n const requestedHashes = [...new Set(hashes)]\n const generation = this.cacheGeneration\n const cache = this.activeCacheMutations === 0 ? this._getCache : undefined\n const fromCache = await this.requestedRepresentations(requestedHashes.map(hash => cache?.get(hash)).filter(exists), requestedHashes)\n const cachedHashes = new Set(fromCache.map(payload => payload._hash))\n const remainingHashes = requestedHashes.filter(hash => !cachedHashes.has(hash))\n const fromGet = await this.requestedRepresentations(await this.getHandler(remainingHashes), remainingHashes)\n const foundHashes = new Set([...fromCache, ...fromGet].map(payload => payload._hash))\n const [parentFoundPayloads] = await this.getFromParents(requestedHashes.filter(hash => !foundHashes.has(hash)))\n\n if (this.storeParentReads && parentFoundPayloads.length > 0) {\n await this.insertWithConfig(parentFoundPayloads)\n }\n // Cache only verified, requested representations. A data-only view must not\n // replace the root representation under its different full hash.\n if (this.activeCacheMutations === 0 && generation === this.cacheGeneration) {\n for (const payload of [...fromGet, ...parentFoundPayloads]) cache?.set(payload._hash, payload)\n }\n return PayloadBuilder.omitPrivateStorageMeta(\n [...fromCache, ...fromGet, ...parentFoundPayloads].toSorted(PayloadBuilder.compareStorageMeta),\n ) as WithStorageMeta<Payload>[]\n }\n\n protected insertHandler(_payloads: WithStorageMeta<Payload>[]): Promisable<WithStorageMeta<Payload>[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async insertQueryHandler<T extends QueryBoundWitnessWrapper = QueryBoundWitnessWrapper>(query: T, payloads?: Payload[]): Promise<WithStorageMeta<Payload>[]> {\n assertEx(payloads, () => `Missing payloads: ${JSON.stringify(query.payload, null, 2)}`)\n const resolvedPayloads = await PayloadBuilder.filterIncludeByEitherHash(payloads, query.payloadHashes)\n assertEx(\n resolvedPayloads.length === query.payloadHashes.length,\n () => `Could not find some passed hashes [${resolvedPayloads.length} != ${query.payloadHashes.length}]`,\n )\n const queryPayload = await query.getQuery()\n const payloadsWithoutQuery = await PayloadBuilder.filterExclude(resolvedPayloads, await PayloadBuilder.dataHash(queryPayload))\n const result = await this.insertWithConfig(payloadsWithoutQuery)\n return result\n }\n\n protected async insertWithConfig(payloads: Payload[], config?: InsertConfig): Promise<WithStorageMeta<Payload>[]> {\n const sanitizedPayloads = this.snapshotPayloads(payloads)\n return await this.withCacheMutation(async () => {\n const emitEvents = config?.emitEvents ?? true\n const writeToParents = config?.writeToParents ?? true\n\n await this.validateInsertPayloads(sanitizedPayloads)\n // Hashing does not depend on order, so it stays outside the sequencer's lock.\n const withHashMeta = await PayloadBuilder.addHashMeta(sanitizedPayloads)\n const hashes = [...new Set(withHashMeta.map(payload => payload._hash))]\n // Sequenced and written as one step, so a cursor reader never sees a\n // payload ahead of one with a lower sequence that is still being written.\n const { existingPayloads, insertedPayloads } = await this._insertSequencer.write(withHashMeta, async (withStorageMeta) => {\n return await this.withStorageMutation(async () => {\n const existingPayloads = await this.getExistingLocalPayloads(hashes)\n await this.repairExistingPayloads(existingPayloads)\n const existingHashes = new Set(existingPayloads.map(payload => payload._hash))\n const payloadsToInsert = withStorageMeta.filter((payload) => {\n if (existingHashes.has(payload._hash)) return false\n existingHashes.add(payload._hash)\n return true\n })\n return { existingPayloads, insertedPayloads: await this.insertHandler(payloadsToInsert) }\n })\n })\n\n if (writeToParents) {\n // A previous attempt may have stored locally before a parent failed.\n // Retry the current request's existing roots as well as its new roots.\n await this.writeToParents([...existingPayloads, ...insertedPayloads])\n }\n if (emitEvents) {\n await this.emit('inserted', {\n mod: this, payloads: insertedPayloads, outPayloads: insertedPayloads, inPayloads: payloads,\n })\n }\n this.reportPayloadCount()\n return PayloadBuilder.omitPrivateStorageMeta(insertedPayloads) as WithStorageMeta<Payload>[]\n })\n }\n\n protected nextHandler(_options?: ArchivistNextOptions): Promisable<WithStorageMeta<Payload>[]> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected async nextWithConfig(options?: ArchivistNextOptions, _config?: InsertConfig): Promise<WithStorageMeta<Payload>[]> {\n const foundPayloads = await this.nextHandler(options)\n return PayloadBuilder.omitPrivateStorageMeta(foundPayloads) as WithStorageMeta<Payload>[]\n }\n\n protected async parentArchivists(): Promise<ArchivistParentInstanceMap> {\n this._parentArchivists ??= {\n commit: { ...await this.resolveArchivists(this.config?.parents?.commit, this.params.parents?.commit) },\n read: { ...await this.resolveArchivists(this.config?.parents?.read) },\n write: { ...await this.resolveArchivists(this.config?.parents?.write) },\n }\n return assertEx(this._parentArchivists)\n }\n\n // the number of payloads in the archivist, -1 if not implemented\n // the implementations of these must be fast, so they may not be promises and should read an auto updated value\n protected payloadCountHandler() {\n return -1\n }\n\n // eslint-disable-next-line max-statements\n protected override async queryHandler<T extends QueryBoundWitness = QueryBoundWitness, TConfig extends ModuleConfig = ModuleConfig>(\n query: T,\n payloads: Payload[],\n queryConfig?: TConfig,\n ): Promise<ModuleQueryHandlerResult> {\n const sanitizedQuery = PayloadBuilder.omitStorageMeta(query) as T\n const sanitizedPayloads = this.snapshotPayloads(payloads)\n const wrappedQuery = QueryBoundWitnessWrapper.parseQuery<ArchivistQueries>(sanitizedQuery, sanitizedPayloads)\n const queryPayload = await wrappedQuery.getQuery()\n assertEx(await this.queryable(sanitizedQuery, sanitizedPayloads, queryConfig))\n const resultPayloads: Payload[] = []\n\n switch (queryPayload.schema) {\n case ArchivistAllQuerySchema: {\n resultPayloads.push(...(await this.allHandler()))\n break\n }\n case ArchivistClearQuerySchema: {\n await this.clearWithConfig()\n break\n }\n case ArchivistCommitQuerySchema: {\n resultPayloads.push(...(await this.commitHandler()))\n break\n }\n case ArchivistDeleteQuerySchema: {\n const typedQueryPayload = queryPayload as ArchivistDeleteQuery\n resultPayloads.push(...(await this.deleteWithConfig(typedQueryPayload.hashes)))\n break\n }\n case ArchivistGetQuerySchema: {\n const typedQueryPayload = queryPayload as ArchivistGetQuery\n resultPayloads.push(...(await this.getWithConfig(typedQueryPayload.hashes ?? [])))\n break\n }\n case ArchivistInsertQuerySchema: {\n resultPayloads.push(...(await this.insertQueryHandler(wrappedQuery, sanitizedPayloads)))\n break\n }\n case ArchivistNextQuerySchema: {\n const typedQueryPayload = queryPayload as ArchivistNextQuery\n resultPayloads.push(...(await this.nextHandler(typedQueryPayload)))\n break\n }\n case ArchivistSnapshotQuerySchema: {\n resultPayloads.push(...(await this.snapshotHandler()))\n break\n }\n default: {\n const result = await super.queryHandler(sanitizedQuery, sanitizedPayloads)\n if (this.config.storeQueries === true) {\n await this.insertWithConfig([sanitizedQuery])\n }\n return PayloadBuilder.omitPrivateStorageMeta(result)\n }\n }\n if (this.config.storeQueries === true) {\n await this.insertWithConfig([sanitizedQuery])\n }\n return PayloadBuilder.omitPrivateStorageMeta(resultPayloads)\n }\n\n /** Restore derived indexes for a stored root without rewriting its body. */\n protected repairExistingPayloads(_payloads: WithStorageMeta<Payload>[]): Promisable<void> {\n return undefined\n }\n\n protected reportPayloadCount(): void {\n this._noOverride('reportPayloadCount')\n const gauge = this.payloadCountGauge\n if (gauge) {\n gauge.record(this.payloadCountHandler())\n }\n }\n\n protected snapshotHandler(): PromisableArray<ArchivistSnapshotPayload<WithStorageMeta<Payload>, Hash>> {\n throw new Error(NOT_IMPLEMENTED)\n }\n\n protected override async startHandler(): Promise<void> {\n if (this.config.getCache?.enabled === true) {\n this._getCache = new LRUCache({\n max: this.config.getCache?.maxEntries ?? 10_000,\n allowStale: true,\n noDisposeOnSet: false,\n updateAgeOnGet: true,\n })\n }\n const result = await super.startHandler()\n this.reportPayloadCount()\n return result\n }\n\n protected override async stateHandler(): Promise<Payload[]> {\n return [...await super.stateHandler(), await this.generateStats()]\n }\n\n /** Enforce backend admission before lookup, repair, insertion or parent writes. */\n protected validateInsertPayloads(_payloads: Payload[]): Promisable<void> {\n return undefined\n }\n\n /** Serialize local storage changes without holding a lock across callbacks or parents. */\n protected async withStorageMutation<T>(operation: () => Promise<T>): Promise<T> {\n return await operation()\n }\n\n protected async writeToParent(parent: ArchivistInstance, payloads: Payload[]): Promise<Payload[]> {\n if (payloads.length === 0) return []\n const sanitized = PayloadBuilder.omitStorageMeta(payloads)\n const hashes = [...new Set(await Promise.all(sanitized.map(payload => PayloadBuilder.hash(payload))))]\n const inserted = await this.exactRepresentations(await parent.insert(sanitized), hashes)\n const insertedHashes = new Set(inserted.map(payload => payload._hash))\n const missing = hashes.filter(hash => !insertedHashes.has(hash))\n const existing = missing.length > 0 ? await this.exactRepresentations(await parent.get(missing), missing) : []\n const acknowledged = new Set([...inserted, ...existing].map(payload => payload._hash))\n if (hashes.some(hash => !acknowledged.has(hash))) {\n throw new Error('Write parent did not acknowledge all requested payloads')\n }\n return [...inserted, ...existing]\n }\n\n protected async writeToParents(payloads: Payload[]): Promise<Payload[]> {\n const parents = await this.parentArchivists()\n const results = await Promise.all(\n Object.values(parents.write ?? {}).map(async (parent) => {\n return parent ? await this.writeToParent(parent, payloads) : undefined\n }),\n )\n return results.filter(exists).flat()\n }\n\n private async exactRepresentations(payloads: WithStorageMeta<Payload>[], hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n const requested = new Set(hashes)\n const found = new Map<Hash, WithStorageMeta<Payload>>()\n for (const payload of payloads) {\n await this.verifyPayloadIdentity(payload)\n if (requested.has(payload._hash)) found.set(payload._hash, payload)\n }\n return found.values().toArray()\n }\n\n private async requestedRepresentations(payloads: WithStorageMeta<Payload>[], hashes: Hash[]): Promise<WithStorageMeta<Payload>[]> {\n const requested = new Set(hashes)\n const result = new Map<Hash, WithStorageMeta<Payload>>()\n const sorted = payloads.toSorted(PayloadBuilder.compareStorageMeta)\n // Prefer actual stored roots (including their original sequence) before\n // constructing data-only views from a different client-metadata variant.\n for (const payload of sorted) {\n await this.verifyPayloadIdentity(payload)\n if (requested.has(payload._hash) && !result.has(payload._hash)) result.set(payload._hash, payload)\n }\n for (const payload of sorted) {\n if (!requested.has(payload._dataHash) || result.has(payload._dataHash)) {\n continue\n }\n\n const dataOnly = PayloadBuilder.omitClientMeta(payload) as WithStorageMeta<Payload>\n result.set(payload._dataHash, { ...dataOnly, _hash: payload._dataHash })\n }\n return result.values().toArray()\n }\n\n private async resolveArchivists(archivists: ModuleIdentifier[] = [], archivistInstances?: ArchivistInstance[]) {\n const resolvedArchivists = await Promise.all(archivists.map(archivist => this.resolve(archivist)))\n const archivistModules = resolvedArchivists.filter(exists).filter(duplicateModules)\n\n assertEx(\n !this.requireAllParents || (archivistModules.length === archivists.length),\n () =>\n `Failed to find some archivists for ${this.modName} (set allRequired to false if ok)]`,\n )\n\n const archivistInstancesMap: Record<XyoAddress, ArchivistInstance> = {}\n const resolvedInstances = archivistInstances ?? []\n for (const archivistInstance of resolvedInstances) {\n archivistInstancesMap[archivistInstance.address] = archivistInstance\n }\n\n for (const mod of archivistModules) {\n archivistInstancesMap[mod.address] = asArchivistInstance(mod, () => {\n isArchivistInstance(mod, { log: console })\n return `Unable to cast resolved module to an archivist: [${mod.address}, ${mod.modName}, ${mod.config.schema})}]`\n }, { required: true })\n }\n return archivistInstancesMap\n }\n\n private snapshotPayloads(payloads: Payload[]): Payload[] {\n // Payloads are JSON values. Capture their bytes before asynchronous work so\n // admission, identity computation and the backend see the same input.\n // JSON normalization is intentional; structuredClone preserves non-JSON values.\n // eslint-disable-next-line unicorn/prefer-structured-clone\n return JSON.parse(JSON.stringify(PayloadBuilder.omitStorageMeta(payloads))) as Payload[]\n }\n\n private async verifyPayloadIdentity(payload: WithStorageMeta<Payload>): Promise<void> {\n const canonicalPayload = PayloadBuilder.omitStorageMeta(payload)\n const [hash, dataHash] = await Promise.all([\n PayloadBuilder.hash(canonicalPayload), PayloadBuilder.dataHash(canonicalPayload),\n ])\n if (hash !== payload._hash || dataHash !== payload._dataHash) {\n throw new Error('Archivist returned payload with invalid hash metadata')\n }\n }\n\n private async withCacheMutation<T>(operation: () => Promise<T>): Promise<T> {\n this.activeCacheMutations++\n this.cacheGeneration++\n this._getCache?.clear()\n try {\n return await operation()\n } finally {\n // Even a failed mutation can have changed persistent state. In-flight reads\n // may finish, but their old generation must never repopulate the cache.\n this.activeCacheMutations--\n this.cacheGeneration++\n this._getCache?.clear()\n }\n }\n}\n", "import type {\n Payload, WithHashMeta, WithStorageMeta,\n} from '@xyo-network/sdk-protocol'\nimport { SequenceConstants, SequenceParser } from '@xyo-network/sdk-protocol'\nimport { Mutex } from 'async-mutex'\n\n// The nonce index of a sequence wraps at this many slots per epoch\nconst INDEXES_PER_EPOCH = 2 ** (SequenceConstants.nonceIndexBytes * 8)\n\n/**\n * Sequences the inserts of one archivist in the order they are written.\n *\n * A reader that follows an archivist by sequence cursor never looks back, so a\n * payload must not become visible after one with a higher sequence. Each batch\n * is therefore sequenced and written under one lock, and no sequence is lower\n * than one handed out before it.\n */\nexport class InsertSequencer {\n private epoch = 0\n private index = 0\n private readonly mutex = new Mutex()\n\n /** Sequence a batch in input order and write it before the next batch is sequenced. */\n async write<T>(\n payloads: WithHashMeta<Payload>[],\n write: (payloads: WithStorageMeta<Payload>[]) => Promise<T>,\n ): Promise<T> {\n return await this.mutex.runExclusive(async () => await write(this.sequence(payloads)))\n }\n\n /**\n * Reserve consecutive slots that sort after every slot reserved before. The\n * epoch is the wall clock. Within one millisecond, or while the clock is\n * behind the last epoch used, the nonce index keeps counting instead of\n * restarting, so the hash tail never decides the order of two inserts.\n */\n private reserve(count: number): { epoch: number; index: number } {\n const now = Date.now()\n if (now > this.epoch) {\n this.epoch = now\n this.index = 0\n } else if (this.index + count > INDEXES_PER_EPOCH) {\n this.epoch += 1\n this.index = 0\n }\n const index = this.index\n this.index += count\n return { epoch: this.epoch, index }\n }\n\n private sequence(payloads: WithHashMeta<Payload>[]): WithStorageMeta<Payload>[] {\n const { epoch, index } = this.reserve(payloads.length)\n return payloads.map((payload, offset) => ({\n ...payload,\n _sequence: SequenceParser.from(epoch, payload._hash, index + offset).localSequence,\n }))\n }\n}\n", "export const StorageClassLabel = 'network.xyo.storage.class'\nexport type StorageClassLabelValue = 'memory' | 'disk' | 'network' | 'proxy' | 'unknown'\n", "import type { Payload } from '@xyo-network/sdk-protocol'\nimport { PayloadBuilder } from '@xyo-network/sdk-protocol'\n\n/** Exact schema admission and limits on UTF-8 JSON bytes before compression. */\nexport interface PayloadAdmissionPolicy {\n /** An empty allowlist admits nothing. */\n allowedSchemas: string[]\n maxPayloadBytes: number\n /** Per-schema limits can only tighten the global limit. */\n schemaMaxPayloadBytes?: Record<string, number>\n}\n\nfunction validByteLimit(value: number): boolean {\n return Number.isSafeInteger(value) && value > 0\n}\n\nexport function validatePayloadAdmissionPolicy(policy: PayloadAdmissionPolicy): void {\n if (!Array.isArray(policy?.allowedSchemas)\n || policy.allowedSchemas.some(schema => typeof schema !== 'string' || schema.length === 0 || schema.trim() !== schema)\n || !validByteLimit(policy.maxPayloadBytes)) {\n throw new TypeError('Invalid payload admission policy')\n }\n if (policy.schemaMaxPayloadBytes === undefined) {\n return\n }\n\n if (policy.schemaMaxPayloadBytes === null || typeof policy.schemaMaxPayloadBytes !== 'object' || Array.isArray(policy.schemaMaxPayloadBytes)) {\n throw new TypeError('Invalid schema payload byte limits')\n }\n for (const [schema, limit] of Object.entries(policy.schemaMaxPayloadBytes)) {\n if (!policy.allowedSchemas.includes(schema) || !validByteLimit(limit)) {\n throw new TypeError('Invalid schema payload byte limits')\n }\n }\n}\n\n/** Reject the entire batch before any storage action if one payload is ineligible. */\nexport function validatePayloadAdmission(payloads: Payload[], policy: PayloadAdmissionPolicy): void {\n validatePayloadAdmissionPolicy(policy)\n const allowed = new Set(policy.allowedSchemas)\n for (const payload of payloads) {\n if (!allowed.has(payload.schema)) throw new Error('Payload schema is not admitted by this archivist')\n const schemaLimit = policy.schemaMaxPayloadBytes && Object.hasOwn(policy.schemaMaxPayloadBytes, payload.schema)\n ? policy.schemaMaxPayloadBytes[payload.schema]\n : policy.maxPayloadBytes\n const limit = Math.min(policy.maxPayloadBytes, schemaLimit)\n const json = JSON.stringify(PayloadBuilder.omitStorageMeta(payload))\n const textEncoder = new TextEncoder()\n if (textEncoder.encode(json).byteLength >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