@fireproof/core 0.19.8-dev-global → 0.19.8-dev-series-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 (64) hide show
  1. package/README.md +34 -0
  2. package/chunk-7EWIAXTM.js +7 -0
  3. package/chunk-7EWIAXTM.js.map +1 -0
  4. package/chunk-OFGPKRCM.js +290 -0
  5. package/chunk-OFGPKRCM.js.map +1 -0
  6. package/chunk-PB4BKL4O.js +7 -0
  7. package/chunk-PB4BKL4O.js.map +1 -0
  8. package/chunk-WS3YRPIA.js +75 -0
  9. package/chunk-WS3YRPIA.js.map +1 -0
  10. package/deno.json +22 -0
  11. package/gateway-5FCWPX5W.js +144 -0
  12. package/gateway-5FCWPX5W.js.map +1 -0
  13. package/{store-indexdb-WLRSICCB.js → gateway-H7UD6TNB.js} +49 -82
  14. package/gateway-H7UD6TNB.js.map +1 -0
  15. package/index.cjs +2365 -1875
  16. package/index.cjs.map +1 -1
  17. package/index.d.cts +663 -535
  18. package/index.d.ts +663 -535
  19. package/index.global.js +26742 -20717
  20. package/index.global.js.map +1 -1
  21. package/index.js +1691 -1094
  22. package/index.js.map +1 -1
  23. package/key-bag-file-WADZBHYG.js +54 -0
  24. package/key-bag-file-WADZBHYG.js.map +1 -0
  25. package/key-bag-indexdb-PGVAI3FJ.js +50 -0
  26. package/key-bag-indexdb-PGVAI3FJ.js.map +1 -0
  27. package/mem-filesystem-YPPJV7Q2.js +41 -0
  28. package/mem-filesystem-YPPJV7Q2.js.map +1 -0
  29. package/metafile-cjs.json +1 -1
  30. package/metafile-esm.json +1 -1
  31. package/metafile-iife.json +1 -1
  32. package/node-filesystem-INX4ZTHE.js +45 -0
  33. package/node-filesystem-INX4ZTHE.js.map +1 -0
  34. package/package.json +14 -8
  35. package/tests/blockstore/fragment-gateway.test.ts +107 -0
  36. package/tests/blockstore/keyed-crypto.test.ts +332 -0
  37. package/tests/blockstore/loader.test.ts +24 -19
  38. package/tests/blockstore/store.test.ts +51 -40
  39. package/tests/blockstore/transaction.test.ts +19 -15
  40. package/tests/fireproof/all-gateway.test.ts +394 -0
  41. package/tests/fireproof/cars/bafkreidxwt2nhvbl4fnqfw3ctlt6zbrir4kqwmjo5im6rf4q5si27kgo2i.car +0 -0
  42. package/tests/fireproof/cars/bafkreidxwt2nhvbl4fnqfw3ctlt6zbrir4kqwmjo5im6rf4q5si27kgo2i.ts +316 -0
  43. package/tests/fireproof/config.test.ts +94 -78
  44. package/tests/fireproof/crdt.test.ts +34 -28
  45. package/tests/fireproof/database.test.ts +22 -14
  46. package/tests/fireproof/fireproof.test.fixture.ts +133 -0
  47. package/tests/fireproof/fireproof.test.ts +331 -219
  48. package/tests/fireproof/hello.test.ts +34 -18
  49. package/tests/fireproof/indexer.test.ts +34 -27
  50. package/tests/fireproof/utils.test.ts +84 -0
  51. package/tests/helpers.ts +28 -57
  52. package/tests/www/todo-local.html +1 -1
  53. package/tests/www/todo.html +12 -15
  54. package/utils-QO2HIWGI.js +14 -0
  55. package/utils-QO2HIWGI.js.map +1 -0
  56. package/chunk-BNL4PVBF.js +0 -314
  57. package/chunk-BNL4PVBF.js.map +0 -1
  58. package/chunk-JW2QT6BF.js +0 -184
  59. package/chunk-JW2QT6BF.js.map +0 -1
  60. package/node-sys-container-MIEX6ELJ.js +0 -29
  61. package/node-sys-container-MIEX6ELJ.js.map +0 -1
  62. package/store-file-VJ6BI4II.js +0 -191
  63. package/store-file-VJ6BI4II.js.map +0 -1
  64. package/store-indexdb-WLRSICCB.js.map +0 -1
package/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types.ts","../../src/runtime/node-sys-container.ts","../../src/runtime/sys-container.ts","../../src/runtime/data-dir.ts","../../src/runtime/store-file-utils.ts","../../src/runtime/crypto.ts","../../src/runtime/files.ts","../../src/runtime/store-file-version.ts","../../src/runtime/store-indexdb-version.ts","../../src/runtime/index.ts","../../src/utils.ts","../../src/blockstore/gateway.ts","../../src/runtime/store-file.ts","../../src/runtime/store-indexdb.ts","../../src/index.ts","../../src/database.ts","../../src/write-queue.ts","../../src/crdt.ts","../../src/crdt-helpers.ts","../../src/blockstore/index.ts","../../src/blockstore/connection-base.ts","../../src/blockstore/task-manager.ts","../../src/blockstore/connect-rest.ts","../../src/blockstore/store-factory.ts","../../src/blockstore/store.ts","../../src/blockstore/loader.ts","../../src/blockstore/types.ts","../../src/blockstore/loader-helpers.ts","../../src/blockstore/encrypt-helpers.ts","../../src/blockstore/encrypt-codec.ts","../../src/blockstore/transaction.ts","../../src/blockstore/commit-queue.ts","../../src/indexer.ts","../../src/indexer-helpers.ts","../../src/crdt-clock.ts","../../src/apply-head-queue.ts","../../src/version.ts"],"sourcesContent":["import type { EventLink } from \"@web3-storage/pail/clock/api\";\nimport type { Operation } from \"@web3-storage/pail/crdt/api\";\n\nimport type { DbMeta, CryptoOpts, StoreOpts, AnyLink } from \"./blockstore/index.js\";\nimport { Logger } from \"@adviser/cement\";\n\nexport type Falsy = false | null | undefined;\n\nexport function isFalsy(value: unknown): value is Falsy {\n return value === false && value === null && value === undefined;\n}\n\nexport function throwFalsy<T>(value: T | Falsy): T {\n if (isFalsy(value)) {\n throw new Error(\"value is Falsy\");\n }\n return value;\n}\n\nexport function falsyToUndef<T>(value: T | Falsy): T | undefined {\n if (isFalsy(value)) {\n return undefined;\n }\n return value;\n}\n\nexport interface ConfigOpts {\n readonly public?: boolean;\n readonly meta?: DbMeta;\n readonly persistIndexes?: boolean;\n readonly autoCompact?: number;\n readonly crypto?: CryptoOpts;\n readonly store?: StoreOpts;\n // readonly indexStore?: StoreOpts;\n readonly threshold?: number;\n readonly logger?: Logger;\n}\n\nexport type ClockLink = EventLink<Operation>;\n\nexport type ClockHead = ClockLink[];\n\nexport type DocFragment = Uint8Array | string | number | boolean | null | AnyLink | DocFragment[] | object;\n// | { [key: string]: DocFragment };\n\nexport type DocLiteral = string | number | boolean | Uint8Array | unknown;\n\nexport type DocObject = NonNullable<unknown>;\nexport type DocTypes = DocObject;\n\nexport type DocRecord<T extends DocObject> = T;\n\nexport type UnknownDoc = DocRecord<never>;\n\nexport type DocFiles = Record<string, DocFileMeta | File>;\n\nexport interface DocBase {\n readonly _id: string;\n readonly _files?: DocFiles;\n readonly _publicFiles?: DocFiles;\n readonly _deleted?: boolean;\n}\n\nexport type DocWithId<T extends DocTypes> = DocBase & T;\n\nexport type DocSet<T extends DocTypes> = Partial<DocBase> & T;\n\nexport interface DocFileMeta {\n readonly type: string;\n readonly size: number;\n readonly cid: AnyLink;\n readonly car?: AnyLink;\n url?: string;\n file?: () => Promise<File>;\n}\n\nexport interface DocUpdate<T extends DocTypes> {\n readonly id: string;\n readonly value?: DocSet<T>;\n readonly del?: boolean;\n readonly clock?: ClockLink; // would be useful to give ClockLinks a type\n}\n\n// todo merge into above\nexport interface DocValue<T extends DocTypes> {\n readonly doc: DocWithId<T>;\n readonly del: boolean;\n readonly cid: AnyLink;\n}\n\nexport type KeyLiteral = string | number | boolean;\nexport type IndexKeyType = KeyLiteral | KeyLiteral[];\nexport type IndexKey<K extends IndexKeyType> = [K, string];\n\nexport interface IndexUpdate<K extends IndexKeyType> {\n readonly key: IndexKey<K>;\n readonly value?: DocFragment;\n readonly del?: boolean;\n}\n\nexport interface IndexUpdateString {\n readonly key: string;\n readonly value?: DocFragment;\n readonly del?: boolean;\n}\n\n// export interface IndexRowObject<K extends IndexKeyType, T extends DocObject> {\n// readonly id: string;\n// readonly key: K;\n// readonly value: T\n// // readonly row: T // DocFragment;\n// // readonly doc?: DocWithId<T>;\n// // value?: T;\n// // readonly del?: boolean;\n// }\n\n// export interface IndexRowLiteral<K extends IndexKeyType, T extends DocLiteral> {\n// readonly id: string;\n// readonly key: IndexKey<K>;\n// readonly value: T\n// }\n\n// export type IndexRow<K extends IndexKeyType, T extends DocTypes> =\n// T extends DocLiteral ? IndexRowLiteral<K, T> : IndexRowObject<K, T>\n\nexport interface IndexRow<K extends IndexKeyType, T extends DocObject, R extends DocFragment> {\n readonly id: string;\n readonly key: K; // IndexKey<K>;\n readonly value: R;\n readonly doc?: DocWithId<T>;\n}\n\nexport interface IndexRows<K extends IndexKeyType, T extends DocObject, R extends DocFragment = T> {\n readonly rows: IndexRow<K, T, R>[];\n}\nexport interface CRDTMeta {\n readonly head: ClockHead;\n}\n\nexport interface IndexTransactionMeta {\n readonly indexes: Record<string, IdxMeta>;\n}\n\nexport interface FileTransactionMeta {\n readonly files?: AnyLink[];\n}\n\nexport type MetaType = CRDTMeta | IndexTransactionMeta | FileTransactionMeta;\n\nexport interface IdxMeta {\n readonly byId: AnyLink;\n readonly byKey: AnyLink;\n readonly map: string;\n readonly name: string;\n readonly head: ClockHead;\n}\n\nexport interface IdxMetaMap {\n readonly indexes?: Map<string, IdxMeta>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface QueryOpts<K extends IndexKeyType> {\n readonly descending?: boolean;\n readonly limit?: number;\n includeDocs?: boolean;\n readonly range?: [IndexKeyType, IndexKeyType];\n readonly key?: DocFragment;\n readonly keys?: DocFragment[];\n prefix?: IndexKeyType;\n}\n\nexport interface AllDocsQueryOpts extends QueryOpts<string> {\n readonly key?: string;\n readonly keys?: string[];\n prefix?: string;\n}\n\nexport interface AllDocsResponse<T extends DocTypes> {\n readonly rows: {\n readonly key: string;\n readonly value: DocWithId<T>;\n }[];\n readonly clock: ClockHead;\n readonly name?: string;\n}\n\ntype EmitFn = (k: IndexKeyType, v?: DocFragment) => void;\nexport type MapFn<T extends DocTypes> = (doc: DocWithId<T>, emit: EmitFn) => DocFragment | unknown;\n\nexport interface ChangesOptions {\n readonly dirty?: boolean;\n readonly limit?: number;\n}\n\nexport interface ChangesResponseRow<T extends DocTypes> {\n readonly key: string;\n readonly value: DocWithId<T>;\n readonly clock?: ClockLink;\n}\n\nexport interface ChangesResponse<T extends DocTypes> {\n readonly clock: ClockHead;\n readonly rows: ChangesResponseRow<T>[];\n readonly name?: string;\n}\n\nexport interface DocResponse {\n readonly id: string;\n readonly clock: ClockHead;\n readonly name?: string;\n}\n\nexport type UpdateListenerFn<T extends DocTypes> = (docs: DocWithId<T>[]) => Promise<void> | void;\nexport type NoUpdateListenerFn = () => Promise<void> | void;\nexport type ListenerFn<T extends DocTypes> = UpdateListenerFn<T> | NoUpdateListenerFn;\n","import { type NodeMap, join } from \"./sys-container.js\";\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport * as os from \"os\";\nimport * as url from \"url\";\n\nexport async function createNodeSysContainer(): Promise<NodeMap> {\n // const nodePath = \"node:path\";\n // const nodeOS = \"node:os\";\n // const nodeURL = \"node:url\";\n // const nodeFS = \"node:fs\";\n // const fs = (await import(\"node:fs\")).promises;\n // const assert = \"assert\";\n // const path = await import(\"node:path\");\n return {\n state: \"node\",\n ...path,\n // ...(await import(\"node:os\")),\n // ...(await import(\"node:url\")),\n ...os,\n ...url,\n ...fs,\n join,\n stat: fs.stat as NodeMap[\"stat\"],\n readdir: fs.readdir as NodeMap[\"readdir\"],\n readfile: fs.readFile as NodeMap[\"readfile\"],\n writefile: fs.writeFile as NodeMap[\"writefile\"],\n };\n}\n","import type { Dirent, MakeDirectoryOptions, ObjectEncodingOptions, PathLike, Stats } from \"fs\";\n\nimport { uuidv4 } from \"uuidv7\";\nimport { ResolveOnce, EnvImpl } from \"@adviser/cement\";\n\nimport { throwFalsy } from \"../types.js\";\n\nexport interface Runtime {\n isNodeIsh: boolean;\n isBrowser: boolean;\n isDeno: boolean;\n isReactNative: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isSet(value: string, ref: any = globalThis): boolean {\n const [head, ...tail] = value.split(\".\");\n // console.log(`isSet: ${head} -> ${tail.join(\".\")} -> ${ref}`);\n if ([\"object\", \"function\"].includes(typeof ref) && ref && [\"object\", \"function\"].includes(typeof ref[head]) && ref[head]) {\n if (tail.length <= 1) {\n // console.log(`isSet: ${value} -> TRUE`);\n return true;\n }\n return isSet(tail.join(\".\"), ref[head]);\n }\n // console.log(`isSet: ${value} -> FALSE`);\n return false;\n}\n\nfunction runtimeFn(): Runtime {\n // console.log(`runtimeFn`);\n const isNodeIsh = isSet(\"process.versions.node\");\n const isDeno = isSet(\"Deno\");\n return {\n isNodeIsh,\n isBrowser: !(isNodeIsh || isDeno),\n isDeno,\n isReactNative: false,\n };\n}\nexport interface NodeMap {\n state: \"seeded\" | \"browser\" | \"node\";\n join: (...args: string[]) => string;\n dirname: (path: string) => string;\n homedir: () => string;\n fileURLToPath: (url: string | URL) => string;\n // assert: (condition: unknown, message?: string | Error) => void;\n\n mkdir: (path: PathLike, options?: { recursive: boolean }) => Promise<string | undefined>;\n readdir: (path: PathLike, options?: unknown) => Promise<unknown[]>;\n\n rm: (path: PathLike, options?: MakeDirectoryOptions & { recursive: boolean }) => Promise<void>;\n copyFile: (source: PathLike, destination: PathLike) => Promise<void>;\n\n readfile: (path: PathLike, options?: { encoding: BufferEncoding; flag?: string }) => Promise<string>;\n\n stat: (path: PathLike) => Promise<Stats>;\n\n unlink: (path: PathLike) => Promise<void>;\n writefile: (path: PathLike, data: Uint8Array | string) => Promise<void>;\n}\n\n// export function assert(condition: unknown, message?: string | Error): asserts condition {\n// SysContainer.freight?.assert(condition, message);\n// }\n\nconst onceStart = new ResolveOnce<void>();\n\nexport function join(...paths: string[]): string {\n return paths.map((i) => i.replace(/\\/+$/, \"\")).join(\"/\");\n}\n\nconst envImpl = new EnvImpl({\n symbol: \"FP_ENV\",\n presetEnv: new Map([\n // [\"FP_DEBUG\", \"xxx\"],\n // [\"FP_ENV\", \"development\"],\n ]),\n});\n// console.log(`EnvImpl`, envImpl);\n\nclass sysContainer {\n freight: NodeMap = {\n state: \"seeded\",\n join,\n dirname: (path: string) => path.split(\"/\").slice(0, -1).join(\"/\"),\n homedir: () => {\n throw new Error(\"SysContainer:homedir is not available in seeded state\");\n },\n fileURLToPath: (strurl: string | URL) => {\n let url: URL;\n if (typeof strurl === \"string\") {\n url = new URL(strurl);\n } else {\n url = strurl;\n }\n return url.pathname;\n },\n // assert: (condition: unknown, message?: string | Error) => {\n // if (!condition) {\n // if (message instanceof Error) {\n // throw message;\n // } else {\n // throw new Error(message);\n // }\n // }\n // },\n mkdir: () => Promise.reject(new Error(\"SysContainer:mkdir is not available in seeded state\")),\n readdir: () => Promise.reject(new Error(\"SysContainer:readdir is not available in seeded state\")),\n rm: () => Promise.reject(new Error(\"SysContainer:rm is not available in seeded state\")),\n copyFile: () => Promise.reject(new Error(\"SysContainer:copyFile is not available in seeded state\")),\n readfile: () => Promise.reject(new Error(\"SysContainer:readfile is not available in seeded state\")),\n unlink: () => Promise.reject(new Error(\"SysContainer:unlink is not available in seeded state\")),\n writefile: () => Promise.reject(new Error(\"SysContainer:writefile is not available in seeded state\")),\n stat: () => Promise.reject(new Error(\"SysContainer:stat is not available in seeded state\")),\n };\n\n readonly id = uuidv4();\n\n async start(): Promise<void> {\n await onceStart.once(async () => {\n switch (this.freight.state) {\n case \"seeded\":\n if (this.runtime().isNodeIsh) {\n const { createNodeSysContainer } = await import(\"./node-sys-container.js\");\n // console.log(\"use NodeSysContainer\");\n this.freight = await createNodeSysContainer();\n } else {\n // console.log(\"use BrowserSysContainer\");\n this.freight.state = \"browser\";\n }\n return;\n case \"browser\":\n case \"node\":\n return;\n }\n });\n }\n\n async readdir(\n path: PathLike,\n options?:\n | (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean })\n | BufferEncoding\n | null\n | undefined,\n ) {\n this.logSeeded(\"readdir\");\n return (throwFalsy(this.freight).readdir(path, options) as Promise<string[]>) || [];\n }\n async readdirent(\n path: PathLike,\n options: (ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean }) | BufferEncoding | null | undefined,\n ): Promise<Dirent[]> {\n this.logSeeded(\"readdirent\");\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (throwFalsy(this.freight).readdir(path, { ...(options as any), withFileTypes: true }) as Promise<Dirent[]>) || [];\n }\n\n async readfile(path: PathLike, options?: { encoding: BufferEncoding; flag?: string }) {\n this.logSeeded(\"readfile\");\n return throwFalsy(this.freight).readfile(path, options) as unknown as Promise<Buffer>;\n }\n\n async mkdir(path: PathLike, options: { recursive: boolean }) {\n this.logSeeded(\"mkdir\");\n return throwFalsy(this.freight).mkdir(path, options);\n }\n\n async rm(path: PathLike, options: MakeDirectoryOptions & { recursive: boolean }) {\n this.logSeeded(\"rm\");\n return throwFalsy(this.freight).rm(path, options);\n }\n\n async unlink(path: PathLike) {\n this.logSeeded(\"unlink\");\n return throwFalsy(this.freight).unlink(path);\n }\n\n async writefile(path: PathLike, data: Uint8Array | string) {\n this.logSeeded(\"writefile\");\n return throwFalsy(this.freight).writefile(path, data);\n }\n\n async copyFile(source: PathLike, destination: PathLike) {\n this.logSeeded(\"copyFile\");\n return throwFalsy(this.freight).copyFile(source, destination);\n }\n\n async stat(path: PathLike) {\n this.logSeeded(\"stat\");\n return throwFalsy(this.freight).stat(path);\n }\n\n fileURLToPath(url: string | URL) {\n this.logSeeded(\"fileURLToPath\");\n return throwFalsy(this.freight).fileURLToPath(url);\n }\n\n dirname(path: string) {\n this.logSeeded(\"dirname\");\n return throwFalsy(this.freight).dirname(path);\n }\n\n join(...args: string[]): string {\n this.logSeeded(\"join\");\n return throwFalsy(this.freight).join(...args);\n }\n\n homedir = () => {\n this.logSeeded(\"homedir\");\n return throwFalsy(this.freight).homedir();\n };\n\n logSeeded(method: string) {\n if (this.freight.state === \"seeded\") {\n const err = new Error();\n console.warn(`SysContainer.${method} is not available in seeded state:`, err.stack);\n }\n }\n\n readonly runtime = runtimeFn;\n readonly env = envImpl;\n}\n\n// // eslint-disable-next-line @typescript-eslint/no-explicit-any\n// export async function saveImport(fName: string): Promise<any> {\n// try {\n// const i = await import(fName);\n// return i;\n// } catch (e: unknown) {\n// console.error(`saveImport failed for ${fName} with`, e);\n// throw e;\n// }\n// }\n\nexport const SysContainer = new sysContainer();\n","import { SysContainer } from \"./sys-container.js\";\n\nexport function dataDir(name?: string, base?: string | URL): string {\n if (!base) {\n if (SysContainer.runtime().isNodeIsh || SysContainer.runtime().isDeno) {\n base = SysContainer.env.get(\"FP_STORAGE_URL\") || `file://${SysContainer.join(SysContainer.homedir(), \".fireproof\")}`;\n } else {\n base = `indexdb://fp`;\n }\n }\n let url: URL;\n if (typeof base === \"string\") {\n try {\n url = new URL(base.toString());\n } catch (e) {\n try {\n base = `file://${base}`;\n url = new URL(base);\n } catch (e) {\n throw new Error(`invalid base url: ${base}`);\n }\n }\n } else {\n url = base;\n }\n url.searchParams.set(\"name\", name || \"\");\n return url.toString();\n}\n","import { Logger, getStore } from \"../utils.js\";\nimport { SysContainer } from \"./sys-container.js\";\n\nexport async function getPath(url: URL, logger: Logger): Promise<string> {\n const basePath = url\n .toString()\n .replace(new RegExp(`^${url.protocol}//`), \"\")\n .replace(/\\?.*$/, \"\");\n const name = url.searchParams.get(\"name\");\n if (name) {\n const version = url.searchParams.get(\"version\");\n if (!version) throw logger.Error().Str(\"url\", url.toString()).Msg(`version not found`).AsError();\n return SysContainer.join(basePath, version, name);\n }\n return SysContainer.join(basePath);\n}\n\nexport function getFileName(url: URL, key: string, logger: Logger): string {\n switch (getStore(url, logger, (...a: string[]) => a.join(\"/\"))) {\n case \"data\":\n return key + \".car\";\n case \"meta\":\n return key + \".json\";\n default:\n throw logger.Error().Str(\"url\", url.toString()).Msg(`unsupported store type`).AsError();\n }\n}\n\nexport function ensureIndexName(url: URL, name: string): string {\n if (url.searchParams.has(\"index\")) {\n name = (url.searchParams.get(\"index\")?.replace(/[^a-zA-Z0-9]/g, \"\") || \"idx\") + \"-\" + name;\n }\n return name;\n}\n","import { CryptoOpts } from \"../blockstore/index.js\";\n\nfunction randomBytes(size: number) {\n const bytes = new Uint8Array(size);\n if (size > 0) {\n crypto.getRandomValues(bytes);\n }\n return bytes;\n}\n\nfunction digestSHA256(data: Uint8Array): Promise<ArrayBuffer> {\n return Promise.resolve(crypto.subtle.digest(\"SHA-256\", data));\n}\n\nexport function toCryptoOpts(cryptoOpts: Partial<CryptoOpts> = {}): CryptoOpts {\n const opts = {\n importKey: cryptoOpts.importKey || crypto.subtle.importKey.bind(crypto.subtle),\n encrypt: cryptoOpts.encrypt || crypto.subtle.encrypt.bind(crypto.subtle),\n decrypt: cryptoOpts.decrypt || crypto.subtle.decrypt.bind(crypto.subtle),\n randomBytes: cryptoOpts.randomBytes || randomBytes,\n digestSHA256: cryptoOpts.digestSHA256 || digestSHA256,\n };\n // console.log(\"cryptoOpts\", cryptoOpts, opts)\n return opts;\n}\n","import * as UnixFS from \"@ipld/unixfs\";\nimport * as raw from \"multiformats/codecs/raw\";\nimport { withMaxChunkSize } from \"@ipld/unixfs/file/chunker/fixed\";\nimport { withWidth } from \"@ipld/unixfs/file/layout/balanced\";\n\nimport type { View } from \"@ipld/unixfs\";\nimport { DocFileMeta } from \"../types.js\";\n\nimport { exporter, ReadableStorage } from \"ipfs-unixfs-exporter\";\nimport { BlobLike, AnyLink, AnyBlock } from \"../blockstore/index.js\";\n\nconst queuingStrategy = UnixFS.withCapacity();\n\nconst settings = UnixFS.configure({\n fileChunkEncoder: raw,\n smallFileEncoder: raw,\n chunker: withMaxChunkSize(1024 * 1024),\n fileLayout: withWidth(1024),\n});\n\nasync function collect<T>(collectable: ReadableStream<T>): Promise<T[]> {\n const chunks: T[] = [];\n await collectable.pipeTo(\n new WritableStream({\n write(chunk) {\n chunks.push(chunk);\n },\n }),\n );\n return chunks;\n}\n\nexport async function encodeFile(blob: BlobLike): Promise<{ cid: AnyLink; blocks: AnyBlock[] }> {\n const readable = createFileEncoderStream(blob);\n const blocks = await collect(readable);\n return { cid: blocks.at(-1).cid, blocks };\n}\n\nexport async function decodeFile(blocks: unknown, cid: AnyLink, meta: DocFileMeta): Promise<File> {\n const entry = await exporter(cid.toString(), blocks as ReadableStorage, { length: meta.size });\n const chunks = [];\n for await (const chunk of entry.content()) {\n chunks.push(chunk);\n }\n return new File(chunks, entry.name, { type: meta.type, lastModified: 0 });\n}\n\nfunction createFileEncoderStream(blob: BlobLike) {\n const { readable, writable } = new TransformStream({}, queuingStrategy);\n const unixfsWriter = UnixFS.createWriter({ writable, settings });\n const fileBuilder = new UnixFSFileBuilder(\"\", blob);\n void (async () => {\n await fileBuilder.finalize(unixfsWriter);\n await unixfsWriter.close();\n })();\n return readable;\n}\n\nclass UnixFSFileBuilder {\n #file;\n readonly name: string;\n constructor(name: string, file: BlobLike) {\n this.name = name;\n this.#file = file;\n }\n\n async finalize(writer: View) {\n const unixfsFileWriter = UnixFS.createFileWriter(writer);\n await this.#file.stream().pipeTo(\n new WritableStream({\n async write(chunk) {\n await unixfsFileWriter.write(chunk as Uint8Array);\n },\n }),\n );\n return await unixfsFileWriter.close();\n }\n}\n","export const FILESTORE_VERSION = \"v0.19-file\";\n","export const INDEXDB_VERSION = \"v0.19-indexdb\";\n","export * from \"./sys-container.js\";\nexport * from \"./data-dir.js\";\nexport * from \"./store-file-utils.js\";\n\n// export * as sql from \"./store-sql/index.js\";\nexport * as crypto from \"./crypto.js\";\nexport * as files from \"./files.js\";\n\nexport { FILESTORE_VERSION } from \"./store-file-version.js\";\nexport { INDEXDB_VERSION } from \"./store-indexdb-version.js\";\n// export { V0_19SQL_VERSION } from \"./store-sql/v0.19/version.js\";\n","import { Logger, LoggerImpl, IsLogger, Result, ResolveOnce } from \"@adviser/cement\";\nimport { SysContainer } from \"./runtime\";\nimport { uuidv7 } from \"uuidv7\";\n\nexport type { Logger };\nexport { Result };\n\nconst globalLogger: Logger = new LoggerImpl();\n\nexport interface LoggerOpts {\n readonly logger?: Logger;\n}\n\nconst registerFP_DEBUG = new ResolveOnce();\n\nexport function ensureLogger(\n optsOrLogger: Partial<LoggerOpts> | Logger,\n componentName: string,\n ctx?: Record<string, unknown>,\n): Logger {\n // if (!opts?.logger) {\n // throw new Error(\"logger is required\");\n // }\n let logger = globalLogger;\n if (IsLogger(optsOrLogger)) {\n logger = optsOrLogger;\n } else if (optsOrLogger && IsLogger(optsOrLogger.logger)) {\n logger = optsOrLogger.logger;\n }\n const cLogger = logger.With().Module(componentName); //.Str(\"this\", uuidv7());\n const debug: string[] = [];\n if (ctx) {\n if (\"debug\" in ctx) {\n if (typeof ctx.debug === \"string\" && ctx.debug.length > 0) {\n debug.push(ctx.debug);\n } else {\n debug.push(componentName);\n }\n delete ctx.debug;\n }\n if (\"this\" in ctx) {\n cLogger.Str(\"this\", uuidv7());\n delete ctx.this;\n }\n for (const [key, value] of Object.entries(ctx)) {\n switch (typeof value) {\n case \"string\":\n cLogger.Str(key, value);\n break;\n case \"number\":\n cLogger.Uint64(key, value);\n break;\n default:\n if (value instanceof Date) {\n cLogger.Str(key, value.toISOString());\n } else if (value instanceof URL) {\n cLogger.Str(key, value.toString());\n } else if (typeof value === \"function\") {\n cLogger.Ref(key, value);\n } else {\n cLogger.Any(key, value);\n }\n break;\n }\n }\n }\n registerFP_DEBUG\n .once(async () => {\n // console.log(\"registerFP_DEBUG\", SysContainer.env)\n SysContainer.env.onSet((key, value) => {\n // console.log(\"FP_DEBUG\", key, value, debug)\n if (value) {\n logger.SetDebug(value);\n }\n }, \"FP_DEBUG\");\n })\n .finally(() => {\n /* do nothing */\n });\n\n if (debug.length > 0) {\n logger.SetDebug(debug);\n }\n const out = cLogger.Logger();\n // out.Debug().Msg(\"logger ready\");\n return out;\n}\n\nexport type Joiner = (...toJoin: string[]) => string;\n\nexport function getStore(url: URL, logger: Logger, joiner: Joiner): string {\n let result = url.searchParams.get(\"store\");\n if (!result) throw logger.Error().Str(\"url\", url.toString()).Msg(`store not found`).AsError();\n if (url.searchParams.has(\"index\")) {\n result = joiner(url.searchParams.get(\"index\") || \"idx\", result);\n }\n return result;\n}\n\nexport function getKey(url: URL, logger: Logger): string {\n const result = url.searchParams.get(\"key\");\n if (!result) throw logger.Error().Str(\"url\", url.toString()).Msg(`key not found`).AsError();\n return result;\n}\n\nexport function getName(url: URL, logger: Logger): string {\n let result = url.searchParams.get(\"name\");\n if (!result) {\n result = SysContainer.dirname(url.pathname);\n if (result.length === 0) {\n throw logger.Error().Str(\"url\", url.toString()).Msg(`name not found`).AsError();\n }\n }\n return result;\n}\n\nexport function exception2Result<T = void>(fn: () => Promise<T>): Promise<Result<T>> {\n return fn()\n .then((value) => Result.Ok(value))\n .catch((e) => Result.Err(e));\n}\n\nexport async function exceptionWrapper<T, E extends Error>(fn: () => Promise<Result<T, E>>): Promise<Result<T, E>> {\n return fn().catch((e) => Result.Err(e));\n}\n","import { Result } from \"@adviser/cement\";\n\nexport interface GatewayOpts {\n readonly gateway: Gateway;\n}\n\nexport class NotFoundError extends Error {\n readonly code = \"ENOENT\";\n}\n\nexport function isNotFoundError(e: Error | Result<unknown> | unknown): e is NotFoundError {\n if (Result.Is(e)) {\n if (e.isOk()) return false;\n e = e.Err();\n }\n if ((e as NotFoundError).code === \"ENOENT\") return true;\n return false;\n}\n\nexport type GetResult = Result<Uint8Array, NotFoundError | Error>;\nexport type VoidResult = Result<void>;\n\nexport interface Gateway {\n // all the methods never throw!\n // an error is reported as a Result\n buildUrl(baseUrl: URL, key: string): Promise<Result<URL>>;\n // start updates URL --> hate this side effect\n start(baseUrl: URL): Promise<VoidResult>;\n close(baseUrl: URL): Promise<VoidResult>;\n destroy(baseUrl: URL): Promise<VoidResult>;\n put(url: URL, body: Uint8Array): Promise<VoidResult>;\n // get could return a NotFoundError if the key is not found\n get(url: URL): Promise<GetResult>;\n delete(url: URL): Promise<VoidResult>;\n}\n","import { SysContainer } from \"./sys-container.js\";\nimport { TestStore } from \"../blockstore/types.js\";\nimport { FILESTORE_VERSION } from \"./store-file-version.js\";\nimport { Logger, ResolveOnce, Result } from \"@adviser/cement\";\nimport { ensureLogger, exception2Result, exceptionWrapper, getStore } from \"../utils.js\";\nimport { Gateway, GetResult, isNotFoundError, NotFoundError } from \"../blockstore/gateway.js\";\nimport { ensureIndexName, getFileName, getPath } from \"./store-file-utils.js\";\n\nconst versionFiles = new Map<string, ResolveOnce<void>>();\nasync function ensureVersionFile(path: string, logger: Logger): Promise<string> {\n let once = versionFiles.get(path);\n if (!once) {\n once = new ResolveOnce<void>();\n versionFiles.set(path, once);\n }\n await once.once(async () => {\n await SysContainer.mkdir(path, { recursive: true });\n const vFile = SysContainer.join(path, \"version\");\n const vFileStat = await SysContainer.stat(vFile).catch(() => undefined);\n if (!vFileStat) {\n await SysContainer.writefile(SysContainer.join(path, \"version\"), FILESTORE_VERSION);\n return;\n } else if (!vFileStat.isFile()) {\n throw logger.Error().Str(\"file\", vFile).Msg(`version file is a directory`).AsError();\n }\n const v = await SysContainer.readfile(vFile);\n if (v.toString() !== FILESTORE_VERSION) {\n console.warn(`version mismatch:${vFile}: ${v.toString()}!=${FILESTORE_VERSION}`);\n }\n });\n return path;\n}\n\nabstract class FileGateway implements Gateway {\n readonly logger: Logger;\n constructor(logger: Logger) {\n this.logger = logger;\n }\n start(baseURL: URL): Promise<Result<void>> {\n return exception2Result(async () => {\n await SysContainer.start();\n baseURL.searchParams.set(\"version\", baseURL.searchParams.get(\"version\") || FILESTORE_VERSION);\n const url = await this.buildUrl(baseURL, \"dummy\");\n if (url.isErr()) return url;\n const dbdir = this.getFilePath(url.Ok());\n // remove dummy\n await SysContainer.mkdir(SysContainer.dirname(dbdir), { recursive: true });\n const dbroot = SysContainer.dirname(dbdir);\n this.logger.Debug().Str(\"url\", url.Ok().toString()).Str(\"dbroot\", SysContainer.dirname(dbroot)).Msg(\"start\");\n await ensureVersionFile(dbroot, this.logger);\n });\n }\n async close(): Promise<Result<void>> {\n return Result.Ok(undefined);\n }\n abstract destroy(baseUrl: URL): Promise<Result<void>>;\n abstract buildUrl(baseUrl: URL, key: string): Promise<Result<URL>>;\n\n getFilePath(url: URL): string {\n const path = url\n .toString()\n .replace(/^file:\\/\\//, \"\")\n .replace(/\\?.*$/, \"\");\n this.logger.Debug().Str(\"url\", url.toString()).Str(\"path\", path).Msg(\"getFilePath\");\n return path;\n }\n\n async put(url: URL, body: Uint8Array): Promise<Result<void>> {\n return exception2Result(async () => {\n const file = this.getFilePath(url);\n this.logger.Debug().Str(\"url\", url.toString()).Str(\"file\", file).Msg(\"put\");\n await SysContainer.writefile(file, body);\n });\n }\n async get(url: URL): Promise<GetResult> {\n return exceptionWrapper(async () => {\n const file = this.getFilePath(url);\n try {\n const res = await SysContainer.readfile(file);\n this.logger.Debug().Url(url).Str(\"file\", file).Msg(\"get\");\n return Result.Ok(new Uint8Array(res));\n } catch (e: unknown) {\n // this.logger.Error().Err(e).Str(\"file\", file).Msg(\"get\");\n if (isNotFoundError(e)) {\n return Result.Err(new NotFoundError(`file not found: ${file}`));\n }\n return Result.Err(e as Error);\n }\n });\n }\n async delete(url: URL): Promise<Result<void>> {\n return exception2Result(async () => {\n await SysContainer.unlink(this.getFilePath(url));\n });\n }\n\n async destroyDir(baseURL: URL): Promise<Result<void>> {\n const url = await this.buildUrl(baseURL, \"x\");\n if (url.isErr()) return url;\n const filepath = SysContainer.dirname(this.getFilePath(url.Ok()));\n let dir: string[] = [];\n try {\n dir = await SysContainer.readdir(filepath);\n } catch (e: unknown) {\n if (!isNotFoundError(e)) {\n throw this.logger.Error().Err(e).Str(\"dir\", filepath).Msg(\"destroy:readdir\").AsError();\n }\n }\n for (const file of dir) {\n const pathed = SysContainer.join(filepath, file);\n try {\n await SysContainer.unlink(pathed);\n } catch (e: unknown) {\n if (!isNotFoundError(e)) {\n throw this.logger.Error().Err(e).Str(\"file\", pathed).Msg(\"destroy:unlink\").AsError();\n }\n }\n }\n return Result.Ok(undefined);\n }\n}\n\nexport class FileWALGateway extends FileGateway {\n constructor(logger: Logger) {\n super(ensureLogger(logger, \"FileWALGateway\"));\n }\n\n async destroy(baseURL: URL): Promise<Result<void>> {\n return this.destroyDir(baseURL);\n }\n async buildUrl(baseUrl: URL, key: string): Promise<Result<URL>> {\n const url = new URL(baseUrl.toString());\n url.pathname = SysContainer.join(await getPath(baseUrl, this.logger), ensureIndexName(baseUrl, \"wal\"), key + \".json\");\n return Result.Ok(url);\n }\n}\n\nexport class FileMetaGateway extends FileGateway {\n constructor(logger: Logger) {\n super(ensureLogger(logger, \"FileMetaGateway\"));\n }\n\n async destroy(baseURL: URL): Promise<Result<void>> {\n return this.destroyDir(baseURL);\n }\n async buildUrl(baseUrl: URL, key: string): Promise<Result<URL>> {\n const url = new URL(baseUrl.toString());\n url.pathname = SysContainer.join(await getPath(baseUrl, this.logger), ensureIndexName(baseUrl, \"meta\"), key + \".json\");\n return Result.Ok(url);\n }\n}\n\nexport class FileDataGateway extends FileGateway {\n readonly branches = new Set<string>();\n constructor(logger: Logger) {\n // console.log(\"FileDataGateway->\", logger);\n super(ensureLogger(logger, \"FileDataGateway\"));\n }\n\n async destroy(baseURL: URL): Promise<Result<void>> {\n return this.destroyDir(baseURL);\n }\n async buildUrl(baseUrl: URL, key: string): Promise<Result<URL>> {\n const url = new URL(baseUrl.toString());\n url.pathname = SysContainer.join(await getPath(baseUrl, this.logger), ensureIndexName(baseUrl, \"data\"), key + \".car\");\n return Result.Ok(url);\n }\n}\n\nfunction toArrayBuffer(buffer: Buffer) {\n const ab = new ArrayBuffer(buffer.length);\n const view = new Uint8Array(ab);\n for (let i = 0; i < buffer.length; ++i) {\n view[i] = buffer[i];\n }\n return view;\n}\n\nexport class FileTestStore implements TestStore {\n readonly logger: Logger;\n constructor(\n // readonly url: URL,\n logger: Logger,\n ) {\n this.logger = ensureLogger(logger, \"FileTestStore\");\n }\n\n async get(url: URL, key: string) {\n const logger = ensureLogger(this.logger, \"get\", { url: url.toString(), key });\n const dbFile = SysContainer.join(\n await getPath(url, this.logger),\n getStore(url, this.logger, SysContainer.join),\n getFileName(url, key, this.logger),\n );\n logger.Debug().Str(\"dbFile\", dbFile).Msg(\"get\");\n const buffer = await SysContainer.readfile(dbFile);\n logger.Debug().Str(\"dbFile\", dbFile).Len(buffer).Msg(\"got\");\n return toArrayBuffer(buffer);\n }\n}\n","import { openDB, IDBPDatabase } from \"idb\";\nimport { KeyedResolvOnce, Logger, Result } from \"@adviser/cement\";\n\nimport { TestStore } from \"../blockstore/types.js\";\nimport { INDEXDB_VERSION } from \"./store-indexdb-version.js\";\nimport { ensureLogger, exception2Result, exceptionWrapper, getKey, getStore } from \"../utils.js\";\nimport { Gateway, NotFoundError } from \"../blockstore/gateway.js\";\nimport { SysContainer } from \"./sys-container.js\";\n\nfunction ensureVersion(url: URL): URL {\n const ret = new URL(url.toString());\n ret.searchParams.set(\"version\", url.searchParams.get(\"version\") || INDEXDB_VERSION);\n return ret;\n}\n\nconst onceIndexDB = new KeyedResolvOnce<{\n readonly db: IDBPDatabase<unknown>;\n readonly dbName: DbName;\n readonly version: string;\n}>();\n\nfunction sanitzeKey(key: string | string[]): string | string[] {\n if (key.length === 1) {\n key = key[0];\n }\n return key;\n}\n\nasync function connectIdb(url: URL, logger: Logger): Promise<IDBPDatabase<unknown>> {\n const dbName = getIndexDBName(url, logger); // `fp.${this.STORAGE_VERSION}.${this.name}`;\n // const urlStr = url.toString().replace(/\\?.*$/, \"\");\n // console.log(`get:${this.id}`);\n // console.log(`connectIdb:pre:`, dbName, url.toString());\n const once = await onceIndexDB.get(dbName.fullDb).once(async () => {\n // console.log(`connectIdb:once:`, dbName, url.toString());\n const db = await openDB(dbName.fullDb, 1, {\n upgrade(db) {\n // console.log('upgrade:', dbName);\n [\"version\", \"data\", \"wal\", \"meta\", \"idx.data\", \"idx.wal\", \"idx.meta\"].map((store) => {\n db.createObjectStore(store, {\n autoIncrement: false,\n });\n });\n },\n });\n const found = await db.get(\"version\", \"version\");\n const version = url.searchParams.get(\"version\") || INDEXDB_VERSION;\n if (!found) {\n await db.put(\"version\", { version }, \"version\");\n } else if (found.version !== version) {\n logger\n .Warn()\n .Str(\"url\", url.toString())\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n .Str(\"version\", version!)\n .Str(\"found\", found.version)\n .Msg(\"version mismatch\");\n }\n return { db, dbName, version };\n });\n url.searchParams.set(\"version\", once.version);\n return once.db;\n}\n\nexport interface DbName {\n readonly fullDb: string;\n readonly objStore: string;\n readonly connectionKey: string;\n // readonly version: number;\n // readonly type: \"data\" | \"meta\" | \"wal\";\n readonly dbName: string;\n}\n\nfunction joinDBName(...names: string[]): string {\n return names\n .map((i) => i.replace(/^[^a-zA-Z0-9]+/g, \"\").replace(/[^a-zA-Z0-9]+/g, \"_\"))\n .filter((i) => i.length)\n .join(\".\");\n}\n\n// const schemaVersion = new Map<string, number>();\nexport function getIndexDBName(iurl: URL, logger: Logger): DbName {\n const url = ensureVersion(iurl);\n const fullDb = url.pathname.replace(/^\\/+/, \"\").replace(/\\?.*$/, \"\"); // cut leading slashes\n // const type = getStore(url);\n // const storageVersion = url.searchParams.get(\"version\");\n // not nice but we need to pass the version to the db name\n // url.searchParams.set(\"version\", storageVersion);\n // console.log(\"getIndexDBName:\", url.toString(), { fullDb, type, branch });\n // const dbName = fullDb.replace(new RegExp(`^fp.${storageVersion}.`), \"\"); // cut fp prefix\n const dbName = url.searchParams.get(\"name\");\n if (!dbName) throw logger.Error().Str(\"url\", url.toString()).Msg(`name not found`).AsError();\n const result = joinDBName(fullDb, dbName);\n const objStore = getStore(url, logger, joinDBName);\n const connectionKey = [result, objStore].join(\":\");\n return {\n fullDb: result,\n objStore,\n connectionKey,\n dbName,\n };\n}\n\nabstract class IndexDBGateway implements Gateway {\n readonly logger: Logger;\n constructor(logger: Logger) {\n this.logger = logger;\n }\n db: IDBPDatabase<unknown> = {} as IDBPDatabase<unknown>;\n idb() {\n this.db;\n }\n\n async start(baseURL: URL): Promise<Result<void>> {\n return exception2Result(async () => {\n this.logger.Debug().Url(baseURL).Msg(\"starting\");\n await SysContainer.start();\n this.db = await connectIdb(baseURL, this.logger);\n this.logger.Debug().Url(baseURL).Msg(\"started\");\n });\n }\n async close(): Promise<Result<void>> {\n return Result.Ok(undefined);\n }\n async destroy(baseUrl: URL): Promise<Result<void>> {\n return exception2Result(async () => {\n // return deleteDB(getIndexDBName(this.url).fullDb);\n const type = getStore(baseUrl, this.logger, joinDBName);\n // console.log(\"IndexDBDataStore:destroy\", type);\n const idb = this.db;\n const trans = idb.transaction(type, \"readwrite\");\n const object_store = trans.objectStore(type);\n const toDelete = [];\n for (let cursor = await object_store.openCursor(); cursor; cursor = await cursor.continue()) {\n toDelete.push(cursor.primaryKey);\n }\n for (const key of toDelete) {\n await trans.db.delete(type, key);\n }\n await trans.done;\n });\n }\n\n abstract buildUrl(baseUrl: URL, key: string): Promise<Result<URL>>;\n\n async get(url: URL) {\n return exceptionWrapper(async () => {\n const key = getKey(url, this.logger);\n const store = getStore(url, this.logger, joinDBName);\n this.logger.Debug().Url(url).Str(\"key\", key).Str(\"store\", store).Msg(\"getting\");\n const tx = this.db.transaction([store], \"readonly\");\n const bytes = await tx.objectStore(store).get(sanitzeKey(key));\n await tx.done;\n if (!bytes) {\n return Result.Err(new NotFoundError(`missing ${key}`));\n }\n return Result.Ok(bytes as Uint8Array);\n });\n }\n async put(url: URL, value: Uint8Array) {\n return exception2Result(async () => {\n const key = getKey(url, this.logger);\n const store = getStore(url, this.logger, joinDBName);\n this.logger.Debug().Url(url).Str(\"key\", key).Str(\"store\", store).Msg(\"putting\");\n const tx = this.db.transaction([store], \"readwrite\");\n await tx.objectStore(store).put(value, sanitzeKey(key));\n await tx.done;\n });\n }\n async delete(url: URL) {\n return exception2Result(async () => {\n const key = getKey(url, this.logger);\n const store = getStore(url, this.logger, joinDBName);\n this.logger.Debug().Url(url).Str(\"key\", key).Str(\"store\", store).Msg(\"deleting\");\n const tx = this.db.transaction([store], \"readwrite\");\n await tx.objectStore(store).delete(sanitzeKey(key));\n await tx.done;\n return Result.Ok(undefined);\n });\n }\n}\n\nexport class IndexDBDataGateway extends IndexDBGateway {\n constructor(logger: Logger) {\n super(ensureLogger(logger, \"IndexDBDataGateway\", {}));\n }\n\n buildUrl(baseUrl: URL, key: string): Promise<Result<URL>> {\n const url = new URL(baseUrl.toString());\n url.searchParams.set(\"key\", key);\n return Promise.resolve(Result.Ok(url));\n }\n}\n\nexport class IndexDBWalGateway extends IndexDBGateway {\n constructor(logger: Logger) {\n super(ensureLogger(logger, \"IndexDBWalGateway\", {}));\n }\n buildUrl(baseUrl: URL, key: string): Promise<Result<URL>> {\n const url = new URL(baseUrl.toString());\n url.searchParams.set(\"key\", key);\n return Promise.resolve(Result.Ok(url));\n }\n}\nexport class IndexDBMetaGateway extends IndexDBGateway {\n constructor(logger: Logger) {\n super(ensureLogger(logger, \"IndexDBDataGateway\", {}));\n }\n\n readonly branches = new Set<string>();\n async buildUrl(baseUrl: URL, key: string): Promise<Result<URL>> {\n const url = new URL(baseUrl.toString());\n this.branches.add(key);\n url.searchParams.set(\"key\", key);\n return Result.Ok(url);\n }\n}\n\nconst txtEncoder = new TextEncoder();\nexport class IndexDBTestStore implements TestStore {\n readonly logger: Logger;\n constructor(logger: Logger) {\n this.logger = ensureLogger(logger, \"IndexDBTestStore\", {});\n }\n async get(url: URL, key: string) {\n const db = await connectIdb(url, this.logger);\n const store = getStore(url, this.logger, joinDBName);\n this.logger.Debug().Str(\"key\", key).Str(\"store\", store).Msg(\"getting\");\n let bytes = await db.get(store, sanitzeKey(key));\n this.logger.Debug().Str(\"key\", key).Str(\"store\", store).Int(\"len\", bytes.length).Msg(\"got\");\n if (typeof bytes === \"string\") {\n bytes = txtEncoder.encode(bytes);\n }\n return bytes as Uint8Array;\n }\n}\n","export * from \"./database.js\";\nexport * from \"./types.js\";\n\nexport * from \"./crdt.js\";\n\nexport * from \"./indexer.js\";\n\nexport * as bs from \"./blockstore/index.js\";\nexport * as blockstore from \"./blockstore/index.js\";\n\nexport * as rt from \"./runtime/index.js\";\nexport * as runtime from \"./runtime/index.js\";\n\nexport * from \"./utils.js\";\n\nexport * from \"./version.js\";\n","import { uuidv7 } from \"uuidv7\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n\nimport { WriteQueue, writeQueue } from \"./write-queue.js\";\nimport { CRDT } from \"./crdt.js\";\nimport { index } from \"./indexer.js\";\nimport type {\n DocUpdate,\n ClockHead,\n ConfigOpts,\n MapFn,\n QueryOpts,\n ChangesOptions,\n DocSet,\n DocWithId,\n IndexKeyType,\n ListenerFn,\n DocResponse,\n ChangesResponse,\n DocTypes,\n IndexRows,\n DocFragment,\n ChangesResponseRow,\n CRDTMeta,\n AllDocsQueryOpts,\n AllDocsResponse,\n} from \"./types.js\";\nimport { BaseBlockstore, Connectable } from \"./blockstore/index.js\";\nimport { SysContainer } from \"./runtime/sys-container.js\";\nimport { ensureLogger } from \"./utils.js\";\nimport { NotFoundError } from \"./blockstore/gateway.js\";\n\nexport class Database<DT extends DocTypes = NonNullable<unknown>> implements Connectable {\n static databases = new Map<string, Database>();\n\n readonly name?: string;\n readonly opts: ConfigOpts = {};\n\n _listening = false;\n readonly _listeners = new Set<ListenerFn<DT>>();\n readonly _noupdate_listeners = new Set<ListenerFn<DT>>();\n readonly _crdt: CRDT<DT>;\n readonly _writeQueue: WriteQueue<DT>;\n readonly blockstore: BaseBlockstore;\n\n async close() {\n await this.ready();\n await this._crdt.close();\n await this.blockstore.close();\n }\n\n async destroy() {\n await this.ready();\n await this._crdt.destroy();\n await this.blockstore.destroy();\n }\n\n readonly _ready = new ResolveOnce<void>();\n async ready() {\n return this._ready.once(async () => {\n await SysContainer.start();\n await this._crdt.ready();\n await this.blockstore.ready();\n });\n }\n\n readonly logger: Logger;\n\n constructor(name?: string, opts?: ConfigOpts) {\n this.name = name;\n this.opts = opts || this.opts;\n this.logger = ensureLogger(this.opts, \"Database\");\n // this.logger.SetDebug(\"Database\")\n this._crdt = new CRDT(name, this.opts);\n this.blockstore = this._crdt.blockstore; // for connector compatibility\n this._writeQueue = writeQueue(async (updates: DocUpdate<DT>[]) => {\n return await this._crdt.bulk(updates);\n }); //, Infinity)\n this._crdt.clock.onTock(() => {\n this._no_update_notify();\n });\n }\n\n async get<T extends DocTypes>(id: string): Promise<DocWithId<T>> {\n if (!id) throw this.logger.Error().Str(\"db\", this.name).Msg(`Doc id is required`).AsError();\n\n await this.ready();\n this.logger.Debug().Str(\"id\", id).Msg(\"get\");\n const got = await this._crdt.get(id).catch((e) => {\n throw new NotFoundError(`Not found: ${id} - ${e.message}`);\n });\n if (!got) throw new NotFoundError(`Not found: ${id}`);\n const { doc } = got;\n return { ...(doc as unknown as DocWithId<T>), _id: id };\n }\n\n async put<T extends DocTypes>(doc: DocSet<T>): Promise<DocResponse> {\n await this.ready();\n this.logger.Debug().Str(\"id\", doc._id).Msg(\"put\");\n const { _id, ...value } = doc;\n const docId = _id || uuidv7();\n const result = (await this._writeQueue.push({\n id: docId,\n value: {\n ...(value as unknown as DocSet<DT>),\n _id: docId,\n },\n })) as CRDTMeta;\n return { id: docId, clock: result?.head, name: this.name } as DocResponse;\n }\n\n async del(id: string): Promise<DocResponse> {\n await this.ready();\n this.logger.Debug().Str(\"id\", id).Msg(\"del\");\n const result = (await this._writeQueue.push({ id: id, del: true })) as CRDTMeta;\n return { id, clock: result?.head, name: this.name } as DocResponse;\n }\n\n async changes<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): Promise<ChangesResponse<T>> {\n await this.ready();\n this.logger.Debug().Any(\"since\", since).Any(\"opts\", opts).Msg(\"changes\");\n const { result, head } = await this._crdt.changes(since, opts);\n const rows: ChangesResponseRow<T>[] = result.map(({ id: key, value, del, clock }) => ({\n key,\n value: (del ? { _id: key, _deleted: true } : { _id: key, ...value }) as DocWithId<T>,\n clock,\n }));\n return { rows, clock: head, name: this.name };\n }\n\n async allDocs<T extends DocTypes>(opts: AllDocsQueryOpts = {}): Promise<AllDocsResponse<T>> {\n await this.ready();\n void opts;\n this.logger.Debug().Msg(\"allDocs\");\n const { result, head } = await this._crdt.allDocs();\n const rows = result.map(({ id: key, value, del }) => ({\n key,\n value: (del ? { _id: key, _deleted: true } : { _id: key, ...value }) as DocWithId<T>,\n }));\n return { rows, clock: head, name: this.name };\n }\n\n async allDocuments<T extends DocTypes>(): Promise<{\n rows: {\n key: string;\n value: DocWithId<T>;\n }[];\n clock: ClockHead;\n }> {\n return this.allDocs<T>();\n }\n\n subscribe<T extends DocTypes>(listener: ListenerFn<T>, updates?: boolean): () => void {\n this.logger.Debug().Bool(\"updates\", updates).Msg(\"subscribe\");\n if (updates) {\n if (!this._listening) {\n this._listening = true;\n this._crdt.clock.onTick((updates: DocUpdate<NonNullable<unknown>>[]) => {\n void this._notify(updates);\n });\n }\n this._listeners.add(listener as ListenerFn<NonNullable<unknown>>);\n return () => {\n this._listeners.delete(listener as ListenerFn<NonNullable<unknown>>);\n };\n } else {\n this._noupdate_listeners.add(listener as ListenerFn<NonNullable<unknown>>);\n return () => {\n this._noupdate_listeners.delete(listener as ListenerFn<NonNullable<unknown>>);\n };\n }\n }\n\n // todo if we add this onto dbs in fireproof.ts then we can make index.ts a separate package\n async query<K extends IndexKeyType, T extends DocTypes, R extends DocFragment = T>(\n field: string | MapFn<T>,\n opts: QueryOpts<K> = {},\n ): Promise<IndexRows<K, T, R>> {\n await this.ready();\n this.logger.Debug().Any(\"field\", field).Any(\"opts\", opts).Msg(\"query\");\n const _crdt = this._crdt as unknown as CRDT<T>;\n const idx =\n typeof field === \"string\" ? index<K, T, R>({ _crdt }, field) : index<K, T, R>({ _crdt }, makeName(field.toString()), field);\n return await idx.query(opts);\n }\n\n async compact() {\n await this.ready();\n await this._crdt.compact();\n }\n\n async _notify(updates: DocUpdate<NonNullable<unknown>>[]) {\n await this.ready();\n if (this._listeners.size) {\n const docs: DocWithId<NonNullable<unknown>>[] = updates.map(({ id, value }) => ({ ...value, _id: id }));\n for (const listener of this._listeners) {\n await (async () => await listener(docs as DocWithId<DT>[]))().catch((e: Error) => {\n this.logger.Error().Err(e).Msg(\"subscriber error\");\n });\n }\n }\n }\n\n async _no_update_notify() {\n await this.ready();\n if (this._noupdate_listeners.size) {\n for (const listener of this._noupdate_listeners) {\n await (async () => await listener([]))().catch((e: Error) => {\n this.logger.Error().Err(e).Msg(\"subscriber error\");\n });\n }\n }\n }\n}\n\nfunction toSortedArray(set?: Record<string, unknown>): Record<string, unknown>[] {\n if (!set) return [];\n return Object.entries(set)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => ({ [k]: v }));\n}\n\nexport function fireproof(name: string, opts?: ConfigOpts): Database {\n const key = JSON.stringify(\n toSortedArray({\n name,\n stores: toSortedArray(opts?.store?.stores),\n\n makeMetaStore: !!opts?.store?.makeMetaStore,\n makeDataStore: !!opts?.store?.makeDataStore,\n makeRemoteWAL: !!opts?.store?.makeRemoteWAL,\n\n encodeFile: !!opts?.store?.encodeFile,\n decodeFile: !!opts?.store?.decodeFile,\n }),\n );\n let db = Database.databases.get(key);\n if (!db) {\n db = new Database(name, opts);\n Database.databases.set(key, db);\n }\n return db;\n}\n\nfunction makeName(fnString: string) {\n const regex = /\\(([^,()]+,\\s*[^,()]+|\\[[^\\]]+\\],\\s*[^,()]+)\\)/g;\n let found: RegExpExecArray | null = null;\n const matches = Array.from(fnString.matchAll(regex), (match) => match[1].trim());\n if (matches.length === 0) {\n found = /=>\\s*(.*)/.exec(fnString);\n }\n if (!found) {\n return fnString;\n } else {\n // it's a consise arrow function, match everything after the arrow\n return found[1];\n }\n}\n","import { DocTypes, MetaType, DocUpdate } from \"./types.js\";\n\ntype WorkerFunction<T extends DocTypes> = (tasks: DocUpdate<T>[]) => Promise<MetaType>;\n\nexport interface WriteQueue<T extends DocTypes> {\n push(task: DocUpdate<T>): Promise<MetaType>;\n}\n\ninterface WriteQueueItem<T extends DocTypes> {\n readonly task: DocUpdate<T>;\n resolve(result: MetaType): void;\n reject(error: Error): void;\n}\n\nexport function writeQueue<T extends DocTypes>(worker: WorkerFunction<T>, payload = Infinity, unbounded = false): WriteQueue<T> {\n const queue: WriteQueueItem<T>[] = [];\n let isProcessing = false;\n\n async function process() {\n if (isProcessing || queue.length === 0) return;\n isProcessing = true;\n\n const tasksToProcess = queue.splice(0, payload);\n const updates = tasksToProcess.map((item) => item.task);\n\n if (unbounded) {\n // Run all updates in parallel and resolve/reject them individually\n const promises = updates.map(async (update, index) => {\n try {\n const result = await worker([update]);\n tasksToProcess[index].resolve(result);\n } catch (error) {\n tasksToProcess[index].reject(error as Error);\n }\n });\n\n await Promise.all(promises);\n } else {\n // Original logic: Run updates in a batch and resolve/reject them together\n try {\n const result = await worker(updates);\n tasksToProcess.forEach((task) => task.resolve(result));\n } catch (error) {\n tasksToProcess.forEach((task) => task.reject(error as Error));\n }\n }\n\n isProcessing = false;\n void process();\n }\n\n return {\n push(task: DocUpdate<T>): Promise<MetaType> {\n return new Promise<MetaType>((resolve, reject) => {\n queue.push({ task, resolve, reject });\n void process();\n });\n },\n };\n}\n","import { Block } from \"multiformats\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n\nimport {\n EncryptedBlockstore,\n type CompactionFetcher,\n type TransactionMeta,\n type CarTransaction,\n BaseBlockstore,\n} from \"./blockstore/index.js\";\nimport {\n clockChangesSince,\n applyBulkUpdateToCrdt,\n getValueFromCrdt,\n readFiles,\n getAllEntries,\n clockVis,\n getBlock,\n doCompact,\n} from \"./crdt-helpers.js\";\nimport type {\n DocUpdate,\n CRDTMeta,\n ClockHead,\n ConfigOpts,\n ChangesOptions,\n IdxMetaMap,\n DocValue,\n IndexKeyType,\n DocWithId,\n DocTypes,\n Falsy,\n} from \"./types.js\";\nimport { index, type Index } from \"./indexer.js\";\nimport { CRDTClock } from \"./crdt-clock.js\";\nimport { blockstoreFactory } from \"./blockstore/transaction.js\";\nimport { ensureLogger } from \"./utils.js\";\n\nexport class CRDT<T extends DocTypes> {\n readonly name?: string;\n readonly opts: ConfigOpts;\n\n readonly onceReady = new ResolveOnce<void>();\n async ready(): Promise<void> {\n return this.onceReady.once(async () => {\n await Promise.all([this.blockstore.ready(), this.indexBlockstore.ready(), this.clock.ready()]);\n });\n }\n\n async close(): Promise<void> {\n await Promise.all([this.blockstore.close(), this.indexBlockstore.close(), this.clock.close()]);\n }\n\n async destroy(): Promise<void> {\n await Promise.all([this.blockstore.destroy(), this.indexBlockstore.destroy()]);\n }\n\n readonly blockstore: BaseBlockstore;\n readonly indexBlockstore: BaseBlockstore;\n readonly indexers = new Map<string, Index<IndexKeyType, NonNullable<unknown>>>();\n readonly clock: CRDTClock<T>;\n\n readonly logger: Logger;\n\n constructor(name?: string, opts: ConfigOpts = {}) {\n this.name = name;\n this.logger = ensureLogger(opts, \"CRDT\");\n this.opts = opts;\n this.blockstore = blockstoreFactory({\n name: name,\n applyMeta: async (meta: TransactionMeta) => {\n const crdtMeta = meta as CRDTMeta;\n if (!crdtMeta.head) throw this.logger.Error().Msg(\"missing head\").AsError();\n await this.clock.applyHead(crdtMeta.head, []);\n },\n compact: async (blocks: CompactionFetcher) => {\n await doCompact(blocks, this.clock.head, this.logger);\n return { head: this.clock.head } as TransactionMeta;\n },\n autoCompact: this.opts.autoCompact || 100,\n crypto: this.opts.crypto,\n store: { ...this.opts.store, isIndex: undefined },\n public: this.opts.public,\n meta: this.opts.meta,\n threshold: this.opts.threshold,\n });\n this.indexBlockstore = blockstoreFactory({\n name: name,\n applyMeta: async (meta: TransactionMeta) => {\n const idxCarMeta = meta as IdxMetaMap;\n if (!idxCarMeta.indexes) throw this.logger.Error().Msg(\"missing indexes\").AsError();\n for (const [name, idx] of Object.entries(idxCarMeta.indexes)) {\n index({ _crdt: this }, name, undefined, idx);\n }\n },\n crypto: this.opts.crypto,\n store: { ...this.opts.store, isIndex: this.opts.store?.isIndex || \"idx\" },\n public: this.opts.public,\n });\n this.clock = new CRDTClock<T>(this.blockstore);\n this.clock.onZoom(() => {\n for (const idx of this.indexers.values()) {\n idx._resetIndex();\n }\n });\n }\n\n async bulk(updates: DocUpdate<T>[]): Promise<CRDTMeta> {\n await this.ready();\n const prevHead = [...this.clock.head];\n\n const done = await this.blockstore.transaction<CRDTMeta>(async (blocks: CarTransaction): Promise<CRDTMeta> => {\n const { head } = await applyBulkUpdateToCrdt<T>(\n this.blockstore.ebOpts.storeRuntime,\n blocks,\n this.clock.head,\n updates,\n this.logger,\n );\n updates = updates.map((dupdate: DocUpdate<T>) => {\n // if (!dupdate.value) throw new Error(\"missing value\");\n readFiles(this.blockstore, { doc: dupdate.value as DocWithId<T> });\n return dupdate;\n });\n return { head };\n });\n await this.clock.applyHead(done.meta.head, prevHead, updates);\n return done.meta;\n }\n\n // if (snap) await this.clock.applyHead(crdtMeta.head, this.clock.head)\n\n async allDocs(): Promise<{ result: DocUpdate<T>[]; head: ClockHead }> {\n await this.ready();\n const result: DocUpdate<T>[] = [];\n for await (const entry of getAllEntries<T>(this.blockstore, this.clock.head, this.logger)) {\n result.push(entry);\n }\n return { result, head: this.clock.head };\n }\n\n async vis(): Promise<string> {\n await this.ready();\n const txt: string[] = [];\n for await (const line of clockVis(this.blockstore, this.clock.head)) {\n txt.push(line);\n }\n return txt.join(\"\\n\");\n }\n\n async getBlock(cidString: string): Promise<Block> {\n await this.ready();\n return await getBlock(this.blockstore, cidString);\n }\n\n async get(key: string): Promise<DocValue<T> | Falsy> {\n await this.ready();\n const result = await getValueFromCrdt<T>(this.blockstore, this.clock.head, key, this.logger);\n if (result.del) return undefined;\n return result;\n }\n\n async changes(\n since: ClockHead = [],\n opts: ChangesOptions = {},\n ): Promise<{\n result: DocUpdate<T>[];\n head: ClockHead;\n }> {\n await this.ready();\n return await clockChangesSince<T>(this.blockstore, this.clock.head, since, opts, this.logger);\n }\n\n async compact(): Promise<void> {\n const blocks = this.blockstore as EncryptedBlockstore;\n return await blocks.compact();\n }\n}\n","import { encode, decode, Block } from \"multiformats/block\";\nimport { parse } from \"multiformats/link\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as codec from \"@ipld/dag-cbor\";\nimport { put, get, entries, root } from \"@web3-storage/pail/crdt\";\nimport { EventBlockView, EventLink, Operation, PutOperation } from \"@web3-storage/pail/crdt/api\";\nimport { EventFetcher, vis } from \"@web3-storage/pail/clock\";\nimport * as Batch from \"@web3-storage/pail/crdt/batch\";\nimport {\n type EncryptedBlockstore,\n type CompactionFetcher,\n CarTransaction,\n BlockFetcher,\n TransactionMeta,\n AnyLink,\n StoreRuntime,\n BaseBlockstore,\n} from \"./blockstore/index.js\";\nimport {\n type IndexKeyType,\n type DocUpdate,\n type ClockHead,\n type DocValue,\n type CRDTMeta,\n type ChangesOptions,\n type DocFileMeta,\n type DocFiles,\n type DocSet,\n type DocWithId,\n type DocTypes,\n throwFalsy,\n} from \"./types.js\";\nimport { Result } from \"@web3-storage/pail/crdt/api\";\nimport { Logger } from \"@adviser/cement\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction time(tag: string) {\n // console.time(tag)\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction timeEnd(tag: string) {\n // console.timeEnd(tag)\n}\n\nfunction toString<K extends IndexKeyType>(key: K, logger: Logger): string {\n switch (typeof key) {\n case \"string\":\n case \"number\":\n return key.toString();\n default:\n throw logger.Error().Msg(\"Invalid key type\").AsError();\n }\n}\n\nexport async function applyBulkUpdateToCrdt<T extends DocTypes>(\n store: StoreRuntime,\n tblocks: CarTransaction,\n head: ClockHead,\n updates: DocUpdate<T>[],\n logger: Logger,\n): Promise<CRDTMeta> {\n let result: Result | null = null;\n if (updates.length > 1) {\n const batch = await Batch.create(tblocks, head);\n for (const update of updates) {\n const link = await writeDocContent(store, tblocks, update, logger);\n await batch.put(toString(update.id, logger), link);\n }\n result = await batch.commit();\n } else if (updates.length === 1) {\n const link = await writeDocContent(store, tblocks, updates[0], logger);\n result = await put(tblocks, head, toString(updates[0].id, logger), link);\n }\n if (!result) throw logger.Error().Uint64(\"updates.len\", updates.length).Msg(\"Missing result\").AsError();\n\n if (result.event) {\n for (const { cid, bytes } of [\n ...result.additions,\n // ...result.removals,\n result.event,\n ]) {\n tblocks.putSync(cid, bytes);\n }\n }\n return { head: result.head } as CRDTMeta;\n}\n\n// this whole thing can get pulled outside of the write queue\nasync function writeDocContent<T extends DocTypes>(\n store: StoreRuntime,\n blocks: CarTransaction,\n update: DocUpdate<T>,\n logger: Logger,\n): Promise<AnyLink> {\n let value: Partial<DocValue<T>>;\n if (update.del) {\n value = { del: true };\n } else {\n if (!update.value) throw logger.Error().Msg(\"Missing value\").AsError();\n await processFiles(store, blocks, update.value, logger);\n value = { doc: update.value as DocWithId<T> };\n }\n const block = await encode({ value, hasher, codec });\n blocks.putSync(block.cid, block.bytes);\n return block.cid;\n}\n\nasync function processFiles<T extends DocTypes>(store: StoreRuntime, blocks: CarTransaction, doc: DocSet<T>, logger: Logger) {\n if (doc._files) {\n await processFileset(logger, store, blocks, doc._files);\n }\n if (doc._publicFiles) {\n await processFileset(logger, store, blocks, doc._publicFiles, true);\n }\n}\n\nasync function processFileset(logger: Logger, store: StoreRuntime, blocks: CarTransaction, files: DocFiles, publicFiles = false) {\n const dbBlockstore = blocks.parent as EncryptedBlockstore;\n if (!dbBlockstore.loader) throw logger.Error().Msg(\"Missing loader, database name is required\").AsError();\n const t = new CarTransaction(dbBlockstore); // maybe this should move to encrypted-blockstore\n const didPut = [];\n // let totalSize = 0\n for (const filename in files) {\n if (File === files[filename].constructor) {\n const file = files[filename] as File;\n\n // totalSize += file.size\n const { cid, blocks: fileBlocks } = await store.encodeFile(file);\n didPut.push(filename);\n for (const block of fileBlocks) {\n t.putSync(block.cid, block.bytes);\n }\n files[filename] = { cid, type: file.type, size: file.size } as DocFileMeta;\n } else {\n const { cid, type, size, car } = files[filename] as DocFileMeta;\n if (cid && type && size && car) {\n files[filename] = { cid, type, size, car };\n }\n }\n }\n\n if (didPut.length) {\n const car = await dbBlockstore.loader.commitFiles(t, { files } as unknown as TransactionMeta, {\n public: publicFiles,\n });\n if (car) {\n for (const name of didPut) {\n files[name] = { car, ...files[name] } as DocFileMeta;\n }\n }\n }\n}\n\nexport async function getValueFromCrdt<T extends DocTypes>(\n blocks: BaseBlockstore,\n head: ClockHead,\n key: string,\n logger: Logger,\n): Promise<DocValue<T>> {\n if (!head.length) throw logger.Debug().Msg(\"Getting from an empty database\").AsError();\n const link = await get(blocks, head, key);\n if (!link) throw logger.Error().Str(\"key\", key).Msg(`Missing key`).AsError();\n return await getValueFromLink(blocks, link, logger);\n}\n\nexport function readFiles<T extends DocTypes>(blocks: BaseBlockstore, { doc }: Partial<DocValue<T>>) {\n if (!doc) return;\n if (doc._files) {\n readFileset(blocks as EncryptedBlockstore, doc._files);\n }\n if (doc._publicFiles) {\n readFileset(blocks as EncryptedBlockstore, doc._publicFiles, true);\n }\n}\n\nfunction readFileset(blocks: EncryptedBlockstore, files: DocFiles, isPublic = false) {\n for (const filename in files) {\n const fileMeta = files[filename] as DocFileMeta;\n if (fileMeta.cid) {\n if (isPublic) {\n fileMeta.url = `https://${fileMeta.cid.toString()}.ipfs.w3s.link/`;\n }\n if (fileMeta.car) {\n fileMeta.file = async () =>\n await blocks.ebOpts.storeRuntime.decodeFile(\n {\n get: async (cid: AnyLink) => {\n return await blocks.getFile(throwFalsy(fileMeta.car), cid, isPublic);\n },\n },\n fileMeta.cid,\n fileMeta,\n );\n }\n }\n files[filename] = fileMeta;\n }\n}\n\nasync function getValueFromLink<T extends DocTypes>(blocks: BlockFetcher, link: AnyLink, logger: Logger): Promise<DocValue<T>> {\n const block = await blocks.get(link);\n if (!block) throw logger.Error().Str(\"link\", link.toString()).Msg(`Missing linked block`).AsError();\n const { value } = (await decode({ bytes: block.bytes, hasher, codec })) as { value: DocValue<T> };\n const cvalue = {\n ...value,\n cid: link,\n };\n readFiles(blocks as EncryptedBlockstore, cvalue);\n return cvalue;\n}\n\nclass DirtyEventFetcher<T> extends EventFetcher<T> {\n async get(link: EventLink<T>): Promise<EventBlockView<T>> {\n try {\n return super.get(link);\n } catch (e) {\n console.error(\"missing event\", link.toString(), e);\n return { value: undefined } as unknown as EventBlockView<T>;\n }\n }\n}\n\nexport async function clockChangesSince<T extends DocTypes>(\n blocks: BlockFetcher,\n head: ClockHead,\n since: ClockHead,\n opts: ChangesOptions,\n logger: Logger,\n): Promise<{ result: DocUpdate<T>[]; head: ClockHead }> {\n const eventsFetcher = (\n opts.dirty ? new DirtyEventFetcher<Operation>(blocks) : new EventFetcher<Operation>(blocks)\n ) as EventFetcher<Operation>;\n const keys = new Set<string>();\n const updates = await gatherUpdates<T>(\n blocks,\n eventsFetcher,\n head,\n since,\n [],\n keys,\n new Set<string>(),\n opts.limit || Infinity,\n logger,\n );\n return { result: updates.reverse(), head };\n}\n\nasync function gatherUpdates<T extends DocTypes>(\n blocks: BlockFetcher,\n eventsFetcher: EventFetcher<Operation>,\n head: ClockHead,\n since: ClockHead,\n updates: DocUpdate<T>[] = [],\n keys: Set<string>,\n didLinks: Set<string>,\n limit: number,\n logger: Logger,\n): Promise<DocUpdate<T>[]> {\n if (limit <= 0) return updates;\n // if (Math.random() < 0.001) console.log('gatherUpdates', head.length, since.length, updates.length)\n const sHead = head.map((l) => l.toString());\n for (const link of since) {\n if (sHead.includes(link.toString())) {\n return updates;\n }\n }\n for (const link of head) {\n if (didLinks.has(link.toString())) continue;\n didLinks.add(link.toString());\n const { value: event } = await eventsFetcher.get(link);\n if (!event) continue;\n const { type } = event.data;\n let ops = [] as PutOperation[];\n if (type === \"batch\") {\n ops = event.data.ops as PutOperation[];\n } else if (type === \"put\") {\n ops = [event.data] as PutOperation[];\n }\n for (let i = ops.length - 1; i >= 0; i--) {\n const { key, value } = ops[i];\n if (!keys.has(key)) {\n // todo option to see all updates\n const docValue = await getValueFromLink<T>(blocks, value, logger);\n updates.push({ id: key, value: docValue.doc, del: docValue.del, clock: link });\n limit--;\n keys.add(key);\n }\n }\n if (event.parents) {\n updates = await gatherUpdates(blocks, eventsFetcher, event.parents, since, updates, keys, didLinks, limit, logger);\n }\n }\n return updates;\n}\n\nexport async function* getAllEntries<T extends DocTypes>(blocks: BlockFetcher, head: ClockHead, logger: Logger) {\n // return entries(blocks, head)\n for await (const [key, link] of entries(blocks, head)) {\n const docValue = await getValueFromLink(blocks, link, logger);\n yield { id: key, value: docValue.doc, del: docValue.del } as DocUpdate<T>;\n }\n}\n\nexport async function* clockVis(blocks: BlockFetcher, head: ClockHead) {\n for await (const line of vis(blocks, head)) {\n yield line;\n }\n}\n\nlet isCompacting = false;\nexport async function doCompact(blockLog: CompactionFetcher, head: ClockHead, logger: Logger) {\n if (isCompacting) {\n // console.log('already compacting')\n return;\n }\n isCompacting = true;\n\n time(\"compact head\");\n for (const cid of head) {\n const bl = await blockLog.get(cid);\n if (!bl) throw logger.Error().Ref(\"cid\", cid).Msg(\"Missing head block\").AsError();\n }\n timeEnd(\"compact head\");\n\n // for await (const blk of blocks.entries()) {\n // const bl = await blockLog.get(blk.cid)\n // if (!bl) throw new Error('Missing tblock: ' + blk.cid.toString())\n // }\n\n // todo maybe remove\n // for await (const blk of blocks.loader!.entries()) {\n // const bl = await blockLog.get(blk.cid)\n // if (!bl) throw new Error('Missing db block: ' + blk.cid.toString())\n // }\n\n time(\"compact all entries\");\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _entry of getAllEntries(blockLog, head, logger)) {\n // result.push(entry)\n // void 1;\n continue;\n }\n timeEnd(\"compact all entries\");\n\n // time(\"compact crdt entries\")\n // for await (const [, link] of entries(blockLog, head)) {\n // const bl = await blockLog.get(link)\n // if (!bl) throw new Error('Missing entry block: ' + link.toString())\n // }\n // timeEnd(\"compact crdt entries\")\n\n time(\"compact clock vis\");\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _line of vis(blockLog, head)) {\n void 1;\n }\n timeEnd(\"compact clock vis\");\n\n time(\"compact root\");\n const result = await root(blockLog, head);\n timeEnd(\"compact root\");\n\n time(\"compact root blocks\");\n for (const { cid, bytes } of [...result.additions, ...result.removals]) {\n blockLog.loggedBlocks.putSync(cid, bytes);\n }\n timeEnd(\"compact root blocks\");\n\n time(\"compact changes\");\n await clockChangesSince(blockLog, head, [], {}, logger);\n timeEnd(\"compact changes\");\n\n isCompacting = false;\n}\n\nexport async function getBlock(blocks: BlockFetcher, cidString: string) {\n const block = await blocks.get(parse(cidString));\n if (!block) throw new Error(`Missing block ${cidString}`);\n const { cid, value } = await decode({ bytes: block.bytes, codec, hasher });\n return new Block({ cid, value, bytes: block.bytes });\n}\n","import { ConnectREST } from \"./connect-rest.js\";\nexport type {\n AnyBlock,\n AnyLink,\n AnyAnyLink,\n CarGroup,\n UploadDataFnParams,\n UploadMetaFnParams,\n DownloadDataFnParams,\n DownloadMetaFnParams,\n DbMeta,\n CommitOpts,\n CryptoOpts,\n StoreFactory,\n StoreOpts,\n StoreRuntime,\n TransactionMeta,\n BlobLike,\n Connection,\n TestStore,\n} from \"./types.js\";\n\nexport * from \"./store-factory.js\";\nexport * from \"./gateway.js\";\n\nimport { type CarClockHead, type Connectable, type DbMetaEventBlock } from \"./connection-base.js\";\nexport { ConnectREST, CarClockHead, Connectable, DbMetaEventBlock };\n\nexport { EncryptedBlockstore, BaseBlockstore, CompactionFetcher, type BlockFetcher, CarTransaction } from \"./transaction.js\";\nexport { Loader, Loadable } from \"./loader.js\";\nexport { DataStore, type DataSaveOpts, MetaStore, RemoteWAL, type WALState } from \"./store.js\";\nexport { parseCarFile } from \"./loader-helpers.js\";\nexport { ConnectionBase } from \"./connection-base.js\";\n","import { EventBlock, decodeEventBlock } from \"@web3-storage/pail/clock\";\nimport { EventView } from \"@web3-storage/pail/clock/api\";\nimport { MemoryBlockstore } from \"@web3-storage/pail/block\";\nimport type { Link, Version } from \"multiformats\";\nimport { Logger } from \"@adviser/cement\";\n\nimport { Falsy, throwFalsy } from \"../types.js\";\nimport { TaskManager } from \"./task-manager.js\";\nimport type { BlockstoreOpts } from \"./transaction.js\";\nimport type { UploadMetaFnParams, UploadDataFnParams, DownloadMetaFnParams, DownloadDataFnParams, Connection } from \"./types.js\";\nimport { Loadable, type Loader } from \"./loader.js\";\nimport { ensureLogger } from \"../utils.js\";\n\nexport type CarClockHead = Link<DbMetaEventBlock, number, number, Version>[];\n\nexport interface Connectable {\n readonly blockstore: {\n readonly loader?: Loader;\n readonly ebOpts: BlockstoreOpts;\n };\n readonly name?: string;\n}\n\nexport abstract class ConnectionBase implements Connection {\n // readonly ready: Promise<unknown>;\n // todo move to LRU blockstore https://github.com/web3-storage/w3clock/blob/main/src/worker/block.js\n readonly eventBlocks = new MemoryBlockstore();\n parents: CarClockHead = [];\n loader?: Loadable;\n taskManager?: TaskManager;\n loaded: Promise<void> = Promise.resolve();\n\n abstract metaUpload(bytes: Uint8Array, params: UploadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n abstract dataUpload(bytes: Uint8Array, params: UploadDataFnParams, opts?: { public?: boolean }): Promise<void>;\n abstract metaDownload(params: DownloadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n abstract dataDownload(params: DownloadDataFnParams): Promise<Uint8Array | Falsy>;\n\n readonly logger: Logger;\n constructor(logger: Logger) {\n this.logger = ensureLogger(logger, \"ConnectionBase\");\n }\n\n async refresh() {\n await throwFalsy(throwFalsy(this.loader).remoteMetaStore).load(\"main\");\n await (await throwFalsy(this.loader).remoteWAL())._process();\n }\n\n connect({ loader }: { loader?: Loader }) {\n if (!loader) throw this.logger.Error().Msg(\"loader is required\").AsError();\n this.connectMeta({ loader });\n this.connectStorage({ loader });\n }\n\n connectMeta({ loader }: { loader?: Loader }) {\n if (!loader) throw this.logger.Error().Msg(\"loader is required\").AsError();\n this.loader = loader;\n this.taskManager = new TaskManager(loader);\n this.onConnect();\n this.logger.Warn().Msg(\"connectMeta: connecting to remote meta store is disabled\");\n // const remote = new RemoteMetaStore(new URL(`remote://connectMeta`), this.loader.name, this, this.logger);\n // remote.onLoad(\"main\", async (metas) => {\n // if (metas) {\n // await throwFalsy(this.loader).handleDbMetasFromStore(metas);\n // }\n // });\n // this.loader.remoteMetaStore = remote;\n // this.loaded = this.loader.ready().then(async () => {\n // remote.load(\"main\").then(async () => {\n // (await throwFalsy(this.loader).remoteWAL())._process();\n // });\n // });\n }\n\n async onConnect() {\n return;\n }\n\n connectStorage({ loader }: { loader?: Loader }) {\n if (!loader) throw this.logger.Error().Msg(\"loader is required\").AsError();\n this.loader = loader;\n this.logger.Warn().Msg(\"connectStorage: connecting to remote meta store is disabled\");\n // loader.remoteCarStore = new RemoteDataStore(new URL(`remote://remoteCarStore`), this.loader.name, this, this.logger);\n // loader.remoteFileStore = new RemoteDataStore(new URL(`remote://remoteFileStore`), this.loader.name, this, this.logger);\n }\n\n async createEventBlock(bytes: Uint8Array): Promise<DbMetaEventBlock> {\n const data = {\n dbMeta: bytes,\n };\n const event = await EventBlock.create(\n data,\n this.parents as unknown as Link<EventView<{ dbMeta: Uint8Array }>, number, number, 1>[],\n );\n await this.eventBlocks.put(event.cid, event.bytes);\n return event as EventBlock<{ dbMeta: Uint8Array }>; // todo test these `as` casts\n }\n\n async decodeEventBlock(bytes: Uint8Array): Promise<DbMetaEventBlock> {\n const event = await decodeEventBlock<{ dbMeta: Uint8Array }>(bytes);\n return event as EventBlock<{ dbMeta: Uint8Array }>; // todo test these `as` casts\n }\n\n // move this stuff to connect\n // async getDashboardURL(compact = true) {\n // const baseUrl = 'https://dashboard.fireproof.storage/'\n // if (!this.loader?.remoteCarStore) return new URL('/howto', baseUrl)\n // // if (compact) {\n // // await this.compact()\n // // }\n // const currents = await this.loader?.metaStore?.load()\n // if (!currents) throw new Error(\"Can't sync empty database: save data first\")\n // if (currents.length > 1)\n // throw new Error(\"Can't sync database with split heads: make an update first\")\n // const current = currents[0]\n // const params = {\n // car: current.car.toString()\n // }\n // if (current.key) {\n // // @ts-ignore\n // params.key = current.key.toString()\n // }\n // // @ts-ignore\n // if (this.name) {\n // // @ts-ignore\n // params.name = this.name\n // }\n // const url = new URL('/import#' + new URLSearchParams(params).toString(), baseUrl)\n // console.log('Import to dashboard: ' + url.toString())\n // return url\n // }\n\n // openDashboard() {\n // void this.getDashboardURL().then(url => {\n // if (url) window.open(url.toString(), '_blank')\n // })\n // }\n}\n\nexport type DbMetaEventBlock = EventBlock<{ dbMeta: Uint8Array }>;\n","import { Logger } from \"@adviser/cement\";\nimport { DbMetaEventBlock } from \"./connection-base.js\";\nimport { AnyLink, Loader } from \"./index.js\";\nimport { ensureLogger } from \"../utils.js\";\n\ninterface TaskItem {\n readonly cid: string;\n readonly eventBlock: DbMetaEventBlock;\n retries: number;\n}\n\nexport class TaskManager {\n private readonly eventsWeHandled = new Set<string>();\n private readonly loader: Loader;\n\n private queue: TaskItem[] = [];\n private isProcessing = false;\n\n readonly logger: Logger;\n constructor(loader: Loader) {\n this.loader = loader;\n this.logger = ensureLogger(loader.logger, \"TaskManager\");\n }\n\n async handleEvent(eventBlock: DbMetaEventBlock) {\n const cid = eventBlock.cid.toString();\n const parents = eventBlock.value.parents.map((cid: AnyLink) => cid.toString());\n for (const parent of parents) {\n this.eventsWeHandled.add(parent);\n }\n this.queue.push({ cid, eventBlock, retries: 0 });\n this.queue = this.queue.filter(({ cid }) => !this.eventsWeHandled.has(cid));\n void this.processQueue();\n }\n\n private async processQueue() {\n if (this.isProcessing) return;\n this.isProcessing = true;\n const filteredQueue = this.queue.filter(({ cid }) => !this.eventsWeHandled.has(cid));\n const first = filteredQueue[0];\n if (!first) {\n return;\n }\n try {\n this.loader?.remoteMetaStore?.handleByteHeads([first.eventBlock.value.data.dbMeta]);\n this.eventsWeHandled.add(first.cid);\n this.queue = this.queue.filter(({ cid }) => !this.eventsWeHandled.has(cid));\n } catch (err) {\n if (first.retries++ > 3) {\n this.logger.Error().Str(\"cid\", first.cid).Msg(\"failed to process event block after 3 retries\");\n this.queue = this.queue.filter(({ cid }) => cid !== first.cid);\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n throw this.logger.Error().Err(err).Msg(\"failed to process event block\").AsError();\n } finally {\n this.isProcessing = false;\n if (this.queue.length > 0) {\n void this.processQueue();\n }\n }\n }\n}\n","import type { DownloadMetaFnParams, DownloadDataFnParams, UploadMetaFnParams, UploadDataFnParams } from \"./types.js\";\nimport { ConnectionBase } from \"./connection-base.js\";\nimport { ensureLogger } from \"../utils.js\";\nimport { Logger } from \"@adviser/cement\";\n\nexport class ConnectREST extends ConnectionBase {\n readonly baseUrl: URL;\n\n constructor(base: string, logger: Logger) {\n super(ensureLogger(logger, \"ConnectREST\"));\n this.baseUrl = new URL(base);\n }\n\n async dataUpload(bytes: Uint8Array, params: UploadDataFnParams) {\n // console.log('s3 dataUpload', params.car.toString())\n const carCid = params.car.toString();\n const uploadURL = new URL(`/cars/${carCid}.car`, this.baseUrl);\n\n const done = await fetch(uploadURL, { method: \"PUT\", body: bytes });\n // console.log('rest dataUpload done', params.car.toString(), done)\n if (!done.ok) {\n throw this.logger.Error().Msg(\"failed to upload data \" + done.statusText);\n }\n }\n\n async dataDownload(params: DownloadDataFnParams) {\n const { car } = params;\n const fetchFromUrl = new URL(`/cars/${car.toString()}.car`, this.baseUrl);\n const response = await fetch(fetchFromUrl);\n if (!response.ok) {\n return undefined; // throw new Error('failed to download data ' + response.statusText)\n }\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async metaUpload(bytes: Uint8Array, params: UploadMetaFnParams) {\n // const event = await this.createEventBlock(bytes)\n // const base64String = Base64.fromUint8Array(bytes)\n // const crdtEntry = {\n // cid: event.cid.toString(),\n // data: base64String,\n // parents: this.parents.map(p => p.toString())\n // }\n // const fetchUploadUrl = new URL(\n // `?${new URLSearchParams({ type: 'meta', ...params }).toString()}`,\n // this.uploadUrl\n // )\n // const done = await fetch(fetchUploadUrl, {\n // method: 'PUT',\n // body: JSON.stringify(crdtEntry)\n // })\n // const result = await done.json()\n // if (result.status != 201) {\n // throw new Error('failed to upload data ' + JSON.parse(result.body).message)\n // }\n // this.parents = [event.cid]\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async metaDownload(params: DownloadMetaFnParams) {\n // const { name, branch } = params\n // const fetchUploadUrl = new URL(`?${new URLSearchParams({ type: \"meta\", ...params }).toString()}`,this.uploadUrl)\n // const data = await fetch(fetchUploadUrl)\n // let response = await data.json()\n // if (response.status != 200) throw new Error(\"Failed to download data\")\n // response = JSON.parse(response.body).items\n // const events = await Promise.all(\n // response.map(async (element: any) => {\n // const base64String = element.data\n // const bytes = Base64.toUint8Array(base64String)\n // return { cid: element.cid, bytes }\n // })\n // )\n // const cids = events.map((e) => e.cid)\n // const uniqueParentsMap = new Map([...this.parents, ...cids].map((p) => [p.toString(), p]))\n // this.parents = Array.from(uniqueParentsMap.values())\n // return events.map((e) => e.bytes)\n return [];\n }\n}\n","import { Logger, KeyedResolvOnce } from \"@adviser/cement\";\n\nimport { dataDir } from \"../runtime/data-dir.js\";\nimport { decodeFile, encodeFile } from \"../runtime/files.js\";\nimport { Loadable } from \"./loader.js\";\nimport { DataStore, MetaStore, RemoteWAL } from \"./store.js\";\nimport { StoreOpts, StoreRuntime, TestStore } from \"./types.js\";\nimport { ensureLogger } from \"../utils.js\";\nimport { Gateway } from \"./gateway.js\";\n\nfunction ensureIsIndex(url: URL, isIndex?: string): URL {\n if (isIndex) {\n url.searchParams.set(\"index\", isIndex);\n return url;\n } else {\n url.searchParams.delete(\"index\");\n return url;\n }\n}\n\nexport function toURL(pathOrUrl: string | URL, isIndex?: string): URL {\n if (pathOrUrl instanceof URL) return ensureIsIndex(pathOrUrl, isIndex);\n try {\n const url = new URL(pathOrUrl);\n return ensureIsIndex(url, isIndex);\n } catch (e) {\n const url = new URL(`file://${pathOrUrl}`);\n return ensureIsIndex(url, isIndex);\n }\n}\n\nexport interface StoreFactoryItem {\n readonly protocol: string;\n readonly overrideBaseURL?: string; // if this set it overrides the defaultURL\n readonly overrideRegistration?: boolean; // if this is set, it will override the registration\n // which switches between file and indexdb\n readonly data: (logger: Logger) => Promise<Gateway>;\n readonly meta: (logger: Logger) => Promise<Gateway>;\n readonly wal: (logger: Logger) => Promise<Gateway>;\n readonly test: (logger: Logger) => Promise<TestStore>;\n}\n\nconst storeFactory = new Map<string, StoreFactoryItem>();\n\nfunction ensureName(name: string, url: URL) {\n if (!url.searchParams.has(\"name\")) {\n url.searchParams.set(\"name\", name);\n }\n}\n\nfunction buildURL(optURL: string | URL | undefined, loader: Loadable): URL {\n const storeOpts = loader.ebOpts.store;\n const obuItem = Array.from(storeFactory.values()).find((items) => items.overrideBaseURL);\n let obuUrl: URL | undefined;\n if (obuItem && obuItem.overrideBaseURL) {\n obuUrl = new URL(obuItem.overrideBaseURL);\n }\n return toURL(optURL || obuUrl || dataDir(loader.name, storeOpts.stores?.base), storeOpts.isIndex);\n}\n\nexport function registerStoreProtocol(item: StoreFactoryItem) {\n let protocol = item.protocol;\n if (!protocol.endsWith(\":\")) {\n protocol += \":\";\n }\n if (storeFactory.has(protocol)) {\n if (!item.overrideBaseURL && storeFactory.get(protocol) !== item) {\n const logger = ensureLogger({}, \"registerStoreProtocol\", { protocol });\n logger.Warn().Msg(`protocol ${protocol} already registered`);\n return () => {\n /* no-op */\n };\n }\n }\n // we need to clear the overrideBaseURL if it is set\n if (item.overrideBaseURL) {\n Array.from(storeFactory.values()).forEach((items) => {\n (\n items as {\n overrideBaseURL?: string;\n }\n ).overrideBaseURL = undefined;\n });\n }\n storeFactory.set(protocol, item);\n return () => {\n storeFactory.delete(protocol);\n };\n}\n\nfunction runStoreFactory<T>(url: URL, logger: Logger, run: (item: StoreFactoryItem) => Promise<T>): Promise<T> {\n const item = storeFactory.get(url.protocol);\n if (!item) {\n throw logger\n .Error()\n .Url(url)\n .Str(\"protocol\", url.protocol)\n .Any(\"keys\", Array(storeFactory.keys()))\n .Msg(`unsupported protocol`)\n .AsError();\n }\n logger.Debug().Str(\"protocol\", url.protocol).Msg(\"run\");\n return run(item);\n}\n\nconst onceLoadDataGateway = new KeyedResolvOnce<Gateway>();\nfunction loadDataGateway(url: URL, logger: Logger) {\n return onceLoadDataGateway.get(url.protocol).once(async () => {\n return runStoreFactory(url, logger, async (item) => item.data(logger));\n });\n}\n\nconst onceDataStoreFactory = new KeyedResolvOnce<DataStore>();\nasync function dataStoreFactory(loader: Loadable): Promise<DataStore> {\n const url = buildURL(loader.ebOpts.store.stores?.data, loader);\n ensureName(loader.name, url);\n const logger = ensureLogger(loader.logger, \"dataStoreFactory\", { url: url.toString() });\n url.searchParams.set(\"store\", \"data\");\n return onceDataStoreFactory.get(url.toString()).once(async () => {\n const gateway = await loadDataGateway(url, logger);\n const store = new DataStore(loader.name, url, loader.logger, gateway);\n const ret = await store.start();\n if (ret.isErr()) {\n throw logger.Error().Result(\"start\", ret).Msg(\"start failed\").AsError();\n }\n logger.Debug().Str(\"prepared\", store.url.toString()).Msg(\"produced\");\n return store;\n });\n}\n\nconst onceLoadMetaGateway = new KeyedResolvOnce<Gateway>();\nfunction loadMetaGateway(url: URL, logger: Logger) {\n return onceLoadMetaGateway.get(url.protocol).once(async () => {\n return runStoreFactory(url, logger, async (item) => item.meta(logger));\n });\n}\n\nconst onceMetaStoreFactory = new KeyedResolvOnce<MetaStore>();\nasync function metaStoreFactory(loader: Loadable): Promise<MetaStore> {\n const url = buildURL(loader.ebOpts.store.stores?.meta, loader);\n ensureName(loader.name, url);\n const logger = ensureLogger(loader.logger, \"metaStoreFactory\", { url: () => url.toString() });\n url.searchParams.set(\"store\", \"meta\");\n return onceMetaStoreFactory.get(url.toString()).once(async () => {\n logger.Debug().Str(\"protocol\", url.protocol).Msg(\"pre-protocol switch\");\n const gateway = await loadMetaGateway(url, logger);\n const store = new MetaStore(loader.name, url, loader.logger, gateway);\n const ret = await store.start();\n if (ret.isErr()) {\n throw logger.Error().Result(\"start\", ret).Msg(\"start failed\").AsError();\n }\n return store;\n });\n}\n\nconst onceWalGateway = new KeyedResolvOnce<Gateway>();\nfunction loadWalGateway(url: URL, logger: Logger) {\n return onceWalGateway.get(url.protocol).once(async () => {\n return runStoreFactory(url, logger, async (item) => item.wal(logger));\n });\n}\n\nconst onceRemoteWalFactory = new KeyedResolvOnce<RemoteWAL>();\nasync function remoteWalFactory(loader: Loadable): Promise<RemoteWAL> {\n const url = buildURL(loader.ebOpts.store.stores?.meta, loader);\n ensureName(loader.name, url);\n const logger = ensureLogger(loader.logger, \"remoteWalFactory\", { url: url.toString() });\n url.searchParams.set(\"store\", \"wal\");\n return onceRemoteWalFactory.get(url.toString()).once(async () => {\n const gateway = await loadWalGateway(url, logger);\n logger.Debug().Str(\"prepared\", url.toString()).Msg(\"produced\");\n const store = new RemoteWAL(loader, url, loader.logger, gateway);\n const ret = await store.start();\n if (ret.isErr()) {\n throw logger.Error().Result(\"start\", ret).Msg(\"start failed\").AsError();\n }\n return store;\n });\n}\n\nexport async function testStoreFactory(url: URL, ilogger?: Logger): Promise<TestStore> {\n const logger = ensureLogger(\n {\n logger: ilogger,\n },\n \"testStoreFactory\",\n );\n return runStoreFactory(url, logger, async (item) => item.test(logger));\n}\n\nexport function toStoreRuntime(opts: StoreOpts, ilogger: Logger): StoreRuntime {\n const logger = ensureLogger(ilogger, \"toStoreRuntime\", {});\n return {\n makeMetaStore: (loader: Loadable) => {\n logger\n .Debug()\n .Str(\"fromOpts\", \"\" + !!loader.ebOpts.store.makeMetaStore)\n .Msg(\"makeMetaStore\");\n return (loader.ebOpts.store.makeMetaStore || metaStoreFactory)(loader);\n },\n makeDataStore: (loader: Loadable) => {\n logger\n .Debug()\n .Str(\"fromOpts\", \"\" + !!loader.ebOpts.store.makeDataStore)\n .Msg(\"makeDataStore\");\n return (loader.ebOpts.store.makeDataStore || dataStoreFactory)(loader);\n },\n makeRemoteWAL: (loader: Loadable) => {\n logger\n .Debug()\n .Str(\"fromOpts\", \"\" + !!loader.ebOpts.store.makeRemoteWAL)\n .Msg(\"makeRemoteWAL\");\n return (loader.ebOpts.store.makeRemoteWAL || remoteWalFactory)(loader);\n },\n\n encodeFile: opts.encodeFile || encodeFile,\n decodeFile: opts.decodeFile || decodeFile,\n };\n}\n\nregisterStoreProtocol({\n protocol: \"file:\",\n data: async (logger) => {\n const { FileDataGateway } = await import(\"../runtime/store-file.js\");\n return new FileDataGateway(logger);\n },\n meta: async (logger) => {\n const { FileMetaGateway } = await import(\"../runtime/store-file.js\");\n return new FileMetaGateway(logger);\n },\n wal: async (logger) => {\n const { FileWALGateway } = await import(\"../runtime/store-file.js\");\n return new FileWALGateway(logger);\n },\n test: async (logger) => {\n const { FileTestStore } = await import(\"../runtime/store-file.js\");\n return new FileTestStore(logger);\n },\n});\n\nregisterStoreProtocol({\n protocol: \"indexdb:\",\n data: async (logger) => {\n const { IndexDBDataGateway } = await import(\"../runtime/store-indexdb.js\");\n return new IndexDBDataGateway(logger);\n },\n meta: async (logger) => {\n const { IndexDBMetaGateway } = await import(\"../runtime/store-indexdb.js\");\n return new IndexDBMetaGateway(logger);\n },\n wal: async (logger) => {\n const { IndexDBMetaGateway } = await import(\"../runtime/store-indexdb.js\");\n return new IndexDBMetaGateway(logger);\n },\n test: async (logger) => {\n const { IndexDBTestStore } = await import(\"../runtime/store-indexdb.js\");\n return new IndexDBTestStore(logger);\n },\n});\n","import pLimit from \"p-limit\";\nimport { format, parse, ToString } from \"@ipld/dag-json\";\nimport { Logger, ResolveOnce, Result } from \"@adviser/cement\";\n\nimport type { AnyBlock, AnyLink, CommitOpts, DbMeta } from \"./types.js\";\nimport { Falsy, throwFalsy } from \"../types.js\";\nimport { Gateway, isNotFoundError } from \"./gateway.js\";\nimport { ensureLogger, exception2Result } from \"../utils.js\";\nimport { carLogIncludesGroup, Loadable } from \"./loader.js\";\nimport { CommitQueue } from \"./commit-queue.js\";\n\n// const match = PACKAGE_VERSION.match(/^([^.]*\\.[^.]*)/);\n// if (!match) throw new Error(\"invalid version: \" + PACKAGE_VERSION);\n// export const STORAGE_VERSION = match[0];\n\nfunction guardVersion(url: URL): Result<URL> {\n if (!url.searchParams.has(\"version\")) {\n return Result.Err(`missing version: ${url.toString()}`);\n }\n return Result.Ok(url);\n}\n\nabstract class VersionedStore {\n // readonly STORAGE_VERSION: string;\n readonly name: string;\n readonly url: URL;\n readonly logger: Logger;\n constructor(name: string, url: URL, logger: Logger) {\n this.name = name;\n this.url = url;\n this.logger = logger;\n // const sv = url.searchParams.get(\"version\");\n // if (!sv) throw this.logger.Error().Str(\"url\", url.toString()).Msg(`version not found`);\n // this.STORAGE_VERSION = sv;\n }\n\n readonly _onStarted: (() => void)[] = [];\n onStarted(fn: () => void) {\n this._onStarted.push(fn);\n }\n abstract start(): Promise<Result<void>>;\n\n readonly _onClosed: (() => void)[] = [];\n onClosed(fn: () => void) {\n this._onClosed.push(fn);\n }\n abstract close(): Promise<Result<void>>;\n}\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport class MetaStore extends VersionedStore {\n readonly tag: string = \"header-base\";\n\n readonly gateway: Gateway;\n\n constructor(name: string, url: URL, logger: Logger, gateway: Gateway) {\n super(name, url, ensureLogger(logger, \"MetaStore\", {}));\n this.gateway = gateway;\n }\n\n makeHeader({ cars, key }: DbMeta): ToString<DbMeta> {\n const toEncode: DbMeta = { cars };\n if (key) toEncode.key = key;\n return format(toEncode);\n }\n\n parseHeader(headerData: ToString<DbMeta>): DbMeta {\n const got = parse<DbMeta>(headerData);\n return got;\n }\n\n async start(): Promise<Result<void>> {\n this.logger.Debug().Msg(\"starting\");\n const res = await this.gateway.start(this.url);\n if (res.isErr()) {\n return res;\n }\n this._onStarted.forEach((fn) => fn());\n return guardVersion(this.url);\n }\n\n async load(branch?: string): Promise<DbMeta[] | Falsy> {\n this.logger\n .Debug()\n .Str(\"branch\", branch || \"\")\n .Msg(\"loading\");\n const url = await this.gateway.buildUrl(this.url, branch || \"main\");\n if (url.isErr()) {\n throw this.logger\n .Error()\n .Result(\"buidUrl\", url)\n .Str(\"branch\", branch || \"\")\n .Url(this.url)\n .Msg(\"got error from gateway.buildUrl\")\n .AsError();\n }\n const bytes = await this.gateway.get(url.Ok());\n if (bytes.isErr()) {\n if (isNotFoundError(bytes)) {\n return undefined;\n }\n throw this.logger.Error().Url(url.Ok()).Result(\"bytes:\", bytes).Msg(\"gateway get\").AsError();\n }\n try {\n return [this.parseHeader(textDecoder.decode(bytes.Ok()))];\n } catch (e) {\n throw this.logger.Error().Err(e).Msg(\"parseHeader\").AsError();\n }\n }\n\n async save(meta: DbMeta, branch = \"main\") {\n this.logger.Debug().Str(\"branch\", branch).Any(\"meta\", meta).Msg(\"saving meta\");\n const bytes = this.makeHeader(meta);\n const url = await this.gateway.buildUrl(this.url, branch);\n if (url.isErr()) {\n throw this.logger.Error().Err(url.Err()).Str(\"branch\", branch).Url(this.url).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n const res = await this.gateway.put(url.Ok(), textEncoder.encode(bytes));\n if (res.isErr()) {\n throw this.logger.Error().Err(res.Err()).Msg(\"got error from gateway.put\").AsError();\n }\n return res.Ok();\n }\n\n async close(): Promise<Result<void>> {\n await this.gateway.close(this.url);\n this._onClosed.forEach((fn) => fn());\n return Result.Ok(undefined);\n }\n async destroy(): Promise<Result<void>> {\n return this.gateway.destroy(this.url);\n }\n}\n\nexport interface DataSaveOpts {\n readonly public: boolean;\n}\n\nexport class DataStore extends VersionedStore {\n readonly tag: string = \"car-base\";\n readonly gateway: Gateway;\n\n constructor(name: string, url: URL, logger: Logger, gateway: Gateway) {\n super(\n name,\n url,\n ensureLogger(logger, \"DataStore\", {\n url: () => url.toString(),\n }),\n );\n this.gateway = gateway;\n }\n\n async start(): Promise<Result<void>> {\n this.logger.Debug().Msg(\"starting-gateway\");\n const res = await this.gateway.start(this.url);\n if (res.isErr()) {\n this.logger.Error().Result(\"gw-start\", res).Msg(\"started-gateway\");\n return res;\n }\n this._onStarted.forEach((fn) => fn());\n const version = guardVersion(this.url);\n if (version.isErr()) {\n this.logger.Error().Result(\"version\", version).Msg(\"guardVersion\");\n await this.close();\n return version;\n }\n this.logger.Debug().Msg(\"started\");\n return version;\n }\n\n async load(cid: AnyLink): Promise<AnyBlock> {\n this.logger.Debug().Any(\"cid\", cid).Msg(\"loading\");\n const url = await this.gateway.buildUrl(this.url, cid.toString());\n if (url.isErr()) {\n throw this.logger.Error().Err(url.Err()).Str(\"cid\", cid.toString()).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n const res = await this.gateway.get(url.Ok());\n if (res.isErr()) {\n throw res.Err();\n }\n return { cid, bytes: res.Ok() };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async save(car: AnyBlock, opts?: DataSaveOpts): Promise</*AnyLink | */ void> {\n this.logger.Debug().Any(\"cid\", car.cid.toString()).Msg(\"saving\");\n const url = await this.gateway.buildUrl(this.url, car.cid.toString());\n if (url.isErr()) {\n throw this.logger.Error().Err(url.Err()).Ref(\"cid\", car.cid).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n const res = await this.gateway.put(url.Ok(), car.bytes);\n if (res.isErr()) {\n throw this.logger.Error().Err(res.Err()).Msg(\"got error from gateway.put\").AsError();\n }\n return res.Ok();\n }\n async remove(cid: AnyLink): Promise<Result<void>> {\n const url = await this.gateway.buildUrl(this.url, cid.toString());\n if (url.isErr()) {\n return url;\n }\n return this.gateway.delete(url.Ok());\n }\n async close(): Promise<Result<void>> {\n await this.gateway.close(this.url);\n this._onClosed.forEach((fn) => fn());\n return Result.Ok(undefined);\n }\n destroy(): Promise<Result<void>> {\n return this.gateway.destroy(this.url);\n }\n}\n\nexport interface WALState {\n operations: DbMeta[];\n noLoaderOps: DbMeta[];\n fileOperations: {\n readonly cid: AnyLink;\n readonly public: boolean;\n }[];\n}\n\nexport class RemoteWAL extends VersionedStore {\n readonly tag: string = \"rwal-base\";\n\n readonly loader: Loadable;\n\n readonly _ready = new ResolveOnce<void>();\n\n private async ready() {\n return this._ready.once(async () => {\n const walState = await this.load().catch((e) => {\n this.logger.Error().Any(\"error\", e).Msg(\"error loading wal\");\n return undefined;\n });\n if (!walState) {\n this.walState.operations = [];\n this.walState.fileOperations = [];\n } else {\n this.walState.operations = walState.operations || [];\n this.walState.fileOperations = walState.fileOperations || [];\n }\n });\n }\n\n walState: WALState = { operations: [], noLoaderOps: [], fileOperations: [] };\n readonly processing: Promise<void> | undefined = undefined;\n readonly processQueue: CommitQueue<void> = new CommitQueue<void>();\n\n readonly gateway: Gateway;\n\n constructor(loader: Loadable, url: URL, logger: Logger, gateway: Gateway) {\n super(loader.name, url, ensureLogger(logger, \"RemoteWAL\"));\n this.loader = loader;\n this.gateway = gateway;\n }\n\n async enqueue(dbMeta: DbMeta, opts: CommitOpts) {\n await this.ready();\n if (opts.noLoader) {\n this.walState.noLoaderOps.push(dbMeta);\n } else {\n this.walState.operations.push(dbMeta);\n }\n await this.save(this.walState);\n void this._process();\n }\n\n async enqueueFile(fileCid: AnyLink, publicFile = false) {\n await this.ready();\n this.walState.fileOperations.push({ cid: fileCid, public: publicFile });\n // await this.save(this.walState)\n }\n\n async _process() {\n await this.ready();\n if (!this.loader.remoteCarStore) return;\n await this.processQueue.enqueue(async () => {\n await this._doProcess();\n if (this.walState.operations.length || this.walState.fileOperations.length || this.walState.noLoaderOps.length) {\n setTimeout(() => void this._process(), 0);\n }\n });\n }\n\n async _doProcess() {\n if (!this.loader.remoteCarStore) return;\n const rmlp = (async () => {\n const operations = [...this.walState.operations];\n const fileOperations = [...this.walState.fileOperations];\n const uploads: Promise<void>[] = [];\n const noLoaderOps = [...this.walState.noLoaderOps];\n const limit = pLimit(5);\n\n if (operations.length + fileOperations.length + noLoaderOps.length === 0) return;\n\n for (const dbMeta of noLoaderOps) {\n const uploadP = limit(async () => {\n for (const cid of dbMeta.cars) {\n const car = await (await this.loader.carStore()).load(cid);\n if (!car) {\n if (carLogIncludesGroup(this.loader.carLog, dbMeta.cars))\n throw this.logger.Error().Ref(\"cid\", cid).Msg(\"missing local car\").AsError();\n } else {\n await throwFalsy(this.loader.remoteCarStore).save(car);\n }\n this.walState.noLoaderOps = this.walState.noLoaderOps.filter((op) => op !== dbMeta);\n }\n });\n uploads.push(uploadP);\n }\n\n for (const dbMeta of operations) {\n const uploadP = limit(async () => {\n for (const cid of dbMeta.cars) {\n const car = await (await this.loader.carStore()).load(cid).catch(() => null);\n if (!car) {\n if (carLogIncludesGroup(this.loader.carLog, dbMeta.cars))\n throw this.logger.Error().Ref(\"cid\", cid).Msg(`missing local car`).AsError();\n } else {\n await throwFalsy(this.loader.remoteCarStore).save(car);\n }\n }\n this.walState.operations = this.walState.operations.filter((op) => op !== dbMeta);\n });\n uploads.push(uploadP);\n }\n\n if (fileOperations.length) {\n const dbLoader = this.loader;\n for (const { cid: fileCid, public: publicFile } of fileOperations) {\n const uploadP = limit(async () => {\n const fileBlock = await (await dbLoader.fileStore()).load(fileCid); // .catch(() => false)\n await dbLoader.remoteFileStore?.save(fileBlock, { public: publicFile });\n this.walState.fileOperations = this.walState.fileOperations.filter((op) => op.cid !== fileCid);\n });\n uploads.push(uploadP);\n }\n }\n\n try {\n const res = await Promise.allSettled(uploads);\n const errors = res.filter((r) => r.status === \"rejected\") as PromiseRejectedResult[];\n if (errors.length) {\n throw this.logger\n .Error()\n .Any(\n \"errors\",\n errors.map((e) => e.reason),\n )\n .Msg(\"error uploading\")\n .AsError();\n\n errors[0].reason;\n }\n if (operations.length) {\n const lastOp = operations[operations.length - 1];\n // console.log('saving remote meta', lastOp.car.toString())\n await this.loader.remoteMetaStore?.save(lastOp).catch((e: Error) => {\n this.walState.operations.push(lastOp);\n throw this.logger.Error().Any(\"error\", e).Msg(\"error saving remote meta\").AsError();\n });\n }\n } finally {\n await this.save(this.walState);\n }\n })();\n // this.loader.remoteMetaLoading = rmlp;\n await rmlp;\n }\n\n async start() {\n const res = await this.gateway.start(this.url);\n if (res.isErr()) {\n return res;\n }\n const ver = guardVersion(this.url);\n if (ver.isErr()) {\n await this.close();\n return ver;\n }\n const ready = await exception2Result(() => this.ready());\n this._onStarted.forEach((fn) => fn());\n if (ready.isErr()) {\n await this.close();\n return ready;\n }\n return ready;\n }\n\n async load(): Promise<WALState | Falsy> {\n this.logger.Debug().Msg(\"loading\");\n const filepath = await this.gateway.buildUrl(this.url, \"main\");\n if (filepath.isErr()) {\n throw this.logger.Error().Err(filepath.Err()).Str(\"url\", this.url.toString()).Msg(\"error building url\").AsError();\n }\n const bytes = await this.gateway.get(filepath.Ok());\n if (bytes.isErr()) {\n if (isNotFoundError(bytes)) {\n return undefined;\n }\n throw this.logger.Error().Err(bytes.Err()).Msg(\"error get\").AsError();\n }\n try {\n return bytes && parse<WALState>(textDecoder.decode(bytes.Ok()));\n } catch (e) {\n throw this.logger.Error().Err(e).Msg(\"error parse\").AsError();\n }\n }\n\n async save(state: WALState) {\n const filepath = await this.gateway.buildUrl(this.url, \"main\");\n if (filepath.isErr()) {\n throw this.logger.Error().Err(filepath.Err()).Str(\"url\", this.url.toString()).Msg(\"error building url\").AsError();\n }\n let encoded: ToString<WALState>;\n try {\n encoded = format(state);\n } catch (e) {\n throw this.logger.Error().Err(e).Any(\"state\", state).Msg(\"error format\").AsError();\n }\n const res = await this.gateway.put(filepath.Ok(), textEncoder.encode(encoded));\n if (res.isErr()) {\n throw this.logger.Error().Err(res.Err()).Str(\"filePath\", filepath.Ok().toString()).Msg(\"error saving\").AsError();\n }\n }\n\n async close() {\n await this.gateway.close(this.url);\n this._onClosed.forEach((fn) => fn());\n return Result.Ok(undefined);\n }\n\n destroy() {\n return this.gateway.destroy(this.url);\n }\n}\n","import pLimit from \"p-limit\";\nimport { CarReader } from \"@ipld/car\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n// import { uuidv4 } from \"uuidv7\";\n\nimport {\n type AnyBlock,\n type AnyLink,\n type CarHeader,\n type CommitOpts,\n type DbMeta,\n type TransactionMeta,\n type CarGroup,\n type CarLog,\n toCIDBlock,\n} from \"./types.js\";\nimport type { BlockstoreOpts, BlockstoreRuntime } from \"./transaction.js\";\n\nimport { encodeCarFile, encodeCarHeader, parseCarFile } from \"./loader-helpers.js\";\nimport { decodeEncryptedCar, encryptedEncodeCarFile } from \"./encrypt-helpers.js\";\n\nimport { DataStore, MetaStore, RemoteWAL } from \"./store.js\";\n\nimport { CarTransaction, defaultedBlockstoreRuntime } from \"./transaction.js\";\nimport { CommitQueue } from \"./commit-queue.js\";\nimport * as CBW from \"@ipld/car/buffer-writer\";\nimport type { Falsy, FileTransactionMeta } from \"../types.js\";\n\nexport function carLogIncludesGroup(list: CarLog, cids: CarGroup) {\n return list.some((arr: CarGroup) => {\n return arr.toString() === cids.toString();\n });\n}\n\n// this works for car groups because toString looks like bafy,bafy\nfunction uniqueCids(list: CarLog, remove = new Set<string>()): CarLog {\n const byString = new Map<string, CarGroup>();\n for (const cid of list) {\n if (remove.has(cid.toString())) continue;\n byString.set(cid.toString(), cid);\n }\n return [...byString.values()];\n}\n\nexport function toHexString(byteArray: Uint8Array) {\n return Array.from(byteArray)\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\ntype AbstractRemoteMetaStore = MetaStore & {\n handleByteHeads(byteHeads: Uint8Array[], branch?: string): Promise<DbMeta[]>;\n};\n\nexport abstract class Loadable {\n name = \"\";\n abstract readonly logger: Logger;\n abstract readonly ebOpts: BlockstoreRuntime;\n remoteCarStore?: DataStore;\n abstract carStore(): Promise<DataStore>;\n carLog: CarLog = new Array<CarGroup>();\n remoteMetaStore?: AbstractRemoteMetaStore;\n remoteFileStore?: DataStore;\n abstract ready(): Promise<void>;\n abstract close(): Promise<void>;\n abstract fileStore(): Promise<DataStore>;\n abstract remoteWAL(): Promise<RemoteWAL>;\n abstract handleDbMetasFromStore(metas: DbMeta[]): Promise<void>;\n}\n\nexport class Loader implements Loadable {\n readonly name: string;\n readonly ebOpts: BlockstoreRuntime;\n readonly commitQueue: CommitQueue<CarGroup> = new CommitQueue<CarGroup>();\n readonly isCompacting = false;\n readonly carReaders = new Map<string, Promise<CarReader>>();\n readonly seenCompacted = new Set<string>();\n readonly processedCars = new Set<string>();\n\n carLog: CarLog = [];\n key?: string;\n keyId?: string;\n remoteMetaStore?: AbstractRemoteMetaStore;\n remoteCarStore?: DataStore;\n remoteFileStore?: DataStore;\n\n private getBlockCache = new Map<string, AnyBlock>();\n private seenMeta = new Set<string>();\n private writeLimit = pLimit(1);\n\n // readonly id = uuidv4();\n\n async carStore(): Promise<DataStore> {\n return this.ebOpts.storeRuntime.makeDataStore(this);\n }\n\n async fileStore(): Promise<DataStore> {\n return this.ebOpts.storeRuntime.makeDataStore(this);\n }\n async remoteWAL(): Promise<RemoteWAL> {\n return this.ebOpts.storeRuntime.makeRemoteWAL(this);\n }\n\n async metaStore(): Promise<MetaStore> {\n return this.ebOpts.storeRuntime.makeMetaStore(this);\n }\n\n readonly onceReady = new ResolveOnce<void>();\n async ready(): Promise<void> {\n return this.onceReady.once(async () => {\n const metas = this.ebOpts.meta ? [this.ebOpts.meta] : await (await this.metaStore()).load(\"main\");\n if (metas) {\n await this.handleDbMetasFromStore(metas);\n }\n });\n }\n\n async close() {\n const toClose = await Promise.all([this.carStore(), this.metaStore(), this.fileStore(), this.remoteWAL()]);\n await Promise.all(toClose.map((store) => store.close()));\n }\n\n async destroy() {\n const toDestroy = await Promise.all([this.carStore(), this.metaStore(), this.fileStore(), this.remoteWAL()]);\n await Promise.all(toDestroy.map((store) => store.destroy()));\n }\n\n readonly logger: Logger;\n constructor(name: string, ebOpts: BlockstoreOpts) {\n this.name = name;\n // console.log(\"Loader\", name, ebOpts)\n this.ebOpts = defaultedBlockstoreRuntime(\n {\n ...ebOpts,\n name,\n },\n \"Loader\",\n );\n this.logger = this.ebOpts.logger;\n }\n\n // async snapToCar(carCid: AnyLink | string) {\n // await this.ready\n // if (typeof carCid === 'string') {\n // carCid = CID.parse(carCid)\n // }\n // const carHeader = await this.loadCarHeaderFromMeta({ car: carCid, key: this.key || null })\n // this.carLog = [carCid, ...carHeader.cars]\n // await this.getMoreReaders(carHeader.cars)\n // await this._applyCarHeader(carHeader, true)\n // }\n\n async handleDbMetasFromStore(metas: DbMeta[]): Promise<void> {\n for (const meta of metas) {\n await this.writeLimit(async () => {\n await this.mergeDbMetaIntoClock(meta);\n });\n }\n }\n\n async mergeDbMetaIntoClock(meta: DbMeta): Promise<void> {\n if (this.isCompacting) {\n throw this.logger.Error().Msg(\"cannot merge while compacting\").AsError();\n }\n\n if (this.seenMeta.has(meta.cars.toString())) return;\n this.seenMeta.add(meta.cars.toString());\n\n if (meta.key) {\n await this.setKey(meta.key);\n }\n if (carLogIncludesGroup(this.carLog, meta.cars)) {\n return;\n }\n const carHeader = await this.loadCarHeaderFromMeta<TransactionMeta>(meta);\n // fetch other cars down the compact log?\n // todo we should use a CID set for the compacted cids (how to expire?)\n // console.log('merge carHeader', carHeader.head.length, carHeader.head.toString(), meta.car.toString())\n carHeader.compact.map((c) => c.toString()).forEach(this.seenCompacted.add, this.seenCompacted);\n await this.getMoreReaders(carHeader.cars.flat());\n this.carLog = [...uniqueCids([meta.cars, ...this.carLog, ...carHeader.cars], this.seenCompacted)];\n await this.ebOpts.applyMeta?.(carHeader.meta);\n }\n\n protected async ingestKeyFromMeta(meta: DbMeta): Promise<void> {\n const { key } = meta;\n if (key) {\n await this.setKey(key);\n }\n }\n\n async loadCarHeaderFromMeta<T>({ cars: cids }: DbMeta): Promise<CarHeader<T>> {\n //Call loadCar for every cid\n const reader = await this.loadCar(cids[0]);\n return await parseCarFile(reader, this.logger);\n }\n\n async _getKey(): Promise<string | undefined> {\n if (this.key) return this.key;\n // generate a random key\n if (!this.ebOpts.public) {\n await this.setKey(toHexString(this.ebOpts.crypto.randomBytes(32)));\n }\n return this.key || undefined;\n }\n\n async commitFiles(\n t: CarTransaction,\n done: TransactionMeta,\n opts: CommitOpts = { noLoader: false, compact: false },\n ): Promise<CarGroup> {\n return this.commitQueue.enqueue(() => this._commitInternalFiles(t, done, opts));\n }\n // can these skip the queue? or have a file queue?\n async _commitInternalFiles(\n t: CarTransaction,\n done: TransactionMeta,\n opts: CommitOpts = { noLoader: false, compact: false },\n ): Promise<CarGroup> {\n await this.ready();\n const { files: roots } = this.makeFileCarHeader(done as FileTransactionMeta) as {\n files: AnyLink[];\n };\n const cids: AnyLink[] = [];\n const cars = await this.prepareCarFilesFiles(roots, t, !!opts.public);\n for (const car of cars) {\n const { cid, bytes } = car;\n await (await this.fileStore()).save({ cid, bytes });\n await (await this.remoteWAL()).enqueueFile(cid, !!opts.public);\n cids.push(cid);\n }\n\n return cids;\n }\n\n async loadFileCar(cid: AnyLink, isPublic = false): Promise<CarReader> {\n return await this.storesLoadCar(cid, await this.fileStore(), this.remoteFileStore, isPublic);\n }\n\n async commit<T = TransactionMeta>(\n t: CarTransaction,\n done: T,\n opts: CommitOpts = { noLoader: false, compact: false },\n ): Promise<CarGroup> {\n return this.commitQueue.enqueue(() => this._commitInternal(t, done, opts));\n }\n\n async cacheTransaction(t: CarTransaction) {\n for await (const block of t.entries()) {\n const sBlock = block.cid.toString();\n if (!this.getBlockCache.has(sBlock)) {\n this.getBlockCache.set(sBlock, block);\n }\n }\n }\n\n async cacheCarReader(carCidStr: string, reader: CarReader) {\n if (this.processedCars.has(carCidStr)) return;\n this.processedCars.add(carCidStr);\n for await (const block of reader.blocks()) {\n const sBlock = block.cid.toString();\n if (!this.getBlockCache.has(sBlock)) {\n this.getBlockCache.set(sBlock, block);\n }\n }\n }\n\n async _commitInternal<T>(t: CarTransaction, done: T, opts: CommitOpts = { noLoader: false, compact: false }): Promise<CarGroup> {\n await this.ready();\n const fp = this.makeCarHeader<T>(done, this.carLog, !!opts.compact);\n const rootBlock = await encodeCarHeader(fp);\n\n const cars = await this.prepareCarFiles(rootBlock, t, !!opts.public);\n const cids: AnyLink[] = [];\n for (const car of cars) {\n const { cid, bytes } = car;\n await (await this.carStore()).save({ cid, bytes });\n cids.push(cid);\n }\n\n await this.cacheTransaction(t);\n const newDbMeta = { cars: cids, key: this.key || null } as DbMeta;\n await (await this.remoteWAL()).enqueue(newDbMeta, opts);\n await (await this.metaStore()).save(newDbMeta);\n await this.updateCarLog(cids, fp, !!opts.compact);\n return cids;\n }\n\n async prepareCarFilesFiles(\n roots: AnyLink[],\n t: CarTransaction,\n isPublic: boolean,\n ): Promise<{ cid: AnyLink; bytes: Uint8Array }[]> {\n const theKey = isPublic ? null : await this._getKey();\n const car =\n theKey && this.ebOpts.crypto\n ? await encryptedEncodeCarFile(this.logger, this.ebOpts.crypto, theKey, roots[0], t)\n : await encodeCarFile(roots, t);\n return [car];\n }\n\n async prepareCarFiles(rootBlock: AnyBlock, t: CarTransaction, isPublic: boolean): Promise<{ cid: AnyLink; bytes: Uint8Array }[]> {\n const theKey = isPublic ? undefined : await this._getKey();\n const carFiles: { cid: AnyLink; bytes: Uint8Array }[] = [];\n const threshold = this.ebOpts.threshold || 1000 * 1000;\n let clonedt = new CarTransaction(t.parent, { add: false });\n clonedt.putSync(rootBlock.cid, rootBlock.bytes);\n let newsize = CBW.blockLength(toCIDBlock(rootBlock));\n let cidRootBlock = rootBlock;\n for (const { cid, bytes } of t.entries()) {\n newsize += CBW.blockLength(toCIDBlock({ cid: cid, bytes }));\n if (newsize >= threshold) {\n carFiles.push(await this.createCarFile(theKey, cidRootBlock.cid, clonedt));\n clonedt = new CarTransaction(t.parent, { add: false });\n clonedt.putSync(cid, bytes);\n cidRootBlock = { cid, bytes };\n newsize = CBW.blockLength(toCIDBlock({ cid, bytes })); //+ CBW.blockLength(rootBlock)\n } else {\n clonedt.putSync(cid, bytes);\n }\n }\n carFiles.push(await this.createCarFile(theKey, cidRootBlock.cid, clonedt));\n // console.log(\"split to \", carFiles.length, \"files\")\n return carFiles;\n }\n\n private async createCarFile(\n theKey: string | undefined,\n cid: AnyLink,\n t: CarTransaction,\n ): Promise<{ cid: AnyLink; bytes: Uint8Array }> {\n try {\n return theKey && this.ebOpts.crypto\n ? await encryptedEncodeCarFile(this.logger, this.ebOpts.crypto, theKey, cid, t)\n : await encodeCarFile([cid], t);\n } catch (e) {\n console.error(\"error creating car file\", e);\n throw e;\n }\n }\n\n protected makeFileCarHeader(result: FileTransactionMeta): TransactionMeta {\n const files: AnyLink[] = [];\n for (const [, meta] of Object.entries(result.files || {})) {\n if (meta && typeof meta === \"object\" && \"cid\" in meta && meta !== null) {\n files.push(meta.cid as AnyLink);\n }\n }\n return { ...result, files };\n }\n\n async updateCarLog<T>(cids: CarGroup, fp: CarHeader<T>, compact: boolean): Promise<void> {\n if (compact) {\n const previousCompactCid = fp.compact[fp.compact.length - 1];\n fp.compact.map((c) => c.toString()).forEach(this.seenCompacted.add, this.seenCompacted);\n this.carLog = [...uniqueCids([...this.carLog, ...fp.cars, cids], this.seenCompacted)];\n await this.removeCidsForCompact(previousCompactCid[0]);\n } else {\n this.carLog.unshift(cids);\n }\n }\n\n async removeCidsForCompact(cid: AnyLink) {\n const carHeader = await this.loadCarHeaderFromMeta({\n cars: [cid],\n } as unknown as DbMeta);\n for (const cids of carHeader.compact) {\n for (const cid of cids) {\n await (await this.carStore()).remove(cid);\n }\n }\n }\n\n // async flushCars() {\n // await this.ready\n // // for each cid in car log, make a dbMeta\n // for (const cid of this.carLog) {\n // const dbMeta = { car: cid, key: this.key || null } as DbMeta\n // await this.remoteWAL!.enqueue(dbMeta, { public: false })\n // }\n // }\n\n async *entries(cache = true): AsyncIterableIterator<AnyBlock> {\n await this.ready();\n if (cache) {\n for (const [, block] of this.getBlockCache) {\n yield block;\n }\n } else {\n for (const [, block] of this.getBlockCache) {\n yield block;\n }\n for (const cids of this.carLog) {\n for (const cid of cids) {\n const reader = await this.loadCar(cid);\n if (!reader) throw this.logger.Error().Ref(\"cid\", cid).Msg(\"missing car reader\").AsError();\n for await (const block of reader.blocks()) {\n const sCid = block.cid.toString();\n if (!this.getBlockCache.has(sCid)) {\n yield block;\n }\n }\n }\n }\n }\n }\n\n async getBlock(cid: AnyLink): Promise<AnyBlock | Falsy> {\n await this.ready();\n const sCid = cid.toString();\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n\n const getCarCid = async (carCid: AnyLink) => {\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n const reader = await this.loadCar(carCid);\n if (!reader) {\n throw this.logger.Error().Ref(\"cid\", carCid).Msg(\"missing car reader\").AsError();\n }\n await this.cacheCarReader(carCid.toString(), reader).catch(() => {\n return;\n });\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n throw this.logger.Error().Str(\"cid\", sCid).Msg(\"block not in reader\").AsError();\n };\n\n const getCompactCarCids = async (carCid: AnyLink) => {\n // console.log(\"getCompactCarCids\", carCid.toString())\n\n const reader = await this.loadCar(carCid);\n if (!reader) {\n throw this.logger.Error().Str(\"cid\", carCid.toString()).Msg(\"missing car reader\").AsError();\n }\n\n const header = await parseCarFile(reader, this.logger);\n\n const compacts = header.compact;\n\n let got: AnyBlock | undefined;\n const batchSize = 5;\n for (let i = 0; i < compacts.length; i += batchSize) {\n const promises: Promise<AnyBlock | undefined>[] = [];\n for (let j = i; j < Math.min(i + batchSize, compacts.length); j++) {\n for (const cid of compacts[j]) {\n promises.push(getCarCid(cid));\n }\n }\n try {\n got = await Promise.any(promises);\n } catch {\n // Ignore the error and continue with the next iteration\n }\n if (got) break;\n }\n\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n throw this.logger.Error().Str(\"cid\", sCid).Msg(\"block not in compact reader\").AsError();\n };\n\n let got;\n const batchSize = 5;\n for (let i = 0; i < this.carLog.length; i += batchSize) {\n const batch = this.carLog.slice(i, i + batchSize);\n const promises: Promise<AnyBlock | undefined>[] = batch.flatMap((slice) => slice.map(getCarCid));\n try {\n got = await Promise.any(promises);\n } catch {\n // Ignore the error and continue with the next iteration\n }\n if (got) break;\n }\n\n if (!got) {\n try {\n got = await getCompactCarCids(this.carLog[this.carLog.length - 1][0]);\n } catch {\n // Ignore the error and continue with the next iteration\n }\n }\n\n return got;\n }\n\n protected makeCarHeader<T>(meta: T, cars: CarLog, compact = false): CarHeader<T> {\n const coreHeader = compact ? { cars: [], compact: cars } : { cars, compact: [] };\n return { ...coreHeader, meta };\n }\n\n async loadCar(cid: AnyLink): Promise<CarReader> {\n if (!this.carStore) {\n throw this.logger.Error().Msg(\"car store not initialized\").AsError();\n }\n const loaded = await this.storesLoadCar(cid, await this.carStore(), this.remoteCarStore);\n return loaded;\n }\n\n //What if instead it returns an Array of CarHeader\n protected async storesLoadCar(cid: AnyLink, local: DataStore, remote?: DataStore, publicFiles?: boolean): Promise<CarReader> {\n const cidsString = cid.toString();\n if (!this.carReaders.has(cidsString)) {\n this.carReaders.set(\n cidsString,\n (async () => {\n let loadedCar: AnyBlock | undefined = undefined;\n try {\n //loadedCar now is an array of AnyBlocks\n this.logger.Debug().Str(\"cid\", cidsString).Msg(\"loading car\");\n loadedCar = await local.load(cid);\n this.logger.Debug().Bool(\"loadedCar\", loadedCar).Msg(\"loaded\");\n } catch (e) {\n if (remote) {\n const remoteCar = await remote.load(cid);\n if (remoteCar) {\n // todo test for this\n this.logger.Debug().Ref(\"cid\", remoteCar.cid).Msg(\"saving remote car locally\");\n await local.save(remoteCar);\n loadedCar = remoteCar;\n }\n } else {\n this.logger.Error().Str(\"cid\", cidsString).Err(e).Msg(\"loading car\");\n }\n }\n if (!loadedCar) {\n throw this.logger.Error().Url(local.url).Str(\"cid\", cidsString).Msg(\"missing car files\").AsError();\n }\n //This needs a fix as well as the fromBytes function expects a Uint8Array\n //Either we can merge the bytes or return an array of rawReaders\n const rawReader = await CarReader.fromBytes(loadedCar.bytes);\n const readerP = publicFiles ? Promise.resolve(rawReader) : this.ensureDecryptedReader(rawReader);\n\n const cachedReaderP = readerP.then(async (reader) => {\n await this.cacheCarReader(cidsString, reader).catch(() => {\n return;\n });\n return reader;\n });\n this.carReaders.set(cidsString, cachedReaderP);\n return readerP;\n })().catch((e) => {\n this.carReaders.delete(cidsString);\n throw e;\n }),\n );\n }\n return this.carReaders.get(cidsString) as Promise<CarReader>;\n }\n\n protected async ensureDecryptedReader(reader: CarReader): Promise<CarReader> {\n const theKey = await this._getKey();\n if (this.ebOpts.public || !(theKey && this.ebOpts.crypto)) {\n return reader;\n }\n const { blocks, root } = await decodeEncryptedCar(this.logger, this.ebOpts.crypto, theKey, reader);\n return {\n getRoots: () => [root],\n get: blocks.get.bind(blocks),\n blocks: blocks.entries.bind(blocks),\n } as unknown as CarReader;\n }\n\n protected async setKey(key: string) {\n if (this.key && this.key !== key)\n throw this.logger.Error().Str(\"this.key\", this.key).Str(\"key\", key).Msg(\"setting key\").AsError();\n this.key = key;\n const encoder = new TextEncoder();\n const data = encoder.encode(key);\n const hashBuffer = await this.ebOpts.crypto.digestSHA256(data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n this.keyId = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n }\n\n protected async getMoreReaders(cids: AnyLink[]) {\n const limit = pLimit(5);\n const missing = cids.filter((cid) => !this.carReaders.has(cid.toString()));\n await Promise.all(missing.map((cid) => limit(() => this.loadCar(cid))));\n }\n}\n","import type { CID, Link, Version } from \"multiformats\";\nimport { DataStore, MetaStore, RemoteWAL } from \"./store.js\";\nimport type { Loadable } from \"./loader.js\";\nimport { DocFileMeta, Falsy } from \"../types.js\";\nimport { CarTransaction } from \"./transaction.js\";\n\nexport type AnyLink = Link<unknown, number, number, Version>;\nexport type CarGroup = AnyLink[];\nexport type CarLog = CarGroup[];\nexport type AnyAnyLink = Link<unknown, number, number, Version>;\n\nexport type AnyLinkFn = (cid: AnyLink) => Promise<AnyBlock | undefined>;\n\nexport interface AnyBlock {\n readonly cid: Link<unknown, number, number, Version>;\n readonly bytes: Uint8Array;\n}\n\nexport interface CIDBlock {\n readonly cid: CID<unknown, number, number, Version>;\n readonly bytes: Uint8Array;\n}\n\nexport function toCIDBlock(block: AnyBlock): CIDBlock {\n return block as CIDBlock;\n}\nexport interface AnyAnyBlock {\n readonly cid: AnyAnyLink;\n readonly bytes: Uint8Array;\n}\n\nexport interface EncryptOpts {\n readonly key: ArrayBuffer;\n readonly cid: AnyLink;\n readonly bytes: Uint8Array;\n}\n\nexport interface DecryptOptsValue {\n readonly bytes: Uint8Array;\n readonly iv: Uint8Array;\n}\n\nexport interface DecryptOpts {\n readonly key: ArrayBuffer;\n readonly value: DecryptOptsValue;\n}\n\nexport interface AnyDecodedBlock {\n readonly cid: AnyLink;\n readonly bytes: Uint8Array;\n readonly value: DecryptOptsValue;\n}\n\nexport interface CarMakeable {\n entries(): Iterable<AnyBlock>;\n get(cid: AnyLink): Promise<AnyBlock | undefined>;\n}\n\nexport interface CarHeader<T> {\n readonly cars: CarLog;\n readonly compact: CarLog;\n readonly meta: T;\n}\n\n// type NestedData =\n// | Uint8Array\n// | string\n// | number\n// | boolean\n// | undefined\n// | null\n// | AnyLink\n// | NestedData[]\n// | { [key: string]: NestedData };\n\nexport interface TransactionWrapper<M extends TransactionMeta> {\n meta: M;\n cars?: CarGroup;\n t: CarTransaction;\n}\n\nexport type TransactionMeta = unknown;\n//CRDTMeta | IndexTransactionMeta | FileTransactionMeta;\n\n// export interface MakeCodecCrypto {\n// subtle: {\n// decrypt: (algo: { name: string; iv: Uint8Array; tagLength: number }, key: CryptoKey, data: Uint8Array) => Promise<ArrayBuffer>;\n// encrypt: (algo: { name: string; iv: Uint8Array; tagLength: number }, key: CryptoKey, data: Uint8Array) => Promise<ArrayBuffer>;\n// };\n// }\n\nexport interface FPJsonWebKey {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kty?: string;\n n?: string;\n oth?: RsaOtherPrimesInfo[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n}\n\nexport type FPKeyFormat = \"jwk\" | \"pkcs8\" | \"raw\" | \"spki\";\nexport type FPKeyUsage = \"decrypt\" | \"deriveBits\" | \"deriveKey\" | \"encrypt\" | \"sign\" | \"unwrapKey\" | \"verify\" | \"wrapKey\";\n\nexport interface FPAlgorithm {\n name: string;\n}\nexport type FPAlgorithmIdentifier = FPAlgorithm | string;\n\nexport interface FPRsaHashedImportParams extends FPAlgorithm {\n hash: FPAlgorithmIdentifier;\n}\n\nexport type FPNamedCurve = string;\nexport interface FPEcKeyImportParams extends FPAlgorithm {\n namedCurve: FPNamedCurve;\n}\n\nexport interface FPHmacImportParams extends FPAlgorithm {\n hash: FPAlgorithmIdentifier;\n length?: number;\n}\n\nexport interface FPAesKeyAlgorithm extends FPAlgorithm {\n length: number;\n}\n\nexport type FPKeyType = \"private\" | \"public\" | \"secret\";\n\nexport interface FPCryptoKey {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */\n readonly algorithm: FPAlgorithm;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */\n readonly extractable: boolean;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */\n readonly type: FPKeyType;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */\n readonly usages: FPKeyUsage[];\n}\n\ninterface FPArrayBufferTypes {\n ArrayBuffer: ArrayBuffer;\n}\ntype FPArrayBufferLike = FPArrayBufferTypes[keyof FPArrayBufferTypes];\n\nexport interface FPArrayBufferView {\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n buffer: FPArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n byteOffset: number;\n}\n\nexport type FPBufferSource = FPArrayBufferView | ArrayBuffer;\nexport interface CryptoOpts {\n importKey(\n format: FPKeyFormat,\n keyData: FPJsonWebKey | FPBufferSource,\n algorithm: FPAlgorithmIdentifier | FPRsaHashedImportParams | FPEcKeyImportParams | FPHmacImportParams | FPAesKeyAlgorithm,\n extractable: boolean,\n keyUsages: FPKeyUsage[],\n ): Promise<FPCryptoKey>;\n\n //(format: \"raw\", key: ArrayBuffer, algo: string, extractable: boolean, usages: string[]) => Promise<CryptoKey>;\n readonly decrypt: (\n algo: { name: string; iv: Uint8Array; tagLength: number },\n key: FPCryptoKey,\n data: Uint8Array,\n ) => Promise<ArrayBuffer>;\n readonly encrypt: (\n algo: { name: string; iv: Uint8Array; tagLength: number },\n key: FPCryptoKey,\n data: Uint8Array,\n ) => Promise<ArrayBuffer>;\n readonly digestSHA256: (data: Uint8Array) => Promise<ArrayBuffer>;\n readonly randomBytes: (size: number) => Uint8Array;\n}\n\nexport interface BlobLike {\n /**\n * Returns a ReadableStream which yields the Blob data.\n */\n stream: () => ReadableStream;\n}\n\nexport interface StoreFactory {\n makeMetaStore?: (loader: Loadable) => Promise<MetaStore>;\n makeDataStore?: (loader: Loadable) => Promise<DataStore>;\n makeRemoteWAL?: (loader: Loadable) => Promise<RemoteWAL>;\n\n encodeFile?: (blob: BlobLike) => Promise<{ cid: AnyLink; blocks: AnyBlock[] }>;\n decodeFile?: (blocks: unknown, cid: AnyLink, meta: DocFileMeta) => Promise<File>;\n}\n\nexport interface StoreOpts extends StoreFactory {\n readonly isIndex?: string; // index prefix\n readonly stores?: {\n // string means local storage\n // URL means schema selects the storeType\n readonly base?: string | URL;\n\n readonly meta?: string | URL;\n readonly data?: string | URL;\n readonly index?: string | URL;\n readonly remoteWAL?: string | URL;\n };\n}\n\nexport interface TestStore {\n // readonly url: URL;\n get(url: URL, key: string): Promise<Uint8Array>;\n // delete the underlying store and all its data\n // delete(): Promise<void>;\n}\n\nexport interface StoreRuntime {\n // the factories should produce ready-to-use stores\n // which means they have to call start() on the store\n // to fullfill lifecycle requirements\n // to release resources, like one database connection\n // for all stores a refcount on close() should be used\n makeMetaStore(loader: Loadable): Promise<MetaStore>;\n makeDataStore(loader: Loadable): Promise<DataStore>;\n makeRemoteWAL(loader: Loadable): Promise<RemoteWAL>;\n encodeFile(blob: BlobLike): Promise<{ cid: AnyLink; blocks: AnyBlock[] }>;\n decodeFile(blocks: unknown, cid: AnyLink, meta: DocFileMeta): Promise<File>;\n}\n\nexport interface CommitOpts {\n readonly noLoader?: boolean;\n readonly compact?: boolean;\n readonly public?: boolean;\n}\n\nexport interface DbMeta {\n readonly cars: CarGroup;\n key?: string;\n}\n\nexport interface UploadMetaFnParams {\n readonly name: string;\n readonly branch: string;\n}\n\nexport type FnParamTypes = \"data\" | \"file\";\n\nexport interface UploadDataFnParams {\n readonly type: FnParamTypes;\n readonly name: string;\n readonly car: string;\n readonly size: string;\n}\n\nexport interface DownloadDataFnParams {\n readonly type: FnParamTypes;\n readonly name: string;\n readonly car: string;\n}\n\nexport interface DownloadMetaFnParams {\n readonly name: string;\n readonly branch: string;\n}\n\nexport interface Connection {\n readonly loader?: Loadable;\n readonly loaded: Promise<void>;\n connectMeta({ loader }: { loader?: Loadable }): void;\n connectStorage({ loader }: { loader?: Loadable }): void;\n\n metaUpload(bytes: Uint8Array, params: UploadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n dataUpload(bytes: Uint8Array, params: UploadDataFnParams, opts?: { public?: boolean }): Promise<void>;\n metaDownload(params: DownloadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n dataDownload(params: DownloadDataFnParams): Promise<Uint8Array | Falsy>;\n}\n","import { CID } from \"multiformats\";\nimport { Block, encode, decode } from \"multiformats/block\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as raw from \"multiformats/codecs/raw\";\nimport * as CBW from \"@ipld/car/buffer-writer\";\nimport * as codec from \"@ipld/dag-cbor\";\nimport { CarReader } from \"@ipld/car\";\nimport type { Logger } from \"@adviser/cement\";\n\nimport { AnyBlock, AnyLink, CarHeader, CarMakeable } from \"./types.js\";\n\nexport async function encodeCarFile(roots: AnyLink[], t: CarMakeable): Promise<AnyBlock> {\n let size = 0;\n const headerSize = CBW.headerLength({ roots } as { roots: CID<unknown, number, number, 1>[] });\n size += headerSize;\n for (const { cid, bytes } of t.entries()) {\n size += CBW.blockLength({ cid, bytes } as Block<unknown, number, number, 1>);\n }\n const buffer = new Uint8Array(size);\n const writer = CBW.createWriter(buffer, { headerSize });\n\n for (const r of roots) {\n writer.addRoot(r as CID<unknown, number, number, 1>);\n }\n\n for (const { cid, bytes } of t.entries()) {\n writer.write({ cid, bytes } as Block<unknown, number, number, 1>);\n }\n writer.close();\n return await encode({ value: writer.bytes, hasher, codec: raw });\n}\n\nexport async function encodeCarHeader<T>(fp: CarHeader<T>) {\n return (await encode({\n value: { fp },\n hasher,\n codec,\n })) as AnyBlock;\n}\n\nexport async function parseCarFile<T>(reader: CarReader, logger: Logger): Promise<CarHeader<T>> {\n const roots = await reader.getRoots();\n const header = await reader.get(roots[0]);\n if (!header) throw logger.Error().Msg(\"missing header block\").AsError();\n const { value } = await decode({ bytes: header.bytes, hasher, codec });\n const fpvalue = value as { readonly fp: CarHeader<T> };\n // @jchris where is the fp attribute coming from?\n if (fpvalue && !fpvalue.fp) {\n throw logger.Error().Msg(\"missing fp\").AsError();\n }\n return fpvalue.fp;\n}\n","import { sha256 } from \"multiformats/hashes/sha2\";\nimport { CID } from \"multiformats\";\nimport { encode, decode, create as mfCreate } from \"multiformats/block\";\nimport type { MultihashHasher, ToString } from \"multiformats\";\n\nimport type { CarReader } from \"@ipld/car\";\nimport * as dagcbor from \"@ipld/dag-cbor\";\n\nimport { MemoryBlockstore } from \"@web3-storage/pail/block\";\n\n// @ts-expect-error \"prolly-trees\" has no types\nimport { bf } from \"prolly-trees/utils\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { nocache as cache } from \"prolly-trees/cache\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { create, load } from \"prolly-trees/cid-set\";\n\nimport { encodeCarFile } from \"./loader-helpers.js\";\nimport { makeCodec } from \"./encrypt-codec.js\";\nimport type { AnyLinkFn, AnyBlock, CarMakeable, AnyLink, AnyDecodedBlock, CryptoOpts } from \"./types.js\";\nimport { Logger } from \"@adviser/cement\";\n\nfunction carLogIncludesGroup(list: AnyLink[], cidMatch: AnyLink) {\n return list.some((cid: AnyLink) => {\n return cid.toString() === cidMatch.toString();\n });\n}\n\nfunction makeEncDec(logger: Logger, crypto: CryptoOpts, randomBytes: (size: number) => Uint8Array) {\n const codec = makeCodec(logger, crypto, randomBytes);\n\n const encrypt = async function* ({\n get,\n cids,\n hasher,\n key,\n cache,\n chunker,\n root,\n }: {\n get: (cid: AnyLink) => Promise<AnyBlock | undefined>;\n key: ArrayBuffer;\n cids: AnyLink[];\n hasher: MultihashHasher<number>;\n chunker: (bytes: Uint8Array) => AsyncGenerator<Uint8Array>;\n cache: (cid: AnyLink) => Promise<AnyBlock>;\n root: AnyLink;\n }): AsyncGenerator<unknown, void, unknown> {\n const set = new Set<ToString<AnyLink>>();\n let eroot;\n if (!carLogIncludesGroup(cids, root)) cids.push(root);\n for (const cid of cids) {\n const unencrypted = await get(cid);\n if (!unencrypted) throw logger.Error().Ref(\"cid\", cid).Msg(\"missing cid block\").AsError();\n const encrypted = await codec.encrypt({ ...unencrypted, key });\n const block = await encode({ ...encrypted, codec, hasher });\n yield block;\n set.add(block.cid.toString());\n if (unencrypted.cid.equals(root)) eroot = block.cid;\n }\n if (!eroot) throw logger.Error().Msg(\"cids does not include root\").AsError();\n const list = [...set].map((s) => CID.parse(s));\n let last;\n for await (const node of create({ list, get, cache, chunker, hasher, codec: dagcbor })) {\n const block = (await node.block) as AnyBlock;\n yield block;\n last = block;\n }\n if (!last) throw logger.Error().Msg(\"missing last block\").AsError();\n const head = [eroot, last.cid];\n const block = await encode({ value: head, codec: dagcbor, hasher });\n yield block;\n };\n\n const decrypt = async function* ({\n root,\n get,\n key,\n cache,\n chunker,\n hasher,\n }: {\n root: AnyLink;\n get: (cid: AnyLink) => Promise<AnyBlock | undefined>;\n key: ArrayBuffer;\n cache: (cid: AnyLink) => Promise<AnyBlock>;\n chunker: (bytes: Uint8Array) => AsyncGenerator<Uint8Array>;\n hasher: MultihashHasher<number>;\n }): AsyncGenerator<AnyBlock, void, undefined> {\n const getWithDecode = async (cid: AnyLink) =>\n get(cid).then(async (block) => {\n if (!block) return;\n const decoded = await decode({ ...block, codec: dagcbor, hasher });\n return decoded;\n });\n const getWithDecrypt = async (cid: AnyLink) =>\n get(cid).then(async (block) => {\n if (!block) return;\n const decoded = await decode({ ...block, codec, hasher });\n return decoded;\n });\n const decodedRoot = await getWithDecode(root);\n if (!decodedRoot) throw logger.Error().Msg(\"missing root\").AsError();\n if (!decodedRoot.bytes) throw logger.Error().Msg(\"missing bytes\").AsError();\n const {\n value: [eroot, tree],\n } = decodedRoot as { value: [AnyLink, AnyLink] };\n const rootBlock = (await get(eroot)) as AnyDecodedBlock;\n if (!rootBlock) throw logger.Error().Msg(\"missing root block\").AsError();\n const cidset = await load({ cid: tree, get: getWithDecode, cache, chunker, codec, hasher });\n const { result: nodes } = (await cidset.getAllEntries()) as { result: { cid: CID }[] };\n const unwrap = async (eblock?: AnyDecodedBlock) => {\n if (!eblock) throw logger.Error().Msg(\"missing block\").AsError();\n if (!eblock.value) {\n eblock = await decode({ ...eblock, codec, hasher });\n if (!eblock.value) throw logger.Error().Msg(\"missing value\").AsError();\n }\n const { bytes, cid } = await codec.decrypt({ ...eblock, key }).catch((e) => {\n throw e;\n });\n const block = await mfCreate({ cid, bytes, hasher, codec });\n return block;\n };\n const promises = [];\n for (const { cid } of nodes) {\n if (!rootBlock.cid.equals(cid)) promises.push(getWithDecrypt(cid).then(unwrap));\n }\n yield* promises;\n yield unwrap(rootBlock);\n };\n return { encrypt, decrypt };\n}\nconst chunker = bf(30);\n\nfunction hexStringToUint8Array(hexString: string) {\n const length = hexString.length;\n const uint8Array = new Uint8Array(length / 2);\n for (let i = 0; i < length; i += 2) {\n uint8Array[i / 2] = parseInt(hexString.substring(i, i + 2), 16);\n }\n return uint8Array;\n}\n\nexport async function encryptedEncodeCarFile(\n logger: Logger,\n crypto: CryptoOpts,\n key: string,\n rootCid: AnyLink,\n t: CarMakeable,\n): Promise<AnyBlock> {\n const encryptionKey = hexStringToUint8Array(key);\n const encryptedBlocks = new MemoryBlockstore();\n const cidsToEncrypt = [] as AnyLink[];\n for (const { cid, bytes } of t.entries()) {\n cidsToEncrypt.push(cid);\n const g = await t.get(cid);\n if (!g) throw logger.Error().Ref(\"cid\", cid).Int(\"bytes\", bytes.length).Msg(\"missing cid block\").AsError();\n }\n let last: AnyBlock | null = null;\n const { encrypt } = makeEncDec(logger, crypto, crypto.randomBytes);\n\n for await (const block of encrypt({\n cids: cidsToEncrypt,\n get: t.get.bind(t),\n key: encryptionKey,\n hasher: sha256,\n chunker,\n cache,\n root: rootCid,\n }) as AsyncGenerator<AnyBlock, void, unknown>) {\n await encryptedBlocks.put(block.cid, block.bytes);\n last = block;\n }\n if (!last) throw logger.Error().Msg(\"no blocks encrypted\").AsError();\n const encryptedCar = await encodeCarFile([last.cid], encryptedBlocks);\n return encryptedCar;\n}\n\nexport async function decodeEncryptedCar(logger: Logger, crypto: CryptoOpts, key: string, reader: CarReader) {\n const roots = await reader.getRoots();\n const root = roots[0];\n return await decodeCarBlocks(logger, crypto, root, reader.get.bind(reader) as AnyLinkFn, key);\n}\nasync function decodeCarBlocks(\n logger: Logger,\n crypto: CryptoOpts,\n root: AnyLink,\n get: (cid: AnyLink) => Promise<AnyBlock | undefined>,\n keyMaterial: string,\n): Promise<{ blocks: MemoryBlockstore; root: AnyLink }> {\n const decryptionKeyUint8 = hexStringToUint8Array(keyMaterial);\n const decryptionKey = decryptionKeyUint8.buffer.slice(0, decryptionKeyUint8.byteLength);\n\n const decryptedBlocks = new MemoryBlockstore();\n let last: AnyBlock | null = null;\n\n const { decrypt } = makeEncDec(logger, crypto, crypto.randomBytes);\n\n for await (const block of decrypt({\n root,\n get,\n key: decryptionKey,\n hasher: sha256,\n chunker,\n cache,\n })) {\n await decryptedBlocks.put(block.cid, block.bytes);\n last = block;\n }\n if (!last) throw logger.Error().Msg(\"no blocks decrypted\").AsError();\n return { blocks: decryptedBlocks, root: last.cid };\n}\n","import { CID } from \"multiformats\";\nimport type { AnyLink, CryptoOpts, DecryptOpts, EncryptOpts } from \"./types.js\";\nimport { ensureLogger } from \"../utils.js\";\nimport { Logger } from \"@adviser/cement\";\n\nexport function makeCodec(ilogger: Logger, crypto: CryptoOpts, randomBytes: (size: number) => Uint8Array) {\n const logger = ensureLogger(ilogger, \"makeCodec\");\n const enc32 = (value: number) => {\n value = +value;\n const buff = new Uint8Array(4);\n buff[3] = value >>> 24;\n buff[2] = value >>> 16;\n buff[1] = value >>> 8;\n buff[0] = value & 0xff;\n return buff;\n };\n\n const readUInt32LE = (buffer: Uint8Array) => {\n const offset = buffer.byteLength - 4;\n return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16)) + buffer[offset + 3] * 0x1000000;\n };\n\n const concat = (buffers: (ArrayBuffer | Uint8Array)[]) => {\n const uint8Arrays = buffers.map((b) => (b instanceof ArrayBuffer ? new Uint8Array(b) : b));\n const totalLength = uint8Arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n\n let offset = 0;\n for (const arr of uint8Arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n\n return result;\n };\n\n const encode = ({ iv, bytes }: { iv: Uint8Array; bytes: Uint8Array }) => concat([iv, bytes]);\n const decode = (bytes: Uint8Array) => {\n const iv = bytes.subarray(0, 12);\n bytes = bytes.slice(12);\n return { iv, bytes };\n };\n\n const code = 0x300000 + 1337;\n\n async function subtleKey(key: ArrayBuffer) {\n return await crypto.importKey(\n \"raw\", // raw or jwk\n key, // raw data\n \"AES-GCM\",\n false, // extractable\n [\"encrypt\", \"decrypt\"],\n );\n }\n\n const decrypt = async ({ key, value }: DecryptOpts): Promise<{ cid: AnyLink; bytes: Uint8Array }> => {\n const { bytes: inBytes, iv } = value;\n const cryKey = await subtleKey(key);\n const deBytes = await crypto.decrypt(\n {\n name: \"AES-GCM\",\n iv,\n tagLength: 128,\n },\n cryKey,\n inBytes,\n );\n const bytes = new Uint8Array(deBytes);\n const len = readUInt32LE(bytes.subarray(0, 4));\n const cid = CID.decode(bytes.subarray(4, 4 + len));\n return { cid, bytes: bytes.subarray(4 + len) };\n };\n const encrypt = async ({ key, cid, bytes }: EncryptOpts) => {\n const len = enc32(cid.bytes.byteLength);\n const iv = randomBytes(12);\n const msg = concat([len, cid.bytes, bytes]);\n try {\n const cryKey = await subtleKey(key);\n const deBytes = await crypto.encrypt(\n {\n name: \"AES-GCM\",\n iv,\n tagLength: 128,\n },\n cryKey,\n msg,\n );\n bytes = new Uint8Array(deBytes);\n } catch (e) {\n throw logger.Error().Err(e).Msg(\"encrypt failed\").AsError();\n }\n return { value: { bytes, iv } };\n };\n\n const cryptoFn = (key: Uint8Array) => {\n return { encrypt: (opts: EncryptOpts) => encrypt({ ...opts, key }), decrypt: (opts: DecryptOpts) => decrypt({ ...opts, key }) };\n };\n\n const name = \"jchris@encrypted-block:aes-gcm\";\n\n return { encode, decode, code, name, encrypt, decrypt, crypto: cryptoFn };\n}\n","import { MemoryBlockstore } from \"@web3-storage/pail/block\";\nimport { BlockFetcher as BlockFetcherApi } from \"@web3-storage/pail/api\";\n\nimport {\n AnyAnyLink,\n AnyBlock,\n AnyLink,\n CarMakeable,\n DbMeta,\n StoreRuntime,\n StoreOpts,\n TransactionMeta,\n TransactionWrapper,\n} from \"./types.js\";\n\nimport { Loader } from \"./loader.js\";\nimport type { CID, Block, Version } from \"multiformats\";\nimport { CryptoOpts } from \"./types.js\";\nimport { falsyToUndef } from \"../types.js\";\nimport { toCryptoOpts } from \"../runtime/crypto.js\";\nimport { toStoreRuntime } from \"./store-factory.js\";\nimport { Logger } from \"@adviser/cement\";\nimport { ensureLogger } from \"../utils.js\";\n\nexport type BlockFetcher = BlockFetcherApi;\n\nexport class CarTransaction extends MemoryBlockstore implements CarMakeable {\n readonly parent: BaseBlockstore;\n constructor(parent: BaseBlockstore, opts = { add: true }) {\n super();\n if (opts.add) {\n parent.transactions.add(this);\n }\n this.parent = parent;\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyLink): Promise<Block<T, C, A, V> | undefined> {\n return ((await this.superGet(cid)) || falsyToUndef(await this.parent.get(cid))) as Block<T, C, A, V>;\n }\n\n async superGet(cid: AnyLink): Promise<AnyBlock | undefined> {\n return super.get(cid);\n }\n}\n\nexport function defaultedBlockstoreRuntime(\n opts: BlockstoreOpts,\n component: string,\n ctx?: Record<string, unknown>,\n): BlockstoreRuntime {\n const logger = ensureLogger(opts, component, ctx);\n const store = opts.store || {};\n return {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n applyMeta: (meta: TransactionMeta, snap?: boolean): Promise<void> => {\n return Promise.resolve();\n },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n compact: async (blocks: CompactionFetcher) => {\n return {} as unknown as TransactionMeta;\n },\n autoCompact: 100,\n public: false,\n name: undefined,\n threshold: 1000 * 1000,\n ...opts,\n logger,\n crypto: toCryptoOpts(opts.crypto),\n store,\n storeRuntime: toStoreRuntime(store, logger),\n };\n}\n\nconst blockstoreFactory = function (opts: BlockstoreOpts): BaseBlockstore | EncryptedBlockstore {\n if (opts.name) {\n return new EncryptedBlockstore(opts);\n } else {\n return new BaseBlockstore(opts);\n }\n};\n\nexport { blockstoreFactory };\n\nexport class BaseBlockstore implements BlockFetcher {\n readonly transactions = new Set<CarTransaction>();\n readonly ebOpts: BlockstoreRuntime;\n\n readonly loader?: Loader;\n readonly name?: string;\n\n // ready: Promise<void>;\n ready(): Promise<void> {\n return Promise.resolve();\n }\n\n async close(): Promise<void> {\n // no-op\n }\n\n async destroy(): Promise<void> {\n // no-op\n }\n\n readonly logger: Logger;\n constructor(ebOpts: BlockstoreOpts = {}) {\n // console.log(\"BaseBlockstore\", ebOpts)\n this.ebOpts = defaultedBlockstoreRuntime(ebOpts, \"BaseBlockstore\");\n this.logger = this.ebOpts.logger;\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyAnyLink): Promise<Block<T, C, A, V> | undefined> {\n if (!cid) throw this.logger.Error().Msg(\"required cid\").AsError();\n for (const f of this.transactions) {\n // if (Math.random() < 0.001) console.log('get', cid.toString(), this.transactions.size)\n const v = await f.superGet(cid);\n if (v) return v as Block<T, C, A, V>;\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async put(cid: AnyAnyLink, block: Uint8Array): Promise<void> {\n throw this.logger.Error().Msg(\"use a transaction to put\").AsError();\n }\n\n lastTxMeta?: unknown; // TransactionMeta\n\n async transaction<M extends TransactionMeta>(\n fn: (t: CarTransaction) => Promise<M>,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _opts = {},\n ): Promise<TransactionWrapper<M>> {\n const t = new CarTransaction(this);\n const done: M = await fn(t);\n this.lastTxMeta = done;\n return { t, meta: done };\n }\n\n async *entries(): AsyncIterableIterator<AnyBlock> {\n const seen = new Set<string>();\n for (const t of this.transactions) {\n for await (const blk of t.entries()) {\n if (seen.has(blk.cid.toString())) continue;\n seen.add(blk.cid.toString());\n yield blk;\n }\n }\n }\n}\n\nexport class EncryptedBlockstore extends BaseBlockstore {\n readonly name: string;\n readonly loader: Loader;\n\n ready(): Promise<void> {\n return this.loader.ready();\n }\n\n close(): Promise<void> {\n return this.loader.close();\n }\n\n destroy(): Promise<void> {\n return this.loader.destroy();\n }\n\n compacting = false;\n readonly logger: Logger;\n\n constructor(ebOpts: BlockstoreOpts) {\n super(ebOpts);\n this.logger = ensureLogger(ebOpts, \"EncryptedBlockstore\");\n const { name } = ebOpts;\n if (!name) {\n throw this.logger.Error().Msg(\"name required\").AsError();\n }\n this.name = name;\n this.loader = new Loader(this.name, ebOpts);\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyAnyLink): Promise<Block<T, C, A, V> | undefined> {\n const got = await super.get(cid);\n if (got) return got as Block<T, C, A, V>;\n if (!this.loader) {\n return;\n }\n return falsyToUndef(await this.loader.getBlock(cid)) as Block<T, C, A, V>;\n }\n\n async transaction<M extends TransactionMeta>(\n fn: (t: CarTransaction) => Promise<M>,\n opts = { noLoader: false },\n ): Promise<TransactionWrapper<M>> {\n const { t, meta: done } = await super.transaction<M>(fn);\n const cars = await this.loader.commit<M>(t, done, opts);\n if (this.ebOpts.autoCompact && this.loader.carLog.length > this.ebOpts.autoCompact) {\n setTimeout(() => void this.compact(), 10);\n }\n if (cars) {\n this.transactions.delete(t);\n return { meta: done, cars, t };\n }\n throw this.logger.Error().Msg(\"failed to commit car files\").AsError();\n }\n\n async getFile(car: AnyLink, cid: AnyLink, isPublic = false): Promise<Uint8Array> {\n await this.ready();\n if (!this.loader) throw this.logger.Error().Msg(\"loader required to get file, database must be named\").AsError();\n const reader = await this.loader.loadFileCar(car, isPublic);\n const block = await reader.get(cid as CID);\n if (!block) throw this.logger.Error().Str(\"cid\", cid.toString()).Msg(`Missing block`).AsError();\n return block.bytes;\n }\n\n async compact() {\n await this.ready();\n if (!this.loader) throw this.logger.Error().Msg(\"loader required to compact\").AsError();\n if (this.loader.carLog.length < 2) return;\n const compactFn = this.ebOpts.compact || ((blocks: CompactionFetcher) => this.defaultCompact(blocks, this.logger));\n if (!compactFn || this.compacting) return;\n const blockLog = new CompactionFetcher(this);\n this.compacting = true;\n const meta = await compactFn(blockLog);\n await this.loader?.commit(blockLog.loggedBlocks, meta, {\n compact: true,\n noLoader: true,\n });\n this.compacting = false;\n }\n\n async defaultCompact(blocks: CompactionFetcher, logger: Logger): Promise<TransactionMeta> {\n // console.log('eb compact')\n if (!this.loader) {\n throw logger.Error().Msg(\"no loader\").AsError();\n }\n if (!this.lastTxMeta) {\n throw logger.Error().Msg(\"no lastTxMeta\").AsError();\n }\n for await (const blk of this.loader.entries(false)) {\n blocks.loggedBlocks.putSync(blk.cid, blk.bytes);\n }\n for (const t of this.transactions) {\n for await (const blk of t.entries()) {\n blocks.loggedBlocks.putSync(blk.cid, blk.bytes);\n }\n }\n return this.lastTxMeta as TransactionMeta;\n }\n\n async *entries(): AsyncIterableIterator<AnyBlock> {\n // const seen = new Set<string>();\n for await (const blk of this.loader.entries()) {\n // if (seen.has(blk.cid.toString())) continue\n // seen.add(blk.cid.toString())\n yield blk;\n }\n }\n}\n\nexport class CompactionFetcher implements BlockFetcher {\n blockstore: EncryptedBlockstore;\n // loader: Loader | null = null\n loggedBlocks: CarTransaction;\n\n constructor(blocks: EncryptedBlockstore) {\n this.blockstore = blocks;\n // this.loader = blocks.loader\n this.loggedBlocks = new CarTransaction(blocks);\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyLink): Promise<Block<T, C, A, V> | undefined> {\n const block = await this.blockstore.get(cid);\n if (block) this.loggedBlocks.putSync(cid, block.bytes);\n return falsyToUndef(block) as Block<T, C, A, V>;\n }\n}\n\nexport type CompactFn = (blocks: CompactionFetcher) => Promise<TransactionMeta>;\n\nexport interface BlockstoreOpts {\n readonly logger?: Logger;\n readonly applyMeta?: (meta: TransactionMeta, snap?: boolean) => Promise<void>;\n readonly compact?: CompactFn;\n readonly autoCompact?: number;\n readonly crypto?: CryptoOpts;\n readonly store?: StoreOpts;\n readonly public?: boolean;\n readonly meta?: DbMeta;\n readonly name?: string;\n readonly threshold?: number;\n}\n\nexport interface BlockstoreRuntime {\n readonly logger: Logger;\n readonly applyMeta: (meta: TransactionMeta, snap?: boolean) => Promise<void>;\n readonly compact: CompactFn;\n readonly autoCompact: number;\n readonly crypto: CryptoOpts;\n readonly store: StoreOpts;\n readonly storeRuntime: StoreRuntime;\n readonly public: boolean;\n readonly meta?: DbMeta;\n readonly name?: string;\n readonly threshold: number;\n}\n","type QueueFunction = () => Promise<void>;\n\nexport class CommitQueue<T = void> {\n readonly queue: QueueFunction[] = [];\n processing = false;\n\n async enqueue(fn: () => Promise<T>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const queueFn = async () => {\n try {\n resolve(await fn());\n } catch (e) {\n reject(e);\n } finally {\n this.processing = false;\n this.processNext();\n }\n };\n this.queue.push(queueFn);\n if (!this.processing) {\n this.processNext();\n }\n });\n }\n\n processNext() {\n if (this.queue.length > 0 && !this.processing) {\n this.processing = true;\n const queueFn = this.queue.shift();\n if (queueFn) {\n queueFn();\n }\n }\n }\n}\n","import {\n type ClockHead,\n type DocUpdate,\n type MapFn,\n type IndexUpdate,\n type QueryOpts,\n type IdxMeta,\n type DocFragment,\n type IdxMetaMap,\n type IndexKeyType,\n type IndexRows,\n type DocTypes,\n type IndexUpdateString,\n throwFalsy,\n IndexTransactionMeta,\n} from \"./types.js\";\nimport { BaseBlockstore } from \"./blockstore/index.js\";\n\nimport {\n bulkIndex,\n indexEntriesForChanges,\n byIdOpts,\n byKeyOpts,\n IndexTree,\n applyQuery,\n encodeRange,\n encodeKey,\n loadIndex,\n IndexDocString,\n CompareKey,\n} from \"./indexer-helpers.js\";\nimport { CRDT } from \"./crdt.js\";\nimport { ensureLogger } from \"./utils.js\";\nimport { Logger } from \"@adviser/cement\";\n\nexport function index<K extends IndexKeyType = string, T extends DocTypes = NonNullable<unknown>, R extends DocFragment = T>(\n { _crdt }: { _crdt: CRDT<T> | CRDT<NonNullable<unknown>> },\n name: string,\n mapFn?: MapFn<T>,\n meta?: IdxMeta,\n): Index<K, T, R> {\n if (mapFn && meta) throw _crdt.logger.Error().Msg(\"cannot provide both mapFn and meta\").AsError();\n if (mapFn && mapFn.constructor.name !== \"Function\") throw _crdt.logger.Error().Msg(\"mapFn must be a function\").AsError();\n if (_crdt.indexers.has(name)) {\n const idx = _crdt.indexers.get(name) as unknown as Index<K, T>;\n idx.applyMapFn(name, mapFn, meta);\n } else {\n const idx = new Index<K, T>(_crdt, name, mapFn, meta);\n _crdt.indexers.set(name, idx as unknown as Index<K, NonNullable<unknown>, NonNullable<unknown>>);\n }\n return _crdt.indexers.get(name) as unknown as Index<K, T, R>;\n}\n\n// interface ByIdIndexIten<K extends IndexKeyType> {\n// readonly key: K;\n// readonly value: [K, K];\n// }\n\nexport class Index<K extends IndexKeyType, T extends DocTypes, R extends DocFragment = T> {\n readonly blockstore: BaseBlockstore;\n readonly crdt: CRDT<T>;\n name: string;\n mapFn?: MapFn<T>;\n mapFnString = \"\";\n byKey = new IndexTree<K, R>();\n byId = new IndexTree<K, R>();\n indexHead?: ClockHead;\n includeDocsDefault = false;\n initError?: Error;\n\n ready(): Promise<void> {\n return Promise.all([this.blockstore.ready(), this.crdt.ready()]).then(() => {\n /* noop */\n });\n }\n\n close(): Promise<void> {\n return Promise.all([this.blockstore.close(), this.crdt.close()]).then(() => {\n /* noop */\n });\n }\n destroy(): Promise<void> {\n return Promise.all([this.blockstore.destroy(), this.crdt.destroy()]).then(() => {\n /* noop */\n });\n }\n\n readonly logger: Logger;\n\n constructor(crdt: CRDT<T> | CRDT<NonNullable<unknown>>, name: string, mapFn?: MapFn<T>, meta?: IdxMeta) {\n this.logger = ensureLogger(crdt.logger, \"Index\");\n this.blockstore = crdt.indexBlockstore;\n this.crdt = crdt as CRDT<T>;\n this.applyMapFn(name, mapFn, meta);\n this.name = name;\n if (!(this.mapFnString || this.initError)) throw this.logger.Error().Msg(\"missing mapFnString\").AsError();\n // this.ready = this.blockstore.ready.then(() => {\n // return;\n // });\n // .then((header: IdxCarHeader) => {\n // // @ts-ignore\n // if (header.head) throw new Error('cannot have head in idx header')\n // if (header.indexes === undefined) throw new Error('missing indexes in idx header')\n // // for (const [name, idx] of Object.entries(header.indexes)) {\n // // index({ _crdt: crdt }, name, undefined, idx as IdxMeta)\n // // }\n // })\n }\n\n applyMapFn(name: string, mapFn?: MapFn<T>, meta?: IdxMeta) {\n if (mapFn && meta) throw this.logger.Error().Msg(\"cannot provide both mapFn and meta\").AsError();\n if (this.name && this.name !== name) throw this.logger.Error().Msg(\"cannot change name\").AsError();\n this.name = name;\n try {\n if (meta) {\n // hydrating from header\n if (this.indexHead && this.indexHead.map((c) => c.toString()).join() !== meta.head.map((c) => c.toString()).join()) {\n throw this.logger.Error().Msg(\"cannot apply different head meta\").AsError();\n }\n\n if (this.mapFnString) {\n // we already initialized from application code\n if (this.mapFnString !== meta.map) {\n this.logger\n .Warn()\n .Msg(`cannot apply different mapFn meta: old mapFnString ${this.mapFnString} new mapFnString ${meta.map}`);\n // throw new Error('cannot apply different mapFn meta')\n } else {\n this.byId.cid = meta.byId;\n this.byKey.cid = meta.byKey;\n this.indexHead = meta.head;\n }\n } else {\n // we are first\n this.mapFnString = meta.map;\n this.byId.cid = meta.byId;\n this.byKey.cid = meta.byKey;\n this.indexHead = meta.head;\n }\n } else {\n if (this.mapFn) {\n // we already initialized from application code\n if (mapFn) {\n if (this.mapFn.toString() !== mapFn.toString()) {\n throw this.logger.Error().Msg(\"cannot apply different mapFn app2\").AsError();\n }\n }\n } else {\n // application code is creating an index\n if (!mapFn) {\n mapFn = ((doc) => (doc as unknown as Record<string, unknown>)[name] ?? undefined) as MapFn<T>;\n }\n if (this.mapFnString) {\n // we already loaded from a header\n if (this.mapFnString !== mapFn.toString()) {\n throw this.logger.Error().Msg(\"cannot apply different mapFn app\").AsError();\n }\n } else {\n // we are first\n this.mapFnString = mapFn.toString();\n }\n this.mapFn = mapFn;\n }\n }\n const matches = /=>\\s*(.*)/.test(this.mapFnString);\n this.includeDocsDefault = matches;\n } catch (e) {\n this.initError = e as Error;\n }\n }\n\n async query(opts: QueryOpts<K> = {}): Promise<IndexRows<K, T, R>> {\n await this.ready();\n // this._resetIndex();\n await this._updateIndex();\n await this._hydrateIndex();\n if (!this.byKey.root) {\n return await applyQuery<K, T, R>(this.crdt, { result: [] }, opts);\n }\n if (this.includeDocsDefault && opts.includeDocs === undefined) opts.includeDocs = true;\n if (opts.range) {\n const eRange = encodeRange(opts.range);\n return await applyQuery<K, T, R>(this.crdt, await throwFalsy(this.byKey.root).range(eRange[0], eRange[1]), opts);\n }\n if (opts.key) {\n const encodedKey = encodeKey(opts.key);\n return await applyQuery<K, T, R>(this.crdt, await throwFalsy(this.byKey.root).get(encodedKey), opts);\n }\n if (Array.isArray(opts.keys)) {\n const results = await Promise.all(\n opts.keys.map(async (key: DocFragment) => {\n const encodedKey = encodeKey(key);\n return (await applyQuery<K, T, R>(this.crdt, await throwFalsy(this.byKey.root).get(encodedKey), opts)).rows;\n }),\n );\n return { rows: results.flat() };\n }\n if (opts.prefix) {\n if (!Array.isArray(opts.prefix)) opts.prefix = [opts.prefix];\n // prefix should be always an array\n const start = [...opts.prefix, NaN];\n const end = [...opts.prefix, Infinity];\n const encodedR = encodeRange([start, end]);\n return await applyQuery<K, T, R>(this.crdt, await this.byKey.root.range(...encodedR), opts);\n }\n const all = await this.byKey.root.getAllEntries(); // funky return type\n return await applyQuery<K, T, R>(\n this.crdt,\n {\n // @ts-expect-error getAllEntries returns a different type than range\n result: all.result.map(({ key: [k, id], value }) => ({\n key: k,\n id,\n value,\n })),\n },\n opts,\n );\n }\n\n _resetIndex() {\n this.byId = new IndexTree();\n this.byKey = new IndexTree();\n this.indexHead = undefined;\n }\n\n async _hydrateIndex() {\n if (this.byId.root && this.byKey.root) return;\n if (!this.byId.cid || !this.byKey.cid) return;\n this.byId.root = await loadIndex<K, R, K>(this.blockstore, this.byId.cid, byIdOpts);\n this.byKey.root = await loadIndex<K, R, CompareKey>(this.blockstore, this.byKey.cid, byKeyOpts);\n }\n\n async _updateIndex(): Promise<IndexTransactionMeta> {\n await this.ready();\n if (this.initError) throw this.initError;\n if (!this.mapFn) throw this.logger.Error().Msg(\"No map function defined\").AsError();\n let result: DocUpdate<T>[], head: ClockHead;\n if (!this.indexHead || this.indexHead.length === 0) {\n ({ result, head } = await this.crdt.allDocs());\n } else {\n ({ result, head } = await this.crdt.changes(this.indexHead));\n }\n if (result.length === 0) {\n this.indexHead = head;\n // return { byId: this.byId, byKey: this.byKey } as IndexTransactionMeta;\n }\n let staleKeyIndexEntries: IndexUpdate<K>[] = [];\n let removeIdIndexEntries: IndexUpdateString[] = [];\n if (this.byId.root) {\n const removeIds = result.map(({ id: key }) => key);\n const { result: oldChangeEntries } = await this.byId.root.getMany(removeIds);\n staleKeyIndexEntries = oldChangeEntries.map((key) => ({ key, del: true }));\n removeIdIndexEntries = oldChangeEntries.map((key) => ({ key: key[1], del: true }));\n }\n const indexEntries = indexEntriesForChanges<T, K>(result, this.mapFn); // use a getter to translate from string\n const byIdIndexEntries: IndexDocString[] = indexEntries.map(({ key }) => ({\n key: key[1],\n value: key,\n }));\n const indexerMeta: IdxMetaMap = { indexes: new Map() };\n\n for (const [name, indexer] of this.crdt.indexers) {\n if (indexer.indexHead) {\n indexerMeta.indexes?.set(name, {\n byId: indexer.byId.cid,\n byKey: indexer.byKey.cid,\n head: indexer.indexHead,\n map: indexer.mapFnString,\n name: indexer.name,\n } as IdxMeta);\n }\n }\n if (result.length === 0) {\n return indexerMeta as unknown as IndexTransactionMeta;\n }\n const { meta } = await this.blockstore.transaction<IndexTransactionMeta>(async (tblocks): Promise<IndexTransactionMeta> => {\n this.byId = await bulkIndex<K, R, K>(tblocks, this.byId, removeIdIndexEntries.concat(byIdIndexEntries), byIdOpts);\n this.byKey = await bulkIndex<K, R, CompareKey>(tblocks, this.byKey, staleKeyIndexEntries.concat(indexEntries), byKeyOpts);\n this.indexHead = head;\n if (this.byId.cid && this.byKey.cid) {\n const idxMeta = {\n byId: this.byId.cid,\n byKey: this.byKey.cid,\n head,\n map: this.mapFnString,\n name: this.name,\n } as IdxMeta;\n indexerMeta.indexes?.set(this.name, idxMeta);\n }\n return indexerMeta as unknown as IndexTransactionMeta;\n });\n return meta;\n }\n}\n","import type { Block, Link } from \"multiformats\";\nimport { create } from \"multiformats/block\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as codec from \"@ipld/dag-cbor\";\n\n// @ts-expect-error \"charwise\" has no types\nimport charwise from \"charwise\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport * as DbIndex from \"prolly-trees/db-index\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { bf, simpleCompare } from \"prolly-trees/utils\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { nocache as cache } from \"prolly-trees/cache\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { ProllyNode as BaseNode } from \"prolly-trees/db-index\";\n\nimport {\n DocUpdate,\n MapFn,\n DocFragment,\n IndexUpdate,\n QueryOpts,\n IndexRow,\n DocWithId,\n IndexKeyType,\n IndexKey,\n DocTypes,\n DocObject,\n IndexUpdateString,\n} from \"./types.js\";\nimport { CarTransaction, BlockFetcher, AnyLink, AnyBlock } from \"./blockstore/index.js\";\nimport { CRDT } from \"./crdt.js\";\n\nexport class IndexTree<K extends IndexKeyType, R extends DocFragment> {\n cid?: AnyLink;\n root?: ProllyNode<K, R>;\n}\n\ntype CompareRef = string | number;\nexport type CompareKey = [string | number, CompareRef];\n\nfunction refCompare(aRef: CompareRef, bRef: CompareRef) {\n if (Number.isNaN(aRef)) return -1;\n if (Number.isNaN(bRef)) throw new Error(\"ref may not be Infinity or NaN\");\n if (aRef === Infinity) return 1;\n // if (!Number.isFinite(bRef)) throw new Error('ref may not be Infinity or NaN')\n\n return simpleCompare(aRef, bRef) as number;\n}\n\nfunction compare(a: CompareKey, b: CompareKey) {\n const [aKey, aRef] = a;\n const [bKey, bRef] = b;\n\n const comp: number = simpleCompare(aKey, bKey);\n if (comp !== 0) return comp;\n return refCompare(aRef, bRef);\n}\n\nexport const byKeyOpts: StaticProllyOptions<CompareKey> = { cache, chunker: bf(30), codec, hasher, compare };\n\nexport const byIdOpts: StaticProllyOptions<unknown> = { cache, chunker: bf(30), codec, hasher, compare: simpleCompare };\n\nexport interface IndexDoc<K extends IndexKeyType> {\n readonly key: IndexKey<K>;\n readonly value: DocFragment;\n}\n\nexport interface IndexDocString {\n readonly key: string;\n readonly value: DocFragment;\n}\n\nexport function indexEntriesForChanges<T extends DocTypes, K extends IndexKeyType>(\n changes: DocUpdate<T>[],\n mapFn: MapFn<T>,\n): IndexDoc<K>[] {\n const indexEntries: IndexDoc<K>[] = [];\n changes.forEach(({ id: key, value, del }) => {\n if (del || !value) return;\n let mapCalled = false;\n const mapReturn = mapFn({ ...(value as DocWithId<T>), _id: key }, (k: IndexKeyType, v?: DocFragment) => {\n mapCalled = true;\n if (typeof k === \"undefined\") return;\n indexEntries.push({\n key: [charwise.encode(k) as K, key],\n value: v || null,\n });\n });\n if (!mapCalled && mapReturn) {\n indexEntries.push({\n key: [charwise.encode(mapReturn) as K, key],\n value: null,\n });\n }\n });\n return indexEntries;\n}\n\nfunction makeProllyGetBlock(blocks: BlockFetcher): (address: AnyLink) => Promise<AnyBlock> {\n return async (address: AnyLink) => {\n const block = await blocks.get(address);\n if (!block) throw new Error(`Missing block ${address.toString()}`);\n const { cid, bytes } = block;\n return create({ cid, bytes, hasher, codec }) as Promise<AnyBlock>;\n };\n}\n\nexport async function bulkIndex<K extends IndexKeyType, T extends DocFragment, CT>(\n tblocks: CarTransaction,\n inIndex: IndexTree<K, T>,\n indexEntries: (IndexUpdate<K> | IndexUpdateString)[],\n opts: StaticProllyOptions<CT>,\n): Promise<IndexTree<K, T>> {\n if (!indexEntries.length) return inIndex;\n if (!inIndex.root) {\n if (!inIndex.cid) {\n let returnRootBlock: Block | undefined = undefined;\n let returnNode: ProllyNode<K, T> | undefined = undefined;\n\n for await (const node of (await DbIndex.create({\n get: makeProllyGetBlock(tblocks),\n list: indexEntries,\n ...opts,\n })) as ProllyNode<K, T>[]) {\n const block = await node.block;\n await tblocks.put(block.cid, block.bytes);\n returnRootBlock = block;\n returnNode = node;\n }\n if (!returnNode || !returnRootBlock) throw new Error(\"failed to create index\");\n return { root: returnNode, cid: returnRootBlock.cid };\n } else {\n inIndex.root = (await DbIndex.load({ cid: inIndex.cid, get: makeProllyGetBlock(tblocks), ...opts })) as ProllyNode<K, T>;\n }\n }\n const { root, blocks: newBlocks } = await inIndex.root.bulk(indexEntries);\n if (root) {\n for await (const block of newBlocks) {\n await tblocks.put(block.cid, block.bytes);\n }\n return { root, cid: (await root.block).cid };\n } else {\n return { root: undefined, cid: undefined };\n }\n}\n\nexport async function loadIndex<K extends IndexKeyType, T extends DocFragment, CT>(\n tblocks: BlockFetcher,\n cid: AnyLink,\n opts: StaticProllyOptions<CT>,\n): Promise<ProllyNode<K, T>> {\n return (await DbIndex.load({ cid, get: makeProllyGetBlock(tblocks), ...opts })) as ProllyNode<K, T>;\n}\n\nexport async function applyQuery<K extends IndexKeyType, T extends DocObject, R extends DocFragment>(\n crdt: CRDT<T>,\n resp: { result: ProllyIndexRow<K, R>[] },\n query: QueryOpts<K>,\n): Promise<{\n rows: IndexRow<K, T, R>[];\n}> {\n if (query.descending) {\n resp.result = resp.result.reverse();\n }\n if (query.limit) {\n resp.result = resp.result.slice(0, query.limit);\n }\n if (query.includeDocs) {\n resp.result = await Promise.all(\n resp.result.map(async (row) => {\n const val = await crdt.get(row.id);\n const doc = val ? ({ ...val.doc, _id: row.id } as DocWithId<T>) : undefined;\n return { ...row, doc };\n }),\n );\n }\n return {\n rows: resp.result.map(({ key, ...row }) => {\n return {\n key: charwise.decode(key),\n ...row,\n };\n }),\n };\n}\n\nexport function encodeRange(range: [IndexKeyType, IndexKeyType]): [string, string] {\n return [charwise.encode(range[0]), charwise.encode(range[1])];\n}\n\nexport function encodeKey(key: DocFragment): string {\n return charwise.encode(key) as string;\n}\n\nexport interface ProllyIndexRow<K extends IndexKeyType, T extends DocFragment> {\n readonly id: string;\n readonly key: IndexKey<K>;\n readonly value: T;\n}\n\n// ProllyNode type based on the ProllyNode from 'prolly-trees/base'\ninterface ProllyNode<K extends IndexKeyType, T extends DocFragment> extends BaseNode {\n getAllEntries(): PromiseLike<{ [x: string]: unknown; result: ProllyIndexRow<K, T>[] }>;\n getMany<KI extends IndexKeyType>(removeIds: KI[]): Promise<{ /* [x: K]: unknown; */ result: IndexKey<K>[] }>;\n range(a: string, b: string): Promise<{ result: ProllyIndexRow<K, T>[] }>;\n get(key: string): Promise<{ result: ProllyIndexRow<K, T>[] }>;\n bulk(bulk: (IndexUpdate<K> | IndexUpdateString)[]): PromiseLike<{\n readonly root?: ProllyNode<K, T>;\n readonly blocks: Block[];\n }>;\n readonly address: Promise<Link>;\n readonly distance: number;\n compare: (a: unknown, b: unknown) => number;\n readonly cache: unknown;\n readonly block: Promise<Block>;\n}\n\ninterface StaticProllyOptions<T> {\n readonly cache: unknown;\n chunker: (entry: T, distance: number) => boolean;\n readonly codec: unknown;\n readonly hasher: unknown;\n compare: (a: T, b: T) => number;\n}\n","import { advance } from \"@web3-storage/pail/clock\";\nimport { root } from \"@web3-storage/pail/crdt\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n\nimport { clockChangesSince } from \"./crdt-helpers.js\";\nimport type { BaseBlockstore, CarTransaction } from \"./blockstore/index.js\";\nimport { type DocUpdate, type ClockHead, type DocTypes, throwFalsy, CRDTMeta } from \"./types.js\";\nimport { applyHeadQueue, ApplyHeadQueue } from \"./apply-head-queue.js\";\nimport { ensureLogger } from \"./utils.js\";\n\nexport class CRDTClock<T extends DocTypes> {\n // todo: track local and remote clocks independently, merge on read\n // that way we can drop the whole remote if we need to\n // should go with making sure the local clock only references locally available blockstore on write\n head: ClockHead = [];\n\n readonly zoomers = new Set<() => void>();\n readonly watchers = new Set<(updates: DocUpdate<T>[]) => void>();\n readonly emptyWatchers = new Set<() => void>();\n\n readonly blockstore: BaseBlockstore;\n\n readonly applyHeadQueue: ApplyHeadQueue<T>;\n\n readonly _ready = new ResolveOnce<void>();\n async ready() {\n return this._ready.once(async () => {\n await this.blockstore.ready();\n });\n }\n\n async close() {\n await this.blockstore.close();\n }\n\n readonly logger: Logger;\n constructor(blockstore: BaseBlockstore) {\n this.blockstore = blockstore;\n this.logger = ensureLogger(blockstore.logger, \"CRDTClock\");\n this.applyHeadQueue = applyHeadQueue(this.int_applyHead.bind(this), this.logger);\n }\n\n setHead(head: ClockHead) {\n this.head = head;\n }\n\n async applyHead(newHead: ClockHead, prevHead: ClockHead, updates?: DocUpdate<T>[]) {\n for await (const { updates: updatesAcc, all } of this.applyHeadQueue.push({\n newHead,\n prevHead,\n updates,\n })) {\n return this.processUpdates(updatesAcc, all, prevHead);\n }\n }\n\n async processUpdates(updatesAcc: DocUpdate<T>[], all: boolean, prevHead: ClockHead) {\n let internalUpdates = updatesAcc;\n if (this.watchers.size && !all) {\n const changes = await clockChangesSince<T>(throwFalsy(this.blockstore), this.head, prevHead, {}, this.logger);\n internalUpdates = changes.result;\n }\n this.zoomers.forEach((fn) => fn());\n this.notifyWatchers(internalUpdates || []);\n }\n\n notifyWatchers(updates: DocUpdate<T>[]) {\n this.emptyWatchers.forEach((fn) => fn());\n this.watchers.forEach((fn) => fn(updates || []));\n }\n\n onTick(fn: (updates: DocUpdate<T>[]) => void) {\n this.watchers.add(fn);\n }\n\n onTock(fn: () => void) {\n this.emptyWatchers.add(fn);\n }\n\n onZoom(fn: () => void) {\n this.zoomers.add(fn);\n }\n\n async int_applyHead(newHead: ClockHead, prevHead: ClockHead, localUpdates: boolean) {\n // if (!(this.head && prevHead && newHead)) {\n // throw new Error(\"missing head\");\n // }\n // console.log(\"int_applyHead\", this.applyHeadQueue.size(), this.head, newHead, prevHead, localUpdates);\n const ogHead = sortClockHead(this.head);\n newHead = sortClockHead(newHead);\n if (compareClockHeads(ogHead, newHead)) {\n return;\n }\n const ogPrev = sortClockHead(prevHead);\n if (compareClockHeads(ogHead, ogPrev)) {\n this.setHead(newHead);\n return;\n }\n\n const noLoader = !localUpdates;\n // const noLoader = this.head.length === 1 && !updates?.length\n if (!this.blockstore) {\n throw this.logger.Error().Msg(\"missing blockstore\").AsError();\n }\n await validateBlocks(this.logger, newHead, this.blockstore);\n const { meta } = await this.blockstore.transaction<CRDTMeta>(\n async (tblocks: CarTransaction) => {\n const advancedHead = await advanceBlocks(this.logger, newHead, tblocks, this.head);\n const result = await root(tblocks, advancedHead);\n for (const { cid, bytes } of [\n ...result.additions,\n // ...result.removals\n ]) {\n tblocks.putSync(cid, bytes);\n }\n return { head: advancedHead };\n },\n { noLoader },\n );\n this.setHead(meta.head);\n }\n}\n\n// Helper functions\nfunction sortClockHead(clockHead: ClockHead) {\n return clockHead.sort((a, b) => a.toString().localeCompare(b.toString()));\n}\n\nasync function validateBlocks(logger: Logger, newHead: ClockHead, blockstore?: BaseBlockstore) {\n if (!blockstore) throw logger.Error().Msg(\"missing blockstore\");\n newHead.map(async (cid) => {\n const got = await blockstore.get(cid);\n if (!got) {\n throw logger.Error().Str(\"cid\", cid.toString()).Msg(\"int_applyHead missing block\").AsError();\n }\n });\n}\n\nfunction compareClockHeads(head1: ClockHead, head2: ClockHead) {\n return head1.toString() === head2.toString();\n}\n\nasync function advanceBlocks(logger: Logger, newHead: ClockHead, tblocks: CarTransaction, head: ClockHead) {\n for (const cid of newHead) {\n try {\n head = await advance(tblocks, head, cid);\n } catch (e) {\n logger.Debug().Err(e).Msg(\"failed to advance head\");\n // console.log('failed to advance head:', cid.toString(), e)\n continue;\n }\n }\n return head;\n}\n","import { Logger } from \"@adviser/cement\";\nimport { ClockHead, DocTypes, DocUpdate } from \"./types.js\";\n\ntype ApplyHeadWorkerFunction = (newHead: ClockHead, prevHead: ClockHead, localUpdates: boolean) => Promise<void>;\n\ninterface ApplyHeadTask<T extends DocTypes> {\n readonly newHead: ClockHead;\n readonly prevHead: ClockHead;\n readonly updates?: DocUpdate<T>[];\n}\n\nexport interface ApplyHeadQueue<T extends DocTypes> {\n push(task: ApplyHeadTask<T>): AsyncGenerator<\n {\n readonly updates: DocUpdate<T>[];\n readonly all: boolean;\n },\n void,\n unknown\n >;\n size(): number;\n}\n\nexport function applyHeadQueue<T extends DocTypes>(worker: ApplyHeadWorkerFunction, logger: Logger): ApplyHeadQueue<T> {\n const queue: ApplyHeadTask<T>[] = [];\n let isProcessing = false;\n\n async function* process() {\n if (isProcessing || queue.length === 0) return;\n isProcessing = true;\n const allUpdates: DocUpdate<T>[] = [];\n try {\n while (queue.length > 0) {\n queue.sort((a, b) => (b.updates ? 1 : -1));\n const task = queue.shift();\n if (!task) continue;\n\n // console.time('int_applyHead worker')\n await worker(task.newHead, task.prevHead, task.updates !== null).catch((e) => {\n throw logger.Error().Err(e).Msg(\"int_applyHead worker error\").AsError();\n });\n // console.timeEnd('int_applyHead worker')\n\n if (task.updates) {\n allUpdates.push(...task.updates);\n }\n // Yield the updates if there are no tasks with updates left in the queue or the current task has updates\n if (!queue.some((t) => t.updates) || task.updates) {\n const allTasksHaveUpdates = queue.every((task) => task.updates !== null);\n yield { updates: allUpdates, all: allTasksHaveUpdates };\n allUpdates.length = 0;\n }\n }\n } finally {\n isProcessing = false;\n const generator = process();\n let result = await generator.next();\n while (!result.done) {\n result = await generator.next();\n }\n }\n }\n\n return {\n push(task: ApplyHeadTask<T>): AsyncGenerator<{ updates: DocUpdate<T>[]; all: boolean }, void, unknown> {\n queue.push(task);\n return process();\n },\n size() {\n return queue.length;\n },\n };\n}\n","export const PACKAGE_VERSION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ACtB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,EACrC,IAAI,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,EAAE,EAAE;AACjC;AAEO,SAAS,UAAU,MAAc,MAA6B;AACnE,QAAM,MAAM,KAAK;AAAA,IACf,cAAc;AAAA,MACZ;AAAA,MACA,QAAQ,cAAc,MAAM,OAAO,MAAM;AAAA,MAEzC,eAAe,CAAC,CAAC,MAAM,OAAO;AAAA,MAC9B,eAAe,CAAC,CAAC,MAAM,OAAO;AAAA,MAC9B,eAAe,CAAC,CAAC,MAAM,OAAO;AAAA,MAE9B,YAAY,CAAC,CAAC,MAAM,OAAO;AAAA,MAC3B,YAAY,CAAC,CAAC,MAAM,OAAO;AAAA,IAC7B,CAAC;AAAA,EACH;AACA,MAAI,KAAK,SAAS,UAAU,IAAI,GAAG;AACnC,MAAI,CAAC,IAAI;AACP,SAAK,IAAI,SAAS,MAAM,IAAI;AAC5B,aAAS,UAAU,IAAI,KAAK,EAAE;AAAA,EAChC;AACA,SAAO;AACT;AAEA,SAAS,SAAS,UAAkB;AAClC,QAAM,QAAQ;AACd,MAAI,QAAgC;AACpC,QAAM,UAAU,MAAM,KAAK,SAAS,SAAS,KAAK,GAAG,CAAC,UAAU,MAAM,CAAC,EAAE,KAAK,CAAC;AAC/E,MAAI,QAAQ,WAAW,GAAG;AACxB,YAAQ,YAAY,KAAK,QAAQ;AAAA,EACnC;AACA,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT,OAAO;AAEL,WAAO,MAAM,CAAC;AAAA,EAChB;AACF;;;ADhQA;AASA;AACA;AAEA;;;AsBbO,IAAM,kBAAkB,OAAO,KAAK;AAAA,EACzC,qBAAqB;AACvB,CAAC,EAAE,CAAC;","names":["path","url","createNodeSysContainer","url","e","url","url","import_cement","import_uuidv7","import_cement","path","import_cement","url","url","db","import_cement","import_uuidv7","import_cement","index","import_cement","import_block","import_sha2","codec","import_clock","cid","import_cement","import_p_limit","import_cement","import_cement","import_block","raw","hasher","import_sha2","import_multiformats","import_block","import_utils","crypto","randomBytes","encode","decode","crypto","randomBytes","codec","get","hasher","cache","chunker","root","block","mfCreate","import_block","CBW","carLogIncludesGroup","pLimit","cid","cache","got","batchSize","root","url","pLimit","carLogIncludesGroup","url","FileDataGateway","FileMetaGateway","FileWALGateway","FileTestStore","IndexDBDataGateway","IndexDBMetaGateway","IndexDBTestStore","hasher","codec","import_block","import_sha2","codec","import_utils","import_cache","cache","hasher","charwise","root","import_clock","import_crdt","import_cement","task","name","updates"]}
1
+ {"version":3,"sources":["../../src/utils.ts","../../src/runtime/gateways/file/mem-filesystem.ts","../../src/runtime/gateways/file/node-filesystem.ts","../../src/runtime/gateways/file/utils.ts","../../src/runtime/key-bag-file.ts","../../src/runtime/key-bag-indexdb.ts","../../src/runtime/gateways/file/version.ts","../../src/runtime/gateways/file/gateway.ts","../../src/runtime/gateways/indexdb/version.ts","../../src/runtime/gateways/indexdb/gateway.ts","../../src/index.ts","../../src/database.ts","../../src/write-queue.ts","../../src/crdt.ts","../../src/runtime/wait-pr-multiformats/block.ts","../../src/crdt-helpers.ts","../../src/blockstore/index.ts","../../src/blockstore/types.ts","../../src/blockstore/store-factory.ts","../../src/runtime/files.ts","../../src/blockstore/store.ts","../../src/types.ts","../../src/blockstore/loader.ts","../../src/blockstore/loader-helpers.ts","../../src/blockstore/transaction.ts","../../src/blockstore/commit-queue.ts","../../src/runtime/key-bag.ts","../../src/blockstore/commitor.ts","../../src/blockstore/task-manager.ts","../../src/runtime/keyed-crypto.ts","../../src/blockstore/fragment-gateway.ts","../../src/blockstore/meta-key-helper.ts","../../src/blockstore/store-remote.ts","../../src/blockstore/connection-base.ts","../../src/indexer-helpers.ts","../../src/indexer.ts","../../src/crdt-clock.ts","../../src/apply-head-queue.ts","../../src/runtime/index.ts","../../src/runtime/wait-pr-multiformats/index.ts","../../src/runtime/wait-pr-multiformats/codec-interface.ts","../../src/version.ts"],"sourcesContent":["import {\n Logger,\n LoggerImpl,\n IsLogger,\n Result,\n ResolveOnce,\n isURL,\n URI,\n CoerceURI,\n runtimeFn,\n envFactory,\n Env,\n toCryptoRuntime,\n CryptoRuntime,\n JSONFormatter,\n YAMLFormatter,\n} from \"@adviser/cement\";\nimport { PathOps, StoreType, SuperThis, SuperThisOpts, TextEndeCoder } from \"./types\";\nimport { base58btc } from \"multiformats/bases/base58\";\n\nexport type { Logger };\nexport { Result };\n\nconst globalLogger: Logger = new LoggerImpl();\n\nconst registerFP_DEBUG = new ResolveOnce();\n\ninterface superThisOpts {\n readonly logger: Logger;\n readonly env: Env;\n readonly pathOps: PathOps;\n readonly crypto: CryptoRuntime;\n readonly ctx: Record<string, unknown>;\n readonly txt: TextEndeCoder;\n}\n\nclass superThis implements SuperThis {\n readonly logger: Logger;\n readonly env: Env;\n readonly pathOps: PathOps;\n readonly ctx: Record<string, unknown>;\n readonly txt: TextEndeCoder;\n readonly crypto: CryptoRuntime;\n\n constructor(opts: superThisOpts) {\n this.logger = opts.logger;\n this.env = opts.env;\n this.crypto = opts.crypto;\n this.pathOps = opts.pathOps;\n this.txt = opts.txt;\n this.ctx = { ...opts.ctx };\n // console.log(\"superThis\", this);\n }\n\n nextId(bytes = 6): { str: string; bin: Uint8Array } {\n const bin = this.crypto.randomBytes(bytes);\n return {\n str: base58btc.encode(bin),\n bin,\n };\n }\n\n timeOrderedNextId(now?: number): { str: string } {\n now = typeof now === \"number\" ? now : new Date().getTime();\n // 49th bit\n const t = (0x1000000000000 + now).toString(16).replace(/^1/, \"\");\n const bin = this.crypto.randomBytes(10);\n bin[1] = (bin[1] & 0xf0) | (bin[1] | 0x08 && 0x0b);\n const hex = Array.from(bin)\n .map((i) => i.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return {\n str: `${t.slice(0, 8)}-${t.slice(8)}-7${hex.slice(0, 3)}-${hex.slice(3, 7)}-${hex.slice(7, 19)}`,\n };\n }\n\n start(): Promise<void> {\n return Promise.resolve();\n }\n\n clone(override: Partial<SuperThisOpts>): SuperThis {\n return new superThis({\n logger: override.logger || this.logger,\n env: envFactory(override.env) || this.env,\n crypto: override.crypto || this.crypto,\n pathOps: override.pathOps || this.pathOps,\n txt: override.txt || this.txt,\n ctx: { ...this.ctx, ...override.ctx },\n });\n }\n}\n\n// const pathOps =\nfunction presetEnv() {\n const penv = new Map([\n // [\"FP_DEBUG\", \"xxx\"],\n // [\"FP_ENV\", \"development\"],\n ...Array.from(\n Object.entries(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ((globalThis as any)[Symbol.for(\"FP_PRESET_ENV\")] || {}) as Record<string, string>,\n ),\n ), // .map(([k, v]) => [k, v as string])\n ]);\n // console.log(\">>>>>>\", penv)\n return penv;\n}\n// const envImpl = envFactory({\n// symbol: \"FP_ENV\",\n// presetEnv: presetEnv(),\n// });\nclass pathOpsImpl implements PathOps {\n join(...paths: string[]): string {\n return paths.map((i) => i.replace(/\\/+$/, \"\")).join(\"/\");\n }\n dirname(path: string) {\n return path.split(\"/\").slice(0, -1).join(\"/\");\n }\n // homedir() {\n // throw new Error(\"SysContainer:homedir is not available in seeded state\");\n // }\n}\nconst pathOps = new pathOpsImpl();\nconst txtOps = {\n encode: (input: string) => new TextEncoder().encode(input),\n decode: (input: Uint8Array) => new TextDecoder().decode(input),\n};\n\nexport function ensureSuperThis(osthis?: Partial<SuperThisOpts>): SuperThis {\n const env = envFactory({\n symbol: osthis?.env?.symbol || \"FP_ENV\",\n presetEnv: osthis?.env?.presetEnv || presetEnv(),\n });\n return new superThis({\n logger: osthis?.logger || globalLogger,\n env,\n crypto: osthis?.crypto || toCryptoRuntime(),\n ctx: osthis?.ctx || {},\n pathOps,\n txt: osthis?.txt || txtOps,\n });\n}\n\n// // eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function ensureSuperLog(sthis: SuperThis, componentName: string, ctx?: Record<string, unknown>): SuperThis {\n return sthis.clone({\n logger: ensureLogger(sthis, componentName, ctx),\n });\n}\n\nexport function ensureLogger(\n sthis: SuperThis /* Partial<LoggerOpts> | Logger */,\n componentName: string,\n ctx?: Record<string, unknown>,\n): Logger {\n // if (!opts?.logger) {\n // throw new Error(\"logger is required\");\n // }\n let logger = globalLogger;\n if (IsLogger(sthis)) {\n logger = sthis;\n } else if (sthis && IsLogger(sthis.logger)) {\n logger = sthis.logger;\n }\n const cLogger = logger.With().Module(componentName); //.Str(\"this\", uuidv7());\n const debug: string[] = [];\n let exposeStack = false;\n if (ctx) {\n if (\"debug\" in ctx) {\n if (typeof ctx.debug === \"string\" && ctx.debug.length > 0) {\n debug.push(ctx.debug);\n } else {\n debug.push(componentName);\n }\n delete ctx.debug;\n }\n if (\"exposeStack\" in ctx) {\n exposeStack = true;\n delete ctx.exposeStack;\n }\n if (\"this\" in ctx) {\n cLogger.Str(\"this\", sthis.nextId(4).str);\n delete ctx.this;\n }\n for (const [key, value] of Object.entries(ctx)) {\n switch (typeof value) {\n case \"string\":\n cLogger.Str(key, value);\n break;\n case \"number\":\n cLogger.Uint64(key, value);\n break;\n default:\n if (value instanceof Date) {\n cLogger.Str(key, value.toISOString());\n } else if (isURL(value)) {\n cLogger.Str(key, value.toString());\n } else if (typeof value === \"function\") {\n cLogger.Ref(key, value);\n } else {\n cLogger.Any(key, value);\n }\n break;\n }\n }\n }\n registerFP_DEBUG\n .once(async () => {\n // console.log(\"registerFP_DEBUG\", SysContainer.env)\n sthis.env.onSet(\n (key, value) => {\n // console.log(\"FP_DEBUG\", key, value, debug)\n switch (key) {\n case \"FP_FORMAT\": {\n switch (value) {\n case \"jsonice\":\n logger.SetFormatter(new JSONFormatter(logger.TxtEnDe(), 2));\n break;\n case \"yaml\":\n logger.SetFormatter(new YAMLFormatter(logger.TxtEnDe(), 2));\n break;\n case \"json\":\n default:\n logger.SetFormatter(new JSONFormatter(logger.TxtEnDe()));\n break;\n }\n break;\n }\n case \"FP_DEBUG\":\n logger.SetDebug(value || []);\n break;\n case \"FP_STACK\":\n logger.SetExposeStack(!!value);\n break;\n }\n },\n \"FP_FORMAT\",\n \"FP_DEBUG\",\n \"FP_STACK\",\n );\n })\n .finally(() => {\n /* do nothing */\n });\n\n if (debug.length > 0) {\n logger.SetDebug(debug);\n }\n if (exposeStack) {\n logger.SetExposeStack(true);\n }\n const out = cLogger.Logger();\n // out.Debug().Msg(\"logger ready\");\n return out;\n}\n\nexport type Joiner = (...toJoin: string[]) => string;\n\nexport interface Store {\n readonly store: StoreType;\n readonly name: string;\n}\n\nexport function getStore(url: URI, sthis: SuperThis, joiner: Joiner): Store {\n const store = url.getParam(\"store\");\n switch (store) {\n case \"data\":\n case \"wal\":\n case \"meta\":\n break;\n default:\n throw sthis.logger.Error().Url(url).Msg(`store not found`).AsError();\n }\n let name: string = store;\n if (url.hasParam(\"index\")) {\n name = joiner(url.getParam(\"index\") || \"idx\", name);\n }\n return { store, name };\n}\n\nexport function getKey(url: URI, logger: Logger): string {\n const result = url.getParam(\"key\");\n if (!result) throw logger.Error().Str(\"url\", url.toString()).Msg(`key not found`).AsError();\n return result;\n}\n\nexport function getName(sthis: SuperThis, url: URI): string {\n let result = url.getParam(\"name\");\n if (!result) {\n result = sthis.pathOps.dirname(url.pathname);\n if (result.length === 0) {\n throw sthis.logger.Error().Str(\"url\", url.toString()).Msg(`name not found`).AsError();\n }\n }\n return result;\n}\n\n// export function exception2Result<T = void>(fn: () => Promise<T>): Promise<Result<T>> {\n// return fn()\n// .then((value) => Result.Ok(value))\n// .catch((e) => Result.Err(e));\n// }\n\nexport async function exceptionWrapper<T, E extends Error>(fn: () => Promise<Result<T, E>>): Promise<Result<T, E>> {\n return fn().catch((e) => Result.Err(e));\n}\n\n// // the big side effect party --- hate it\n// export function sanitizeURL(url: URL) {\n// url.searchParams.sort();\n// // const searchParams = Object.entries(url.searchParams).sort(([a], [b]) => a.localeCompare(b));\n// // console.log(\"searchParams\", searchParams);\n// // for (const [key] of searchParams) {\n// // url.searchParams.delete(key);\n// // }\n// // for (const [key, value] of searchParams) {\n// // url.searchParams.set(key, value);\n// // }\n// }\n\nexport class NotFoundError extends Error {\n readonly code = \"ENOENT\";\n}\n\nexport function isNotFoundError(e: Error | Result<unknown> | unknown): e is NotFoundError {\n if (Result.Is(e)) {\n if (e.isOk()) return false;\n e = e.Err();\n }\n if ((e as NotFoundError).code === \"ENOENT\") return true;\n return false;\n}\n\nexport function dataDir(sthis: SuperThis, name?: string, base?: CoerceURI): URI {\n if (!base) {\n if (!runtimeFn().isBrowser) {\n const home = sthis.env.get(\"HOME\") || \"./\";\n base = sthis.env.get(\"FP_STORAGE_URL\") || `file://${sthis.pathOps.join(home, \".fireproof\")}`;\n } else {\n base = sthis.env.get(\"FP_STORAGE_URL\") || `indexdb://fp`;\n }\n }\n return URI.from(base.toString())\n .build()\n .setParam(\"name\", name || \"\")\n .URI();\n}\n\nexport function UInt8ArrayEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n","import type { PathLike, MakeDirectoryOptions, Stats } from \"fs\";\nimport { fs } from \"memfs\";\nimport { IReaddirOptions } from \"memfs/lib/node/types/options.js\";\nimport { toArrayBuffer } from \"./utils.js\";\nimport { SysFileSystem } from \"../../../types.js\";\n\nexport class MemFileSystem implements SysFileSystem {\n async start(): Promise<SysFileSystem> {\n return this;\n }\n mkdir(path: PathLike, options?: { recursive: boolean }): Promise<string | undefined> {\n return fs.promises.mkdir(path, options);\n }\n readdir(path: PathLike, options?: IReaddirOptions): Promise<string[]> {\n return fs.promises.readdir(path, options) as Promise<string[]>;\n }\n rm(path: PathLike, options?: MakeDirectoryOptions & { recursive: boolean }): Promise<void> {\n return fs.promises.rm(path, options);\n }\n copyFile(source: PathLike, destination: PathLike): Promise<void> {\n return fs.promises.copyFile(source, destination);\n }\n async readfile(path: PathLike, options?: { encoding: BufferEncoding; flag?: string }): Promise<Uint8Array> {\n const ret = await fs.promises.readFile(path, options);\n return toArrayBuffer(ret);\n }\n stat(path: PathLike): Promise<Stats> {\n return fs.promises.stat(path) as Promise<Stats>;\n }\n unlink(path: PathLike): Promise<void> {\n return fs.promises.unlink(path);\n }\n writefile(path: PathLike, data: Uint8Array | string): Promise<void> {\n return fs.promises.writeFile(path, Buffer.from(data));\n }\n}\n","import type { PathLike, MakeDirectoryOptions, Stats, ObjectEncodingOptions } from \"node:fs\";\nimport type { mkdir, readdir, rm, copyFile, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { toArrayBuffer } from \"./utils.js\";\nimport { SysFileSystem } from \"../../../types.js\";\nimport { runtimeFn } from \"@adviser/cement\";\n\nexport class NodeFileSystem implements SysFileSystem {\n fs?: {\n mkdir: typeof mkdir;\n readdir: typeof readdir;\n rm: typeof rm;\n copyFile: typeof copyFile;\n readFile: typeof readFile;\n stat: typeof stat;\n unlink: typeof unlink;\n writeFile: typeof writeFile;\n };\n\n async start(): Promise<SysFileSystem> {\n this.fs = await import(\"node:fs/promises\");\n return this;\n }\n async mkdir(path: PathLike, options?: { recursive: boolean }): Promise<string | undefined> {\n return this.fs?.mkdir(path, options);\n }\n async readdir(path: PathLike, options?: ObjectEncodingOptions): Promise<string[]> {\n return this.fs?.readdir(path, options) as Promise<string[]>;\n }\n async rm(path: PathLike, options?: MakeDirectoryOptions & { recursive: boolean }): Promise<void> {\n return this.fs?.rm(path, options);\n }\n async copyFile(source: PathLike, destination: PathLike): Promise<void> {\n return this.fs?.copyFile(source, destination);\n }\n async readfile(path: PathLike, options?: { encoding: BufferEncoding; flag?: string }): Promise<Uint8Array> {\n const ret = (await this.fs?.readFile(path, options)) as Buffer;\n return toArrayBuffer(ret);\n }\n stat(path: PathLike): Promise<Stats> {\n return this.fs?.stat(path) as Promise<Stats>;\n }\n async unlink(path: PathLike): Promise<void> {\n return this.fs?.unlink(path);\n }\n async writefile(path: PathLike, data: Uint8Array | string): Promise<void> {\n if (runtimeFn().isDeno) {\n return this.fs?.writeFile(path, data);\n }\n return this.fs?.writeFile(path, Buffer.from(data));\n }\n}\n\n// import { type NodeMap, join } from \"../../sys-container.js\";\n// import type { ObjectEncodingOptions, PathLike } from \"fs\";\n// import * as fs from \"fs/promises\";\n// import * as path from \"path\";\n// import * as os from \"os\";\n// import * as url from \"url\";\n// import { toArrayBuffer } from \"./utils.js\";\n\n// export async function createNodeSysContainer(): Promise<NodeMap> {\n// // const nodePath = \"node:path\";\n// // const nodeOS = \"node:os\";\n// // const nodeURL = \"node:url\";\n// // const nodeFS = \"node:fs\";\n// // const fs = (await import(\"node:fs\")).promises;\n// // const assert = \"assert\";\n// // const path = await import(\"node:path\");\n// return {\n// state: \"node\",\n// ...path,\n// // ...(await import(\"node:os\")),\n// // ...(await import(\"node:url\")),\n// ...os,\n// ...url,\n// ...fs,\n// join,\n// stat: fs.stat as NodeMap[\"stat\"],\n// readdir: fs.readdir as NodeMap[\"readdir\"],\n// readfile: async (path: PathLike, options?: ObjectEncodingOptions): Promise<Uint8Array> => {\n// const rs = await fs.readFile(path, options);\n// return toArrayBuffer(rs);\n// },\n// writefile: fs.writeFile as NodeMap[\"writefile\"],\n// };\n// }\n","import { URI } from \"@adviser/cement\";\nimport { getStore } from \"../../../utils.js\";\nimport { SuperThis, SysFileSystem } from \"../../../types.js\";\n\nexport async function getFileSystem(url: URI): Promise<SysFileSystem> {\n const name = url.getParam(\"fs\");\n let fs: SysFileSystem;\n switch (name) {\n case \"mem\":\n {\n const { MemFileSystem } = await import(\"./mem-filesystem.js\");\n fs = new MemFileSystem();\n }\n break;\n // case 'deno': {\n // const { DenoFileSystem } = await import(\"./deno-filesystem.js\");\n // fs = new DenoFileSystem();\n // break;\n // }\n case \"node\": {\n const { NodeFileSystem } = await import(\"./node-filesystem.js\");\n fs = new NodeFileSystem();\n break;\n }\n case \"sys\":\n default: {\n // if (runtimeFn().isDeno) {\n // return getFileSystem(url.build().setParam(\"fs\", \"deno\").URI());\n // } else {\n return getFileSystem(url.build().setParam(\"fs\", \"node\").URI());\n // }\n }\n }\n return fs.start();\n}\n\nexport function getPath(url: URI, sthis: SuperThis): string {\n const basePath = url.pathname;\n // .toString()\n // .replace(new RegExp(`^${url.protocol}//`), \"\")\n // .replace(/\\?.*$/, \"\");\n const name = url.getParam(\"name\");\n if (name) {\n const version = url.getParam(\"version\");\n if (!version) throw sthis.logger.Error().Url(url).Msg(`version not found`).AsError();\n return sthis.pathOps.join(basePath, version, name);\n }\n return sthis.pathOps.join(basePath);\n}\n\nexport function getFileName(url: URI, sthis: SuperThis): string {\n const key = url.getParam(\"key\");\n if (!key) throw sthis.logger.Error().Url(url).Msg(`key not found`).AsError();\n const res = getStore(url, sthis, (...a: string[]) => a.join(\"-\"));\n switch (res.store) {\n case \"data\":\n return sthis.pathOps.join(res.name, key + \".car\");\n case \"wal\":\n case \"meta\":\n return sthis.pathOps.join(res.name, key + \".json\");\n default:\n throw sthis.logger.Error().Url(url).Msg(`unsupported store type`).AsError();\n }\n}\n\nexport function toArrayBuffer(buffer: Buffer | string): Uint8Array {\n if (typeof buffer === \"string\") {\n buffer = Buffer.from(buffer);\n }\n const ab = new ArrayBuffer(buffer.length);\n const view = new Uint8Array(ab);\n for (let i = 0; i < buffer.length; ++i) {\n view[i] = buffer[i];\n }\n return view;\n}\n","import { URI } from \"@adviser/cement\";\nimport { isNotFoundError, Logger } from \"../utils.js\";\nimport { KeyBagProvider, KeyItem } from \"./key-bag.js\";\nimport { SuperThis, SysFileSystem } from \"../types.js\";\n\ninterface KeyBagCtx {\n readonly dirName: string;\n readonly sysFS: SysFileSystem;\n readonly fName: string;\n}\n\nexport class KeyBagProviderFile implements KeyBagProvider {\n async _prepare(id: string): Promise<KeyBagCtx> {\n await this.sthis.start();\n let sysFS: SysFileSystem;\n switch (this.url.protocol) {\n case \"file:\": {\n const { getFileSystem } = await import(\"./gateways/file/utils.js\");\n sysFS = await getFileSystem(this.url);\n break;\n }\n default:\n throw this.logger.Error().Url(this.url).Msg(\"unsupported protocol\").AsError();\n }\n const dirName = this.url.pathname;\n await sysFS.mkdir(dirName, { recursive: true });\n return {\n dirName,\n sysFS,\n fName: this.sthis.pathOps.join(dirName, `${id.replace(/[^a-zA-Z0-9]/g, \"_\")}.json`),\n };\n }\n\n private readonly url: URI;\n readonly logger: Logger;\n readonly sthis: SuperThis;\n constructor(url: URI, sthis: SuperThis) {\n this.url = url;\n this.sthis = sthis;\n this.logger = sthis.logger;\n }\n\n async get(id: string): Promise<KeyItem | undefined> {\n const ctx = await this._prepare(id);\n try {\n const p = await ctx.sysFS.readfile(ctx.fName);\n const ki = JSON.parse(this.sthis.txt.decode(p)) as KeyItem;\n return ki;\n } catch (e) {\n if (isNotFoundError(e)) {\n return undefined;\n }\n throw this.logger.Error().Err(e).Str(\"file\", ctx.dirName).Msg(\"read bag failed\").AsError();\n }\n }\n\n async set(id: string, item: KeyItem): Promise<void> {\n const ctx = await this._prepare(id);\n const p = this.sthis.txt.encode(JSON.stringify(item, null, 2));\n await ctx.sysFS.writefile(ctx.fName, p);\n }\n}\n","import { IDBPDatabase, openDB } from \"idb\";\nimport { KeyBagProvider, KeyItem } from \"./key-bag.js\";\nimport { getPath } from \"./gateways/file/utils.js\";\nimport { Logger, ResolveOnce, URI } from \"@adviser/cement\";\nimport { SuperThis } from \"use-fireproof\";\n\nexport class KeyBagProviderIndexDB implements KeyBagProvider {\n readonly _db: ResolveOnce<IDBPDatabase<unknown>> = new ResolveOnce<IDBPDatabase<unknown>>();\n\n readonly dbName: string;\n readonly url: URI;\n readonly logger: Logger;\n readonly sthis: SuperThis;\n constructor(url: URI, sthis: SuperThis) {\n this.sthis = sthis;\n this.logger = sthis.logger;\n this.url = url;\n this.dbName = getPath(this.url, this.sthis);\n }\n\n async _prepare(): Promise<IDBPDatabase<unknown>> {\n return this._db.once(async () => {\n return await openDB(this.dbName, 1, {\n upgrade(db) {\n // console.log('upgrade:', dbName);\n [\"bag\"].map((store) => {\n db.createObjectStore(store, {\n autoIncrement: false,\n });\n });\n },\n });\n });\n }\n\n async get(id: string): Promise<KeyItem | undefined> {\n const db = await this._prepare();\n const tx = db.transaction([\"bag\"], \"readonly\");\n const keyItem = await tx.objectStore(\"bag\").get(id);\n await tx.done;\n if (!keyItem) {\n return undefined;\n }\n return keyItem;\n }\n\n async set(id: string, item: KeyItem): Promise<void> {\n const db = await this._prepare();\n const tx = db.transaction([\"bag\"], \"readwrite\");\n await tx.objectStore(\"bag\").put(item, id);\n await tx.done;\n }\n}\n","export const FILESTORE_VERSION = \"v0.19-file\";\n","import { FILESTORE_VERSION } from \"./version.js\";\nimport { exception2Result, KeyedResolvOnce, Logger, Result, URI } from \"@adviser/cement\";\nimport { ensureLogger, exceptionWrapper, isNotFoundError, NotFoundError } from \"../../../utils.js\";\nimport { Gateway, GetResult, TestGateway } from \"../../../blockstore/gateway.js\";\nimport { getFileName, getFileSystem, getPath } from \"./utils.js\";\nimport { SuperThis, SysFileSystem } from \"../../../types.js\";\n\nconst versionFiles = new KeyedResolvOnce<string>();\n\nexport class FileGateway implements Gateway {\n // abstract readonly storeType: StoreType;\n readonly logger: Logger;\n readonly sthis: SuperThis;\n\n _fs?: SysFileSystem;\n\n get fs(): SysFileSystem {\n if (!this._fs) throw this.logger.Error().Msg(\"fs not initialized\").AsError();\n return this._fs;\n }\n\n constructor(sthis: SuperThis) {\n this.sthis = sthis;\n this.logger = sthis.logger;\n }\n\n async getVersionFromFile(path: string, logger: Logger): Promise<string> {\n return versionFiles.get(path).once(async () => {\n await this.fs.mkdir(path, { recursive: true });\n const vFile = this.sthis.pathOps.join(path, \"version\");\n const vFileStat = await this.fs.stat(vFile).catch(() => undefined);\n if (!vFileStat) {\n await this.fs.writefile(this.sthis.pathOps.join(path, \"version\"), FILESTORE_VERSION);\n return FILESTORE_VERSION;\n } else if (!vFileStat.isFile()) {\n throw logger.Error().Str(\"file\", vFile).Msg(`version file is a directory`).AsError();\n }\n const v = await this.fs.readfile(vFile);\n const vStr = new TextDecoder().decode(v);\n if (vStr !== FILESTORE_VERSION) {\n logger.Warn().Str(\"file\", vFile).Str(\"from\", vStr).Str(\"expected\", FILESTORE_VERSION).Msg(`version mismatch`);\n }\n return vStr;\n });\n }\n\n start(baseURL: URI): Promise<Result<URI>> {\n return exception2Result(async () => {\n this._fs = await getFileSystem(baseURL);\n await this.fs.start();\n const url = baseURL.build();\n url.defParam(\"version\", FILESTORE_VERSION);\n // url.defParam(\"store\", this.storeType);\n const dbUrl = await this.buildUrl(url.URI(), \"dummy\");\n const dbdirFile = this.getFilePath(dbUrl.Ok());\n await this.fs.mkdir(this.sthis.pathOps.dirname(dbdirFile), { recursive: true });\n const dbroot = this.sthis.pathOps.dirname(dbdirFile);\n this.logger.Debug().Url(url.URI()).Str(\"dbroot\", dbroot).Msg(\"start\");\n url.setParam(\"version\", await this.getVersionFromFile(dbroot, this.logger));\n return url.URI();\n });\n }\n\n async buildUrl(baseUrl: URI, key: string): Promise<Result<URI>> {\n return Result.Ok(baseUrl.build().setParam(\"key\", key).URI());\n }\n\n async close(): Promise<Result<void>> {\n return Result.Ok(undefined);\n }\n // abstract buildUrl(baseUrl: URL, key: string): Promise<Result<URL>>;\n\n getFilePath(url: URI): string {\n const key = url.getParam(\"key\");\n if (!key) throw this.logger.Error().Url(url).Msg(`key not found`).AsError();\n return this.sthis.pathOps.join(getPath(url, this.sthis), getFileName(url, this.sthis));\n }\n\n async put(url: URI, body: Uint8Array): Promise<Result<void>> {\n return exception2Result(async () => {\n const file = await this.getFilePath(url);\n this.logger.Debug().Str(\"url\", url.toString()).Str(\"file\", file).Msg(\"put\");\n await this.fs.writefile(file, body);\n });\n }\n\n async get(url: URI): Promise<GetResult> {\n return exceptionWrapper(async () => {\n const file = this.getFilePath(url);\n try {\n const res = await this.fs.readfile(file);\n this.logger.Debug().Url(url.asURL()).Str(\"file\", file).Msg(\"get\");\n return Result.Ok(new Uint8Array(res));\n } catch (e: unknown) {\n // this.logger.Error().Err(e).Str(\"file\", file).Msg(\"get\");\n if (isNotFoundError(e)) {\n return Result.Err(new NotFoundError(`file not found: ${file}`));\n }\n return Result.Err(e as Error);\n }\n });\n }\n\n async delete(url: URI): Promise<Result<void>> {\n return exception2Result(async () => {\n await this.fs.unlink(this.getFilePath(url));\n });\n }\n\n async destroy(baseURL: URI): Promise<Result<void>> {\n const url = await this.buildUrl(baseURL, \"x\");\n if (url.isErr()) return url;\n const filepath = this.sthis.pathOps.dirname(this.getFilePath(url.Ok()));\n let files: string[] = [];\n try {\n files = await this.fs.readdir(filepath);\n } catch (e: unknown) {\n if (!isNotFoundError(e)) {\n throw this.logger.Error().Err(e).Str(\"dir\", filepath).Msg(\"destroy:readdir\").AsError();\n }\n }\n for (const file of files) {\n const pathed = this.sthis.pathOps.join(filepath, file);\n try {\n await this.fs.unlink(pathed);\n } catch (e: unknown) {\n if (!isNotFoundError(e)) {\n throw this.logger.Error().Err(e).Str(\"file\", pathed).Msg(\"destroy:unlink\").AsError();\n }\n }\n }\n return Result.Ok(undefined);\n }\n}\n\n// export class FileWALGateway extends FileGateway {\n// readonly storeType = \"wal\";\n// constructor(logger: Logger) {\n// super(ensureLogger(logger, \"FileWALGateway\"));\n// }\n// }\n\n// export class FileMetaGateway extends FileGateway {\n// readonly storeType = \"meta\";\n// constructor(logger: Logger) {\n// super(ensureLogger(logger, \"FileMetaGateway\"));\n// }\n// }\n\n// export class FileDataGateway extends FileGateway {\n// readonly storeType = \"data\";\n// readonly branches = new Set<string>();\n// constructor(logger: Logger) {\n// // console.log(\"FileDataGateway->\", logger);\n// super(ensureLogger(logger, \"FileDataGateway\"));\n// }\n// }\n\nexport class FileTestStore implements TestGateway {\n readonly logger: Logger;\n readonly sthis: SuperThis;\n constructor(sthis: SuperThis) {\n this.logger = ensureLogger(sthis, \"FileTestStore\");\n this.sthis = sthis;\n }\n\n async get(iurl: URI, key: string) {\n const url = iurl.build().setParam(\"key\", key).URI();\n const dbFile = this.sthis.pathOps.join(getPath(url, this.sthis), getFileName(url, this.sthis));\n this.logger.Debug().Url(url).Str(\"dbFile\", dbFile).Msg(\"get\");\n const buffer = await (await getFileSystem(url)).readfile(dbFile);\n this.logger.Debug().Url(url).Str(\"dbFile\", dbFile).Len(buffer).Msg(\"got\");\n return buffer;\n }\n}\n","export const INDEXDB_VERSION = \"v0.19-indexdb\";\n","import { openDB, IDBPDatabase } from \"idb\";\nimport { exception2Result, KeyedResolvOnce, Logger, Result, URI } from \"@adviser/cement\";\n\nimport { INDEXDB_VERSION } from \"./version.js\";\nimport { ensureLogger, exceptionWrapper, getKey, getStore, NotFoundError } from \"../../../utils.js\";\nimport { Gateway, GetResult, TestGateway } from \"../../../blockstore/gateway.js\";\nimport { SuperThis } from \"../../../types.js\";\n\nfunction ensureVersion(url: URI): URI {\n return url.build().defParam(\"version\", INDEXDB_VERSION).URI();\n}\n\ninterface IDBConn {\n readonly db: IDBPDatabase<unknown>;\n readonly dbName: DbName;\n readonly version: string;\n readonly url: URI;\n}\nconst onceIndexDB = new KeyedResolvOnce<IDBConn>();\n\nfunction sanitzeKey(key: string | string[]): string | string[] {\n if (key.length === 1) {\n key = key[0];\n }\n return key;\n}\n\nasync function connectIdb(url: URI, sthis: SuperThis): Promise<IDBConn> {\n const dbName = getIndexDBName(url, sthis);\n const once = await onceIndexDB.get(dbName.fullDb).once(async () => {\n const db = await openDB(dbName.fullDb, 1, {\n upgrade(db) {\n [\"version\", \"data\", \"wal\", \"meta\", \"idx.data\", \"idx.wal\", \"idx.meta\"].map((store) => {\n db.createObjectStore(store, {\n autoIncrement: false,\n });\n });\n },\n });\n const found = await db.get(\"version\", \"version\");\n const version = ensureVersion(url).getParam(\"version\") as string;\n if (!found) {\n await db.put(\"version\", { version }, \"version\");\n } else if (found.version !== version) {\n sthis.logger.Warn().Str(\"url\", url.toString()).Str(\"version\", version).Str(\"found\", found.version).Msg(\"version mismatch\");\n }\n return { db, dbName, version, url };\n });\n return {\n ...once,\n url: url.build().setParam(\"version\", once.version).URI(),\n };\n}\n\nexport interface DbName {\n readonly fullDb: string;\n readonly objStore: string;\n readonly connectionKey: string;\n readonly dbName: string;\n}\n\nfunction joinDBName(...names: string[]): string {\n return names\n .map((i) => i.replace(/^[^a-zA-Z0-9]+/g, \"\").replace(/[^a-zA-Z0-9]+/g, \"_\"))\n .filter((i) => i.length)\n .join(\".\");\n}\n\n// const schemaVersion = new Map<string, number>();\nexport function getIndexDBName(iurl: URI, sthis: SuperThis): DbName {\n const url = ensureVersion(iurl);\n const fullDb = url.pathname.replace(/^\\/+/, \"\").replace(/\\?.*$/, \"\"); // cut leading slashes\n // const type = getStore(url);\n // const storageVersion = url.searchParams.get(\"version\");\n // not nice but we need to pass the version to the db name\n // url.searchParams.set(\"version\", storageVersion);\n // console.log(\"getIndexDBName:\", url.toString(), { fullDb, type, branch });\n // const dbName = fullDb.replace(new RegExp(`^fp.${storageVersion}.`), \"\"); // cut fp prefix\n const dbName = url.getParam(\"name\");\n if (!dbName) throw sthis.logger.Error().Str(\"url\", url.toString()).Msg(`name not found`).AsError();\n const result = joinDBName(fullDb, dbName);\n const objStore = getStore(url, sthis, joinDBName).name;\n const connectionKey = [result, objStore].join(\":\");\n return {\n fullDb: result,\n objStore,\n connectionKey,\n dbName,\n };\n}\n\nexport class IndexDBGateway implements Gateway {\n readonly logger: Logger;\n readonly sthis: SuperThis;\n constructor(sthis: SuperThis) {\n this.logger = ensureLogger(sthis, \"IndexDBGateway\");\n this.sthis = sthis;\n }\n _db: IDBPDatabase<unknown> = {} as IDBPDatabase<unknown>;\n\n async start(baseURL: URI): Promise<Result<URI>> {\n return exception2Result(async () => {\n this.logger.Debug().Url(baseURL).Msg(\"starting\");\n await this.sthis.start();\n const ic = await connectIdb(baseURL, this.sthis);\n this._db = ic.db;\n this.logger.Debug().Url(ic.url).Msg(\"started\");\n return ic.url;\n });\n }\n async close(): Promise<Result<void>> {\n return Result.Ok(undefined);\n }\n async destroy(baseUrl: URI): Promise<Result<void>> {\n return exception2Result(async () => {\n // return deleteDB(getIndexDBName(this.url).fullDb);\n const type = getStore(baseUrl, this.sthis, joinDBName).name;\n // console.log(\"IndexDBDataStore:destroy\", type);\n const idb = this._db;\n const trans = idb.transaction(type, \"readwrite\");\n const object_store = trans.objectStore(type);\n const toDelete = [];\n for (let cursor = await object_store.openCursor(); cursor; cursor = await cursor.continue()) {\n toDelete.push(cursor.primaryKey);\n }\n for (const key of toDelete) {\n await trans.db.delete(type, key);\n }\n await trans.done;\n });\n }\n\n buildUrl(baseUrl: URI, key: string): Promise<Result<URI>> {\n return Promise.resolve(Result.Ok(baseUrl.build().setParam(\"key\", key).URI()));\n }\n\n async get(url: URI): Promise<GetResult> {\n return exceptionWrapper(async () => {\n const key = getKey(url, this.logger);\n const store = getStore(url, this.sthis, joinDBName).name;\n this.logger.Debug().Url(url).Str(\"key\", key).Str(\"store\", store).Msg(\"getting\");\n const tx = this._db.transaction([store], \"readonly\");\n const bytes = await tx.objectStore(store).get(sanitzeKey(key));\n await tx.done;\n if (!bytes) {\n return Result.Err(new NotFoundError(`missing ${key}`));\n }\n return Result.Ok(bytes as Uint8Array);\n });\n }\n async put(url: URI, value: Uint8Array) {\n return exception2Result(async () => {\n const key = getKey(url, this.logger);\n const store = getStore(url, this.sthis, joinDBName).name;\n this.logger.Debug().Url(url).Str(\"key\", key).Str(\"store\", store).Msg(\"putting\");\n const tx = this._db.transaction([store], \"readwrite\");\n await tx.objectStore(store).put(value, sanitzeKey(key));\n await tx.done;\n });\n }\n async delete(url: URI) {\n return exception2Result(async () => {\n const key = getKey(url, this.logger);\n const store = getStore(url, this.sthis, joinDBName).name;\n this.logger.Debug().Url(url).Str(\"key\", key).Str(\"store\", store).Msg(\"deleting\");\n const tx = this._db.transaction([store], \"readwrite\");\n await tx.objectStore(store).delete(sanitzeKey(key));\n await tx.done;\n return Result.Ok(undefined);\n });\n }\n}\n\n// export class IndexDBDataGateway extends IndexDBGateway {\n// readonly storeType = \"data\";\n// constructor(logger: Logger) {\n// super(ensureLogger(logger, \"IndexDBDataGateway\"));\n// }\n// }\n\n// export class IndexDBWalGateway extends IndexDBGateway {\n// readonly storeType = \"wal\";\n// constructor(logger: Logger) {\n// super(ensureLogger(logger, \"IndexDBWalGateway\"));\n// }\n// }\n// export class IndexDBMetaGateway extends IndexDBGateway {\n// readonly storeType = \"meta\";\n// constructor(logger: Logger) {\n// super(ensureLogger(logger, \"IndexDBMetaGateway\"));\n// }\n// }\n\nexport class IndexDBTestStore implements TestGateway {\n readonly logger: Logger;\n readonly sthis: SuperThis;\n constructor(sthis: SuperThis) {\n this.sthis = sthis;\n this.logger = ensureLogger(sthis, \"IndexDBTestStore\", {});\n }\n async get(url: URI, key: string) {\n const ic = await connectIdb(url, this.sthis);\n const store = getStore(ic.url, this.sthis, joinDBName).name;\n this.logger.Debug().Str(\"key\", key).Str(\"store\", store).Msg(\"getting\");\n let bytes = await ic.db.get(store, sanitzeKey(key));\n this.logger.Debug().Str(\"key\", key).Str(\"store\", store).Int(\"len\", bytes.length).Msg(\"got\");\n if (typeof bytes === \"string\") {\n bytes = this.sthis.txt.encode(bytes);\n }\n return bytes as Uint8Array;\n }\n}\n","export * from \"./database.js\";\nexport * from \"./types.js\";\n\nexport * from \"./crdt.js\";\n\nexport * from \"./indexer.js\";\n\nexport * as bs from \"./blockstore/index.js\";\nexport * as blockstore from \"./blockstore/index.js\";\n\nimport { type Connectable } from \"./blockstore\";\nexport { Connectable };\n\nexport * as rt from \"./runtime/index.js\";\nexport * as runtime from \"./runtime/index.js\";\n\nexport * from \"./utils.js\";\n\nexport * from \"./version.js\";\n","import { Logger, ResolveOnce } from \"@adviser/cement\";\n\nimport { WriteQueue, writeQueue } from \"./write-queue.js\";\nimport { CRDT } from \"./crdt.js\";\nimport { index } from \"./indexer.js\";\nimport type {\n DocUpdate,\n ClockHead,\n ConfigOpts,\n MapFn,\n QueryOpts,\n ChangesOptions,\n DocSet,\n DocWithId,\n IndexKeyType,\n ListenerFn,\n DocResponse,\n ChangesResponse,\n DocTypes,\n IndexRows,\n DocFragment,\n ChangesResponseRow,\n CRDTMeta,\n AllDocsQueryOpts,\n AllDocsResponse,\n SuperThis,\n} from \"./types.js\";\nimport { BaseBlockstore, Connectable } from \"./blockstore/index.js\";\nimport { ensureLogger, ensureSuperThis, NotFoundError } from \"./utils.js\";\n\nexport class Database<DT extends DocTypes = NonNullable<unknown>> implements Connectable {\n static databases: Map<string, Database> = new Map<string, Database>();\n\n readonly name?: string;\n readonly opts: ConfigOpts = {};\n\n _listening = false;\n readonly _listeners: Set<ListenerFn<DT>> = new Set<ListenerFn<DT>>();\n readonly _noupdate_listeners: Set<ListenerFn<DT>> = new Set<ListenerFn<DT>>();\n readonly _crdt: CRDT<DT>;\n readonly _writeQueue: WriteQueue<DT>;\n readonly blockstore: BaseBlockstore;\n\n async close() {\n await this.ready();\n await this._crdt.close();\n await this.blockstore.close();\n }\n\n async destroy() {\n await this.ready();\n await this._crdt.destroy();\n await this.blockstore.destroy();\n }\n\n readonly _ready: ResolveOnce<void> = new ResolveOnce<void>();\n async ready(): Promise<void> {\n return this._ready.once(async () => {\n await this.sthis.start();\n await this._crdt.ready();\n await this.blockstore.ready();\n });\n }\n\n readonly logger: Logger;\n readonly sthis: SuperThis;\n\n constructor(name?: string, opts?: ConfigOpts) {\n this.name = name;\n this.opts = opts || this.opts;\n this.sthis = ensureSuperThis(this.opts);\n this.logger = ensureLogger(this.sthis, \"Database\");\n // this.logger.SetDebug(\"Database\")\n this._crdt = new CRDT(this.sthis, name, this.opts);\n this.blockstore = this._crdt.blockstore; // for connector compatibility\n this._writeQueue = writeQueue(async (updates: DocUpdate<DT>[]) => {\n return await this._crdt.bulk(updates);\n }); //, Infinity)\n this._crdt.clock.onTock(() => {\n this._no_update_notify();\n });\n }\n\n async get<T extends DocTypes>(id: string): Promise<DocWithId<T>> {\n if (!id) throw this.logger.Error().Str(\"db\", this.name).Msg(`Doc id is required`).AsError();\n\n await this.ready();\n this.logger.Debug().Str(\"id\", id).Msg(\"get\");\n const got = await this._crdt.get(id).catch((e) => {\n throw new NotFoundError(`Not found: ${id} - ${e.message}`);\n });\n if (!got) throw new NotFoundError(`Not found: ${id}`);\n const { doc } = got;\n return { ...(doc as unknown as DocWithId<T>), _id: id };\n }\n\n async put<T extends DocTypes>(doc: DocSet<T>): Promise<DocResponse> {\n await this.ready();\n this.logger.Debug().Str(\"id\", doc._id).Msg(\"put\");\n const { _id, ...value } = doc;\n const docId = _id || this.sthis.timeOrderedNextId().str;\n const result = (await this._writeQueue.push({\n id: docId,\n value: {\n ...(value as unknown as DocSet<DT>),\n _id: docId,\n },\n })) as CRDTMeta;\n return { id: docId, clock: result?.head, name: this.name } as DocResponse;\n }\n\n async del(id: string): Promise<DocResponse> {\n await this.ready();\n this.logger.Debug().Str(\"id\", id).Msg(\"del\");\n const result = (await this._writeQueue.push({ id: id, del: true })) as CRDTMeta;\n return { id, clock: result?.head, name: this.name } as DocResponse;\n }\n\n async changes<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): Promise<ChangesResponse<T>> {\n await this.ready();\n this.logger.Debug().Any(\"since\", since).Any(\"opts\", opts).Msg(\"changes\");\n const { result, head } = await this._crdt.changes(since, opts);\n const rows: ChangesResponseRow<T>[] = result.map(({ id: key, value, del, clock }) => ({\n key,\n value: (del ? { _id: key, _deleted: true } : { _id: key, ...value }) as DocWithId<T>,\n clock,\n }));\n return { rows, clock: head, name: this.name };\n }\n\n async allDocs<T extends DocTypes>(opts: AllDocsQueryOpts = {}): Promise<AllDocsResponse<T>> {\n await this.ready();\n void opts;\n this.logger.Debug().Msg(\"allDocs\");\n const { result, head } = await this._crdt.allDocs();\n const rows = result.map(({ id: key, value, del }) => ({\n key,\n value: (del ? { _id: key, _deleted: true } : { _id: key, ...value }) as DocWithId<T>,\n }));\n return { rows, clock: head, name: this.name };\n }\n\n async allDocuments<T extends DocTypes>(): Promise<{\n rows: {\n key: string;\n value: DocWithId<T>;\n }[];\n clock: ClockHead;\n }> {\n return this.allDocs<T>();\n }\n\n subscribe<T extends DocTypes>(listener: ListenerFn<T>, updates?: boolean): () => void {\n this.logger.Debug().Bool(\"updates\", updates).Msg(\"subscribe\");\n if (updates) {\n if (!this._listening) {\n this._listening = true;\n this._crdt.clock.onTick((updates: DocUpdate<NonNullable<unknown>>[]) => {\n void this._notify(updates);\n });\n }\n this._listeners.add(listener as ListenerFn<NonNullable<unknown>>);\n return () => {\n this._listeners.delete(listener as ListenerFn<NonNullable<unknown>>);\n };\n } else {\n this._noupdate_listeners.add(listener as ListenerFn<NonNullable<unknown>>);\n return () => {\n this._noupdate_listeners.delete(listener as ListenerFn<NonNullable<unknown>>);\n };\n }\n }\n\n // todo if we add this onto dbs in fireproof.ts then we can make index.ts a separate package\n async query<K extends IndexKeyType, T extends DocTypes, R extends DocFragment = T>(\n field: string | MapFn<T>,\n opts: QueryOpts<K> = {},\n ): Promise<IndexRows<K, T, R>> {\n await this.ready();\n this.logger.Debug().Any(\"field\", field).Any(\"opts\", opts).Msg(\"query\");\n const _crdt = this._crdt as unknown as CRDT<T>;\n const idx =\n typeof field === \"string\"\n ? index<K, T, R>(this.sthis, { _crdt }, field)\n : index<K, T, R>(this.sthis, { _crdt }, makeName(field.toString()), field);\n return await idx.query(opts);\n }\n\n async compact() {\n await this.ready();\n await this._crdt.compact();\n }\n\n async _notify(updates: DocUpdate<NonNullable<unknown>>[]) {\n await this.ready();\n if (this._listeners.size) {\n const docs: DocWithId<NonNullable<unknown>>[] = updates.map(({ id, value }) => ({ ...value, _id: id }));\n for (const listener of this._listeners) {\n await (async () => await listener(docs as DocWithId<DT>[]))().catch((e: Error) => {\n this.logger.Error().Err(e).Msg(\"subscriber error\");\n });\n }\n }\n }\n\n async _no_update_notify() {\n await this.ready();\n if (this._noupdate_listeners.size) {\n for (const listener of this._noupdate_listeners) {\n await (async () => await listener([]))().catch((e: Error) => {\n this.logger.Error().Err(e).Msg(\"subscriber error\");\n });\n }\n }\n }\n}\n\nfunction toSortedArray(set?: Record<string, unknown>): Record<string, unknown>[] {\n if (!set) return [];\n return Object.entries(set)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => ({ [k]: v }));\n}\n\nexport function fireproof(name: string, opts?: ConfigOpts): Database {\n const key = JSON.stringify(\n toSortedArray({\n name,\n stores: toSortedArray(opts?.store?.stores),\n }),\n );\n let db = Database.databases.get(key);\n if (!db) {\n db = new Database(name, opts);\n Database.databases.set(key, db);\n }\n return db;\n}\n\nfunction makeName(fnString: string) {\n const regex = /\\(([^,()]+,\\s*[^,()]+|\\[[^\\]]+\\],\\s*[^,()]+)\\)/g;\n let found: RegExpExecArray | null = null;\n const matches = Array.from(fnString.matchAll(regex), (match) => match[1].trim());\n if (matches.length === 0) {\n found = /=>\\s*{?\\s*([^{}]+)\\s*}?/.exec(fnString);\n if (found && found[1].includes(\"return\")) {\n found = null;\n }\n }\n if (!found) {\n return fnString;\n } else {\n // it's a consise arrow function, match everything after the arrow\n return found[1];\n }\n}\n","import { DocTypes, MetaType, DocUpdate } from \"./types.js\";\n\ntype WorkerFunction<T extends DocTypes> = (tasks: DocUpdate<T>[]) => Promise<MetaType>;\n\nexport interface WriteQueue<T extends DocTypes> {\n push(task: DocUpdate<T>): Promise<MetaType>;\n}\n\ninterface WriteQueueItem<T extends DocTypes> {\n readonly task: DocUpdate<T>;\n resolve(result: MetaType): void;\n reject(error: Error): void;\n}\n\nexport function writeQueue<T extends DocTypes>(worker: WorkerFunction<T>, payload = Infinity, unbounded = false): WriteQueue<T> {\n const queue: WriteQueueItem<T>[] = [];\n let isProcessing = false;\n\n async function process() {\n if (isProcessing || queue.length === 0) return;\n isProcessing = true;\n\n const tasksToProcess = queue.splice(0, payload);\n const updates = tasksToProcess.map((item) => item.task);\n\n if (unbounded) {\n // Run all updates in parallel and resolve/reject them individually\n const promises = updates.map(async (update, index) => {\n try {\n const result = await worker([update]);\n tasksToProcess[index].resolve(result);\n } catch (error) {\n tasksToProcess[index].reject(error as Error);\n }\n });\n\n await Promise.all(promises);\n } else {\n // Original logic: Run updates in a batch and resolve/reject them together\n try {\n const result = await worker(updates);\n tasksToProcess.forEach((task) => task.resolve(result));\n } catch (error) {\n tasksToProcess.forEach((task) => task.reject(error as Error));\n }\n }\n\n isProcessing = false;\n void process();\n }\n\n return {\n push(task: DocUpdate<T>): Promise<MetaType> {\n return new Promise<MetaType>((resolve, reject) => {\n queue.push({ task, resolve, reject });\n void process();\n });\n },\n };\n}\n","import { Block } from \"multiformats\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n\nimport {\n EncryptedBlockstore,\n type TransactionMeta,\n type CarTransaction,\n BaseBlockstore,\n CompactFetcher,\n} from \"./blockstore/index.js\";\nimport {\n clockChangesSince,\n applyBulkUpdateToCrdt,\n getValueFromCrdt,\n readFiles,\n getAllEntries,\n clockVis,\n getBlock,\n doCompact,\n} from \"./crdt-helpers.js\";\nimport type {\n DocUpdate,\n CRDTMeta,\n ClockHead,\n ConfigOpts,\n ChangesOptions,\n IdxMetaMap,\n DocValue,\n IndexKeyType,\n DocWithId,\n DocTypes,\n Falsy,\n SuperThis,\n} from \"./types.js\";\nimport { index, type Index } from \"./indexer.js\";\nimport { CRDTClock } from \"./crdt-clock.js\";\nimport { blockstoreFactory } from \"./blockstore/transaction.js\";\nimport { ensureLogger } from \"./utils.js\";\n\nexport class CRDT<T extends DocTypes> {\n readonly name?: string;\n readonly opts: ConfigOpts;\n\n readonly blockstore: BaseBlockstore;\n readonly indexBlockstore: BaseBlockstore;\n readonly indexers: Map<string, Index<IndexKeyType, NonNullable<unknown>>> = new Map<\n string,\n Index<IndexKeyType, NonNullable<unknown>>\n >();\n readonly clock: CRDTClock<T>;\n\n readonly logger: Logger;\n readonly sthis: SuperThis;\n\n constructor(sthis: SuperThis, name?: string, opts: ConfigOpts = {}) {\n this.sthis = sthis;\n this.name = name;\n this.logger = ensureLogger(sthis, \"CRDT\");\n this.opts = opts;\n this.blockstore = blockstoreFactory(sthis, {\n name: name,\n applyMeta: async (meta: TransactionMeta) => {\n const crdtMeta = meta as CRDTMeta;\n if (!crdtMeta.head) throw this.logger.Error().Msg(\"missing head\").AsError();\n await this.clock.applyHead(crdtMeta.head, []);\n },\n compact: async (blocks: CompactFetcher) => {\n await doCompact(blocks, this.clock.head, this.logger);\n return { head: this.clock.head } as TransactionMeta;\n },\n autoCompact: this.opts.autoCompact || 100,\n store: { ...this.opts.store, isIndex: undefined },\n public: this.opts.public,\n meta: this.opts.meta,\n threshold: this.opts.threshold,\n });\n this.indexBlockstore = blockstoreFactory(sthis, {\n name: name,\n applyMeta: async (meta: TransactionMeta) => {\n const idxCarMeta = meta as IdxMetaMap;\n if (!idxCarMeta.indexes) throw this.logger.Error().Msg(\"missing indexes\").AsError();\n for (const [name, idx] of Object.entries(idxCarMeta.indexes)) {\n index(this.sthis, { _crdt: this }, name, undefined, idx);\n }\n },\n store: { ...this.opts.store, isIndex: this.opts.store?.isIndex || \"idx\" },\n public: this.opts.public,\n });\n this.clock = new CRDTClock<T>(this.blockstore);\n this.clock.onZoom(() => {\n for (const idx of this.indexers.values()) {\n idx._resetIndex();\n }\n });\n }\n\n async bulk(updates: DocUpdate<T>[]): Promise<CRDTMeta> {\n await this.ready();\n const prevHead = [...this.clock.head];\n\n const done = await this.blockstore.transaction<CRDTMeta>(async (blocks: CarTransaction): Promise<CRDTMeta> => {\n const { head } = await applyBulkUpdateToCrdt<T>(\n this.blockstore.ebOpts.storeRuntime,\n blocks,\n this.clock.head,\n updates,\n this.logger,\n );\n updates = updates.map((dupdate: DocUpdate<T>) => {\n // if (!dupdate.value) throw new Error(\"missing value\");\n readFiles(this.blockstore, { doc: dupdate.value as DocWithId<T> });\n return dupdate;\n });\n return { head };\n });\n await this.clock.applyHead(done.meta.head, prevHead, updates);\n return done.meta;\n }\n\n readonly onceReady: ResolveOnce<void> = new ResolveOnce<void>();\n async ready(): Promise<void> {\n return this.onceReady.once(async () => {\n try {\n // await this.blockstore.ready();\n // await this.indexBlockstore.ready();\n // await this.clock.ready();\n await Promise.all([this.blockstore.ready(), this.indexBlockstore.ready(), this.clock.ready()]);\n } catch (e) {\n throw this.logger.Error().Err(e).Msg(`CRDT is not ready`).AsError();\n }\n });\n }\n\n async close(): Promise<void> {\n await Promise.all([this.blockstore.close(), this.indexBlockstore.close(), this.clock.close()]);\n }\n\n async destroy(): Promise<void> {\n await Promise.all([this.blockstore.destroy(), this.indexBlockstore.destroy()]);\n }\n\n // if (snap) await this.clock.applyHead(crdtMeta.head, this.clock.head)\n\n async allDocs(): Promise<{ result: DocUpdate<T>[]; head: ClockHead }> {\n await this.ready();\n const result: DocUpdate<T>[] = [];\n for await (const entry of getAllEntries<T>(this.blockstore, this.clock.head, this.logger)) {\n result.push(entry);\n }\n return { result, head: this.clock.head };\n }\n\n async vis(): Promise<string> {\n await this.ready();\n const txt: string[] = [];\n for await (const line of clockVis(this.blockstore, this.clock.head)) {\n txt.push(line);\n }\n return txt.join(\"\\n\");\n }\n\n async getBlock(cidString: string): Promise<Block> {\n await this.ready();\n return await getBlock(this.blockstore, cidString);\n }\n\n async get(key: string): Promise<DocValue<T> | Falsy> {\n await this.ready();\n const result = await getValueFromCrdt<T>(this.blockstore, this.clock.head, key, this.logger);\n if (result.del) return undefined;\n return result;\n }\n\n async changes(\n since: ClockHead = [],\n opts: ChangesOptions = {},\n ): Promise<{\n result: DocUpdate<T>[];\n head: ClockHead;\n }> {\n await this.ready();\n return await clockChangesSince<T>(this.blockstore, this.clock.head, since, opts, this.logger);\n }\n\n async compact(): Promise<void> {\n const blocks = this.blockstore as EncryptedBlockstore;\n return await blocks.compact();\n }\n}\n","// this enable async codec\n// it should be gone if this in multiformats is merged:\n// https://github.com/multiformats/js-multiformats/pull/305\nimport { bytes as binary, CID, MultihashHasher, BlockView, ByteView, Version, Link } from \"multiformats\";\nimport { Block as mfBlock } from \"multiformats/block\";\nimport { BlockDecoder, BlockEncoder } from \"./codec-interface\";\n\n// export type Block<T, C extends number, A extends number, V extends Version> = mfBlock<T, C, A, V>\n\nexport const Block = mfBlock;\n\ninterface DecodeInput<T, Code extends number, Alg extends number> {\n bytes: ByteView<T>;\n codec: BlockDecoder<Code, T>;\n hasher: MultihashHasher<Alg>;\n}\n\nexport async function decode<T, Code extends number, Alg extends number>({\n bytes,\n codec,\n hasher,\n}: DecodeInput<T, Code, Alg>): Promise<BlockView<T, Code, Alg>> {\n if (bytes == null) throw new Error('Missing required argument \"bytes\"');\n if (codec == null || hasher == null) throw new Error(\"Missing required argument: codec or hasher\");\n\n const value = await Promise.resolve(codec.decode(bytes));\n const hash = await hasher.digest(bytes);\n const cid = CID.create(1, codec.code, hash) as CID<T, Code, Alg, 1>;\n\n return new mfBlock({ value, bytes, cid });\n}\n\ninterface EncodeInput<T, Code extends number, Alg extends number> {\n value: T;\n codec: BlockEncoder<Code, T>;\n hasher: MultihashHasher<Alg>;\n}\n\nexport async function encode<T, Code extends number, Alg extends number>({\n value,\n codec,\n hasher,\n}: EncodeInput<T, Code, Alg>): Promise<BlockView<T, Code, Alg>> {\n if (typeof value === \"undefined\") throw new Error('Missing required argument \"value\"');\n if (codec == null || hasher == null) throw new Error(\"Missing required argument: codec or hasher\");\n\n const bytes = await Promise.resolve(codec.encode(value));\n const hash = await hasher.digest(bytes);\n const cid = CID.create(1, codec.code, hash) as CID<T, Code, Alg, 1>;\n\n return new mfBlock({ value, bytes, cid });\n}\n\ninterface CreateInput<T, Code extends number, Alg extends number, V extends Version> {\n bytes: ByteView<T>;\n cid: Link<T, Code, Alg, V>;\n hasher: MultihashHasher<Alg>;\n codec: BlockDecoder<Code, T>;\n}\n\nexport async function create<T, Code extends number, Alg extends number, V extends Version>({\n bytes,\n cid,\n hasher,\n codec,\n}: CreateInput<T, Code, Alg, V>): Promise<BlockView<T, Code, Alg, V>> {\n if (bytes == null) throw new Error('Missing required argument \"bytes\"');\n if (hasher == null) throw new Error('Missing required argument \"hasher\"');\n const value = await Promise.resolve(codec.decode(bytes));\n const hash = await hasher.digest(bytes);\n if (!binary.equals(cid.multihash.bytes, hash.bytes)) {\n throw new Error(\"CID hash does not match bytes\");\n }\n\n return createUnsafe({\n bytes,\n cid,\n value,\n codec,\n });\n}\n\ntype CreateUnsafeInput<T, Code extends number, Alg extends number, V extends Version> =\n | {\n cid: Link<T, Code, Alg, V>;\n value: T;\n codec?: BlockDecoder<Code, T>;\n bytes: ByteView<T>;\n }\n | {\n cid: Link<T, Code, Alg, V>;\n value?: undefined;\n codec: BlockDecoder<Code, T>;\n bytes: ByteView<T>;\n };\n\n/**\n * @template T - Logical type of the data encoded in the block\n * @template Code - multicodec code corresponding to codec used to encode the block\n * @template Alg - multicodec code corresponding to the hashing algorithm used in CID creation.\n * @template V - CID version\n */\nexport async function createUnsafe<T, Code extends number, Alg extends number, V extends Version>({\n bytes,\n cid,\n value: maybeValue,\n codec,\n}: CreateUnsafeInput<T, Code, Alg, V>): Promise<BlockView<T, Code, Alg, V>> {\n const value = await Promise.resolve(maybeValue !== undefined ? maybeValue : codec?.decode(bytes));\n\n if (value === undefined) throw new Error('Missing required argument, must either provide \"value\" or \"codec\"');\n\n return new Block({\n cid: cid as CID<T, Code, Alg, V>,\n bytes,\n value,\n });\n}\n","import { encode, decode, Block } from \"./runtime/wait-pr-multiformats/block.js\";\nimport { parse } from \"multiformats/link\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as codec from \"@ipld/dag-cbor\";\nimport { put, get, entries, root } from \"@web3-storage/pail/crdt\";\nimport { EventBlockView, EventLink, Operation, PutOperation } from \"@web3-storage/pail/crdt/api\";\nimport { EventFetcher, vis } from \"@web3-storage/pail/clock\";\nimport * as Batch from \"@web3-storage/pail/crdt/batch\";\nimport {\n type EncryptedBlockstore,\n CarTransaction,\n BlockFetcher,\n TransactionMeta,\n AnyLink,\n StoreRuntime,\n BaseBlockstore,\n CompactFetcher,\n} from \"./blockstore/index.js\";\nimport {\n type IndexKeyType,\n type DocUpdate,\n type ClockHead,\n type DocValue,\n type CRDTMeta,\n type ChangesOptions,\n type DocFileMeta,\n type DocFiles,\n type DocSet,\n type DocWithId,\n type DocTypes,\n throwFalsy,\n} from \"./types.js\";\nimport { Result } from \"@web3-storage/pail/crdt/api\";\nimport { Logger } from \"@adviser/cement\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction time(tag: string) {\n // console.time(tag)\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction timeEnd(tag: string) {\n // console.timeEnd(tag)\n}\n\nfunction toString<K extends IndexKeyType>(key: K, logger: Logger): string {\n switch (typeof key) {\n case \"string\":\n case \"number\":\n return key.toString();\n default:\n throw logger.Error().Msg(\"Invalid key type\").AsError();\n }\n}\n\nexport async function applyBulkUpdateToCrdt<T extends DocTypes>(\n store: StoreRuntime,\n tblocks: CarTransaction,\n head: ClockHead,\n updates: DocUpdate<T>[],\n logger: Logger,\n): Promise<CRDTMeta> {\n let result: Result | null = null;\n if (updates.length > 1) {\n const batch = await Batch.create(tblocks, head);\n for (const update of updates) {\n const link = await writeDocContent(store, tblocks, update, logger);\n await batch.put(toString(update.id, logger), link);\n }\n result = await batch.commit();\n } else if (updates.length === 1) {\n const link = await writeDocContent(store, tblocks, updates[0], logger);\n result = await put(tblocks, head, toString(updates[0].id, logger), link);\n }\n if (!result) throw logger.Error().Uint64(\"updates.len\", updates.length).Msg(\"Missing result\").AsError();\n\n if (result.event) {\n for (const { cid, bytes } of [\n ...result.additions,\n // ...result.removals,\n result.event,\n ]) {\n tblocks.putSync(cid, bytes);\n }\n }\n return { head: result.head } as CRDTMeta;\n}\n\n// this whole thing can get pulled outside of the write queue\nasync function writeDocContent<T extends DocTypes>(\n store: StoreRuntime,\n blocks: CarTransaction,\n update: DocUpdate<T>,\n logger: Logger,\n): Promise<AnyLink> {\n let value: Partial<DocValue<T>>;\n if (update.del) {\n value = { del: true };\n } else {\n if (!update.value) throw logger.Error().Msg(\"Missing value\").AsError();\n await processFiles(store, blocks, update.value, logger);\n value = { doc: update.value as DocWithId<T> };\n }\n const block = await encode({ value, hasher, codec });\n blocks.putSync(block.cid, block.bytes);\n return block.cid;\n}\n\nasync function processFiles<T extends DocTypes>(store: StoreRuntime, blocks: CarTransaction, doc: DocSet<T>, logger: Logger) {\n if (doc._files) {\n await processFileset(logger, store, blocks, doc._files);\n }\n if (doc._publicFiles) {\n await processFileset(logger, store, blocks, doc._publicFiles /*, true*/);\n }\n}\n\nasync function processFileset(\n logger: Logger,\n store: StoreRuntime,\n blocks: CarTransaction,\n files: DocFiles /*, publicFiles = false */,\n) {\n const dbBlockstore = blocks.parent as EncryptedBlockstore;\n if (!dbBlockstore.loader) throw logger.Error().Msg(\"Missing loader, database name is required\").AsError();\n const t = new CarTransaction(dbBlockstore); // maybe this should move to encrypted-blockstore\n const didPut = [];\n // let totalSize = 0\n for (const filename in files) {\n if (File === files[filename].constructor) {\n const file = files[filename] as File;\n\n // totalSize += file.size\n const { cid, blocks: fileBlocks } = await store.encodeFile(file);\n didPut.push(filename);\n for (const block of fileBlocks) {\n t.putSync(block.cid, block.bytes);\n }\n files[filename] = { cid, type: file.type, size: file.size } as DocFileMeta;\n } else {\n const { cid, type, size, car } = files[filename] as DocFileMeta;\n if (cid && type && size && car) {\n files[filename] = { cid, type, size, car };\n }\n }\n }\n\n if (didPut.length) {\n const car = await dbBlockstore.loader.commitFiles(\n t,\n { files } as unknown as TransactionMeta /* {\n public: publicFiles,\n } */,\n );\n if (car) {\n for (const name of didPut) {\n files[name] = { car, ...files[name] } as DocFileMeta;\n }\n }\n }\n}\n\nexport async function getValueFromCrdt<T extends DocTypes>(\n blocks: BaseBlockstore,\n head: ClockHead,\n key: string,\n logger: Logger,\n): Promise<DocValue<T>> {\n if (!head.length) throw logger.Debug().Msg(\"Getting from an empty database\").AsError();\n const link = await get(blocks, head, key);\n if (!link) throw logger.Error().Str(\"key\", key).Msg(`Missing key`).AsError();\n return await getValueFromLink(blocks, link, logger);\n}\n\nexport function readFiles<T extends DocTypes>(blocks: BaseBlockstore, { doc }: Partial<DocValue<T>>) {\n if (!doc) return;\n if (doc._files) {\n readFileset(blocks as EncryptedBlockstore, doc._files);\n }\n if (doc._publicFiles) {\n readFileset(blocks as EncryptedBlockstore, doc._publicFiles, true);\n }\n}\n\nfunction readFileset(blocks: EncryptedBlockstore, files: DocFiles, isPublic = false) {\n for (const filename in files) {\n const fileMeta = files[filename] as DocFileMeta;\n if (fileMeta.cid) {\n if (isPublic) {\n fileMeta.url = `https://${fileMeta.cid.toString()}.ipfs.w3s.link/`;\n }\n if (fileMeta.car) {\n fileMeta.file = async () =>\n await blocks.ebOpts.storeRuntime.decodeFile(\n {\n get: async (cid: AnyLink) => {\n return await blocks.getFile(throwFalsy(fileMeta.car), cid);\n },\n },\n fileMeta.cid,\n fileMeta,\n );\n }\n }\n files[filename] = fileMeta;\n }\n}\n\nasync function getValueFromLink<T extends DocTypes>(blocks: BlockFetcher, link: AnyLink, logger: Logger): Promise<DocValue<T>> {\n const block = await blocks.get(link);\n if (!block) throw logger.Error().Str(\"link\", link.toString()).Msg(`Missing linked block`).AsError();\n const { value } = (await decode({ bytes: block.bytes, hasher, codec })) as { value: DocValue<T> };\n const cvalue = {\n ...value,\n cid: link,\n };\n readFiles(blocks as EncryptedBlockstore, cvalue);\n return cvalue;\n}\n\nclass DirtyEventFetcher<T> extends EventFetcher<T> {\n readonly logger: Logger;\n constructor(logger: Logger, blocks: BlockFetcher) {\n super(blocks);\n this.logger = logger;\n }\n async get(link: EventLink<T>): Promise<EventBlockView<T>> {\n try {\n return super.get(link);\n } catch (e) {\n this.logger.Error().Ref(\"link\", link.toString()).Err(e).Msg(\"Missing event\");\n return { value: undefined } as unknown as EventBlockView<T>;\n }\n }\n}\n\nexport async function clockChangesSince<T extends DocTypes>(\n blocks: BlockFetcher,\n head: ClockHead,\n since: ClockHead,\n opts: ChangesOptions,\n logger: Logger,\n): Promise<{ result: DocUpdate<T>[]; head: ClockHead }> {\n const eventsFetcher = (\n opts.dirty ? new DirtyEventFetcher<Operation>(logger, blocks) : new EventFetcher<Operation>(blocks)\n ) as EventFetcher<Operation>;\n const keys = new Set<string>();\n const updates = await gatherUpdates<T>(\n blocks,\n eventsFetcher,\n head,\n since,\n [],\n keys,\n new Set<string>(),\n opts.limit || Infinity,\n logger,\n );\n return { result: updates.reverse(), head };\n}\n\nasync function gatherUpdates<T extends DocTypes>(\n blocks: BlockFetcher,\n eventsFetcher: EventFetcher<Operation>,\n head: ClockHead,\n since: ClockHead,\n updates: DocUpdate<T>[] = [],\n keys: Set<string>,\n didLinks: Set<string>,\n limit: number,\n logger: Logger,\n): Promise<DocUpdate<T>[]> {\n if (limit <= 0) return updates;\n // if (Math.random() < 0.001) console.log('gatherUpdates', head.length, since.length, updates.length)\n const sHead = head.map((l) => l.toString());\n for (const link of since) {\n if (sHead.includes(link.toString())) {\n return updates;\n }\n }\n for (const link of head) {\n if (didLinks.has(link.toString())) continue;\n didLinks.add(link.toString());\n const { value: event } = await eventsFetcher.get(link);\n if (!event) continue;\n const { type } = event.data;\n let ops = [] as PutOperation[];\n if (type === \"batch\") {\n ops = event.data.ops as PutOperation[];\n } else if (type === \"put\") {\n ops = [event.data] as PutOperation[];\n }\n for (let i = ops.length - 1; i >= 0; i--) {\n const { key, value } = ops[i];\n if (!keys.has(key)) {\n // todo option to see all updates\n const docValue = await getValueFromLink<T>(blocks, value, logger);\n updates.push({ id: key, value: docValue.doc, del: docValue.del, clock: link });\n limit--;\n keys.add(key);\n }\n }\n if (event.parents) {\n updates = await gatherUpdates(blocks, eventsFetcher, event.parents, since, updates, keys, didLinks, limit, logger);\n }\n }\n return updates;\n}\n\nexport async function* getAllEntries<T extends DocTypes>(blocks: BlockFetcher, head: ClockHead, logger: Logger) {\n // return entries(blocks, head)\n for await (const [key, link] of entries(blocks, head)) {\n const docValue = await getValueFromLink(blocks, link, logger);\n yield { id: key, value: docValue.doc, del: docValue.del } as DocUpdate<T>;\n }\n}\n\nexport async function* clockVis(blocks: BlockFetcher, head: ClockHead) {\n for await (const line of vis(blocks, head)) {\n yield line;\n }\n}\n\nlet isCompacting = false;\nexport async function doCompact(blockLog: CompactFetcher, head: ClockHead, logger: Logger) {\n if (isCompacting) {\n // console.log('already compacting')\n return;\n }\n isCompacting = true;\n\n time(\"compact head\");\n for (const cid of head) {\n const bl = await blockLog.get(cid);\n if (!bl) throw logger.Error().Ref(\"cid\", cid).Msg(\"Missing head block\").AsError();\n }\n timeEnd(\"compact head\");\n\n // for await (const blk of blocks.entries()) {\n // const bl = await blockLog.get(blk.cid)\n // if (!bl) throw new Error('Missing tblock: ' + blk.cid.toString())\n // }\n\n // todo maybe remove\n // for await (const blk of blocks.loader!.entries()) {\n // const bl = await blockLog.get(blk.cid)\n // if (!bl) throw new Error('Missing db block: ' + blk.cid.toString())\n // }\n\n time(\"compact all entries\");\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _entry of getAllEntries(blockLog, head, logger)) {\n // result.push(entry)\n // void 1;\n continue;\n }\n timeEnd(\"compact all entries\");\n\n // time(\"compact crdt entries\")\n // for await (const [, link] of entries(blockLog, head)) {\n // const bl = await blockLog.get(link)\n // if (!bl) throw new Error('Missing entry block: ' + link.toString())\n // }\n // timeEnd(\"compact crdt entries\")\n\n time(\"compact clock vis\");\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _line of vis(blockLog, head)) {\n void 1;\n }\n timeEnd(\"compact clock vis\");\n\n time(\"compact root\");\n const result = await root(blockLog, head);\n timeEnd(\"compact root\");\n\n time(\"compact root blocks\");\n for (const { cid, bytes } of [...result.additions, ...result.removals]) {\n blockLog.loggedBlocks.putSync(cid, bytes);\n }\n timeEnd(\"compact root blocks\");\n\n time(\"compact changes\");\n await clockChangesSince(blockLog, head, [], {}, logger);\n timeEnd(\"compact changes\");\n\n isCompacting = false;\n}\n\nexport async function getBlock(blocks: BlockFetcher, cidString: string) {\n const block = await blocks.get(parse(cidString));\n if (!block) throw new Error(`Missing block ${cidString}`);\n const { cid, value } = await decode({ bytes: block.bytes, codec, hasher });\n return new Block({ cid, value, bytes: block.bytes });\n}\n","export * from \"./types.js\";\n\nexport * from \"./store-factory.js\";\nexport * from \"./gateway.js\";\nexport * from \"./fragment-gateway.js\";\n\nimport { type Connectable } from \"./connection-base.js\";\nexport { Connectable };\n\n// import { type CarClockHead, type DbMetaEventBlock } from \"./types.js\";\n// export { CarClockHead, DbMetaEventBlock };\n\nexport { EncryptedBlockstore, BaseBlockstore, CompactionFetcher, type BlockFetcher, CarTransaction } from \"./transaction.js\";\nexport { Loader } from \"./loader.js\";\nexport { parseCarFile } from \"./loader-helpers.js\";\nexport { ConnectionBase } from \"./connection-base.js\";\nexport { setCryptoKeyFromGatewayMetaPayload, addCryptoKeyToGatewayMetaPayload } from \"./meta-key-helper.js\";\n","import type { CID, Link, Version } from \"multiformats\";\nimport type { BlockCodec } from \"../runtime/wait-pr-multiformats/codec-interface\";\nimport { DocFileMeta, Falsy, StoreType, SuperThis } from \"../types.js\";\nimport { BlockFetcher, CarTransaction } from \"./transaction.js\";\nimport { Logger, Result } from \"../utils.js\";\nimport { CommitQueue } from \"./commit-queue.js\";\nimport { KeyBagOpts } from \"../runtime/key-bag.js\";\nimport { CoerceURI, CryptoRuntime, CTCryptoKey, URI } from \"@adviser/cement\";\nimport { EventBlock } from \"@web3-storage/pail/clock\";\nimport { TaskManager } from \"./task-manager\";\n\nexport type AnyLink = Link<unknown, number, number, Version>;\nexport type CarGroup = AnyLink[];\nexport type CarLog = CarGroup[];\nexport type AnyAnyLink = Link<unknown, number, number, Version>;\n\nexport type AnyLinkFn = (cid: AnyLink) => Promise<AnyBlock | undefined>;\n\nexport interface AnyBlock {\n readonly cid: Link<unknown, number, number, Version>;\n readonly bytes: Uint8Array;\n}\n\nexport interface CIDBlock {\n readonly cid: CID<unknown, number, number, Version>;\n readonly bytes: Uint8Array;\n}\n\nexport function toCIDBlock(block: AnyBlock): CIDBlock {\n return block as CIDBlock;\n}\nexport interface AnyAnyBlock {\n readonly cid: AnyAnyLink;\n readonly bytes: Uint8Array;\n}\n\n// export interface EncryptOpts {\n// readonly key: ArrayBuffer;\n// readonly cid: AnyLink;\n// readonly bytes: Uint8Array;\n// }\n\nexport interface IvKeyIdData {\n readonly iv: Uint8Array;\n readonly keyId: Uint8Array;\n readonly data: Uint8Array;\n}\n\nexport interface IvAndBytes {\n readonly bytes: Uint8Array;\n readonly iv: Uint8Array;\n}\n\nexport interface BytesWithIv {\n readonly bytes: Uint8Array;\n readonly iv?: Uint8Array;\n}\n\n// export interface DecryptOpts {\n// readonly key: ArrayBuffer;\n// readonly value: IvAndBytes;\n// }\n\nexport interface AnyDecodedBlock {\n readonly cid: AnyLink;\n readonly bytes: Uint8Array;\n readonly value: Uint8Array;\n}\n\nexport interface CarMakeable {\n entries(): Iterable<AnyBlock>;\n get(cid: AnyLink): Promise<AnyBlock | undefined>;\n}\n\nexport interface CarHeader<T> {\n readonly cars: CarLog;\n readonly compact: CarLog;\n readonly meta: T;\n}\n\n// type NestedData =\n// | Uint8Array\n// | string\n// | number\n// | boolean\n// | undefined\n// | null\n// | AnyLink\n// | NestedData[]\n// | { [key: string]: NestedData };\n\nexport interface TransactionWrapper<M extends TransactionMeta> {\n meta: M;\n cars?: CarGroup;\n t: CarTransaction;\n}\n\nexport type TransactionMeta = unknown;\n//CRDTMeta | IndexTransactionMeta | FileTransactionMeta;\n\n// export interface MakeCodecCrypto {\n// subtle: {\n// decrypt: (algo: { name: string; iv: Uint8Array; tagLength: number }, key: CryptoKey, data: Uint8Array) => Promise<ArrayBuffer>;\n// encrypt: (algo: { name: string; iv: Uint8Array; tagLength: number }, key: CryptoKey, data: Uint8Array) => Promise<ArrayBuffer>;\n// };\n// }\n\n// an implementation of this Interface contains the keymaterial\n// so that the fp-core can use the decrypt and encrypt without knowing the key\nexport interface EncryptedBlock {\n readonly value: IvAndBytes;\n}\n\nexport interface KeyMaterial {\n readonly key: Uint8Array;\n readonly keyStr: string;\n}\n\nexport interface KeyWithFingerPrint {\n readonly fingerPrint: string;\n readonly key: CTCryptoKey;\n}\n\nexport interface KeyWithFingerExtract extends KeyWithFingerPrint {\n extract(): Promise<KeyMaterial>;\n}\n\nexport interface CodecOpts {\n readonly ivCalc: \"random\" | \"hash\";\n readonly noIVVerify: boolean;\n}\nexport interface KeyedCrypto {\n readonly ivLength: number; // in bytes only 12 and 16 are allowed\n readonly logger: Logger;\n readonly crypto: CryptoRuntime;\n readonly url: URI;\n // readonly codec: BlockCodec<number, IvAndBytes>;\n // readonly isEncrypting: boolean;\n fingerPrint(): Promise<string>;\n algo(iv?: Uint8Array): { name: string; iv: Uint8Array; tagLength: number };\n codec(iv?: Uint8Array, codecOpts?: Partial<CodecOpts>): BlockCodec<number, Uint8Array>;\n _decrypt(data: IvAndBytes): Promise<Uint8Array>;\n _encrypt(data: BytesWithIv): Promise<Uint8Array>;\n // encode(data: Uint8Array): Promise<Uint8Array>;\n // decode(bytes: Uint8Array | ArrayBuffer): Promise<Uint8Array>;\n}\n\nexport interface BlobLike {\n /**\n * Returns a ReadableStream which yields the Blob data.\n */\n stream: () => ReadableStream;\n}\n\nexport interface StoreFactory {\n makeMetaStore?: (loader: Loadable) => Promise<MetaStore>;\n makeDataStore?: (loader: Loadable) => Promise<DataStore>;\n makeWALStore?: (loader: Loadable) => Promise<WALStore>;\n\n encodeFile?: (blob: BlobLike) => Promise<{ cid: AnyLink; blocks: AnyBlock[] }>;\n decodeFile?: (blocks: unknown, cid: AnyLink, meta: DocFileMeta) => Promise<File>;\n}\n\nexport interface StoreOpts extends StoreFactory {\n readonly isIndex?: string; // index prefix\n readonly stores?: {\n // string means local storage\n // URL means schema selects the storeType\n readonly base?: CoerceURI;\n\n readonly meta?: CoerceURI;\n readonly data?: CoerceURI;\n readonly index?: CoerceURI;\n readonly wal?: CoerceURI;\n };\n}\n\nexport interface StoreRuntime {\n // the factories should produce ready-to-use stores\n // which means they have to call start() on the store\n // to fullfill lifecycle requirements\n // to release resources, like one database connection\n // for all stores a refcount on close() should be used\n makeMetaStore(loader: Loadable): Promise<MetaStore>;\n makeDataStore(loader: Loadable): Promise<DataStore>;\n makeWALStore(loader: Loadable): Promise<WALStore>;\n encodeFile(blob: BlobLike): Promise<{ cid: AnyLink; blocks: AnyBlock[] }>;\n decodeFile(blocks: unknown, cid: AnyLink, meta: DocFileMeta): Promise<File>;\n}\n\nexport interface CommitOpts {\n readonly noLoader?: boolean;\n readonly compact?: boolean;\n // readonly public?: boolean;\n}\n\nexport interface DbMeta {\n readonly cars: CarGroup;\n key?: string;\n}\n\n// export interface UploadMetaFnParams {\n// readonly name: string;\n// readonly branch: string;\n// }\n\n// export type FnParamTypes = \"data\" | \"file\";\n\n// export interface UploadDataFnParams {\n// readonly type: FnParamTypes;\n// readonly name: string;\n// readonly car: string;\n// readonly size: string;\n// }\n\n// export interface DownloadDataFnParams {\n// readonly type: FnParamTypes;\n// readonly name: string;\n// readonly car: string;\n// }\n\n// export interface DownloadMetaFnParams {\n// readonly name: string;\n// readonly branch: string;\n// }\n\nexport type LoadHandler = (dbMetas: DbMeta[]) => Promise<void>;\n\nexport interface Connection {\n readonly loader?: Loadable;\n readonly loaded: Promise<void>;\n connectMeta_X({ loader }: { loader?: Loadable }): void;\n connectStorage_X({ loader }: { loader?: Loadable }): void;\n\n // metaUpload(bytes: Uint8Array, params: UploadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n // dataUpload(bytes: Uint8Array, params: UploadDataFnParams, opts?: { public?: boolean }): Promise<void>;\n // metaDownload(params: DownloadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n // dataDownload(params: DownloadDataFnParams): Promise<Uint8Array | Falsy>;\n}\n\nexport interface BaseStore {\n readonly storeType: StoreType;\n // readonly url: URI\n url(): URI;\n readonly name: string;\n onStarted(fn: () => void): void;\n onClosed(fn: () => void): void;\n\n keyedCrypto(): Promise<KeyedCrypto>;\n\n close(): Promise<Result<void>>;\n destroy(): Promise<Result<void>>;\n readonly ready?: () => Promise<void>;\n start(): Promise<Result<URI>>;\n}\n\nexport interface MetaStore extends BaseStore {\n readonly storeType: \"meta\";\n load(branch?: string): Promise<DbMeta[] | Falsy>;\n // branch is defaulted to \"main\"\n save(meta: DbMeta, branch?: string): Promise<Result<void>>;\n handleByteHeads(byteHeads: Uint8Array, branch?: string): Promise<{ eventCid: CarClockLink; dbMeta: DbMeta }[]>;\n}\n\nexport interface DataSaveOpts {\n readonly public: boolean;\n}\n\nexport interface DataStore extends BaseStore {\n readonly storeType: \"data\";\n load(cid: AnyLink): Promise<AnyBlock>;\n save(car: AnyBlock, opts?: DataSaveOpts): Promise</*AnyLink | */ void>;\n remove(cid: AnyLink): Promise<Result<void>>;\n}\n\nexport interface WALState {\n operations: DbMeta[];\n noLoaderOps: DbMeta[];\n fileOperations: {\n readonly cid: AnyLink;\n readonly public: boolean;\n }[];\n}\n\nexport interface WALStore extends BaseStore {\n readonly storeType: \"wal\";\n ready(): Promise<void>;\n readonly processing?: Promise<void> | undefined;\n readonly processQueue: CommitQueue<void>;\n\n process(): Promise<void>;\n enqueue(dbMeta: DbMeta, opts: CommitOpts): Promise<void>;\n enqueueFile(fileCid: AnyLink /*, publicFile?: boolean*/): Promise<void>;\n load(): Promise<WALState | Falsy>;\n save(state: WALState): Promise<void>;\n}\n\nexport type CompactFetcher = BlockFetcher & {\n readonly loggedBlocks: CarTransaction;\n};\nexport type CompactFn = (blocks: CompactFetcher) => Promise<TransactionMeta>;\n\nexport type BlockstoreOpts = Partial<{\n readonly logger: Logger;\n readonly applyMeta: (meta: TransactionMeta, snap?: boolean) => Promise<void>;\n readonly compact: CompactFn;\n readonly autoCompact: number;\n readonly crypto: CryptoRuntime;\n readonly store: StoreOpts;\n readonly keyBag: KeyBagOpts;\n readonly public: boolean;\n readonly meta: DbMeta;\n readonly name: string;\n readonly threshold: number;\n}>;\n\nexport interface BlockstoreRuntime {\n readonly logger: Logger;\n readonly applyMeta: (meta: TransactionMeta, snap?: boolean) => Promise<void>;\n readonly compact: CompactFn;\n readonly autoCompact: number;\n readonly crypto: CryptoRuntime;\n readonly store: StoreOpts;\n readonly storeRuntime: StoreRuntime;\n readonly keyBag: Partial<KeyBagOpts>;\n // readonly public: boolean;\n readonly meta?: DbMeta;\n readonly name?: string;\n readonly threshold: number;\n}\n\nexport interface Loadable {\n readonly name: string; // = \"\";\n readonly sthis: SuperThis;\n readonly ebOpts: BlockstoreRuntime;\n remoteCarStore?: DataStore;\n carStore(): Promise<DataStore>;\n carLog: CarLog; // = new Array<CarGroup>();\n remoteMetaStore?: MetaStore;\n remoteFileStore?: DataStore;\n taskManager?: TaskManager;\n ready(): Promise<void>;\n close(): Promise<void>;\n fileStore(): Promise<DataStore>;\n WALStore(): Promise<WALStore>;\n handleDbMetasFromStore(metas: DbMeta[]): Promise<void>;\n}\n\nexport type DbMetaEventBlock = EventBlock<{ dbMeta: Uint8Array }>;\nexport type CarClockLink = Link<DbMetaEventBlock, number, number, Version>;\nexport type CarClockHead = CarClockLink[];\n","import { Logger, KeyedResolvOnce, CoerceURI, URI, Result } from \"@adviser/cement\";\n\nimport { decodeFile, encodeFile } from \"../runtime/files.js\";\nimport { DataStoreImpl, WALStoreImpl, MetaStoreImpl } from \"./store.js\";\nimport { Loadable, StoreOpts, StoreRuntime } from \"./types.js\";\nimport { dataDir, ensureLogger, ensureSuperLog } from \"../utils.js\";\nimport { Gateway, TestGateway } from \"./gateway.js\";\nimport { getKeyBag } from \"../runtime/key-bag.js\";\nimport { SuperThis } from \"../types.js\";\n\nfunction ensureIsIndex(url: URI, isIndex?: string): URI {\n if (isIndex) {\n return url.build().setParam(\"index\", isIndex).URI();\n }\n return url.build().delParam(\"index\").URI();\n}\n\nfunction ensureName(name: string, url: URI): URI {\n if (!url.hasParam(\"name\")) {\n return url.build().setParam(\"name\", name).URI();\n }\n return url;\n}\n\nexport interface GatewayFactoryItem {\n readonly protocol: string;\n readonly overrideBaseURL?: string; // if this set it overrides the defaultURL\n readonly overrideRegistration?: boolean; // if this is set, it will override the registration\n\n readonly gateway: (sthis: SuperThis) => Promise<Gateway>;\n readonly test: (sthis: SuperThis) => Promise<TestGateway>;\n // which switches between file and indexdb\n // readonly data: (logger: Logger) => Promise<Gateway>;\n // readonly meta: (logger: Logger) => Promise<Gateway>;\n // readonly wal: (logger: Logger) => Promise<Gateway>;\n // readonly test: (logger: Logger) => Promise<TestStore>;\n}\n\nconst storeFactory = new Map<string, GatewayFactoryItem>();\n\nfunction buildURL(optURL: CoerceURI, loader: Loadable): URI {\n const storeOpts = loader.ebOpts.store;\n const obuItem = Array.from(storeFactory.values()).find((items) => items.overrideBaseURL);\n let obuUrl: URI | undefined;\n if (obuItem && obuItem.overrideBaseURL) {\n obuUrl = URI.from(obuItem.overrideBaseURL);\n }\n const ret = ensureIsIndex(\n URI.from(optURL || obuUrl || dataDir(loader.sthis, loader.name, storeOpts.stores?.base)),\n storeOpts.isIndex,\n );\n // console.log(\"buildURL\", storeOpts.isIndex);\n return ret;\n}\n\ninterface GatewayReady {\n readonly gateway: Gateway;\n readonly test: TestGateway;\n}\nconst onceGateway = new KeyedResolvOnce<GatewayReady>();\nexport async function getGatewayFromURL(url: URI, sthis: SuperThis): Promise<GatewayReady | undefined> {\n return onceGateway.get(url.toString()).once(async () => {\n const item = storeFactory.get(url.protocol);\n if (item) {\n const ret = {\n gateway: await item.gateway(sthis),\n test: await item.test(sthis),\n };\n const res = await ret.gateway.start(url);\n if (res.isErr()) {\n sthis.logger.Error().Result(\"start\", res).Msg(\"start failed\");\n return undefined;\n }\n return ret;\n }\n sthis.logger.Warn().Url(url).Msg(\"unsupported protocol\");\n return undefined;\n });\n}\n\nexport function registerStoreProtocol(item: GatewayFactoryItem): () => void {\n let protocol = item.protocol;\n if (!protocol.endsWith(\":\")) {\n protocol += \":\";\n }\n if (storeFactory.has(protocol)) {\n if (!item.overrideBaseURL && storeFactory.get(protocol) !== item) {\n throw new Error(`we need a logger here`);\n // const logger = ensureLogger(sthis, \"registerStoreProtocol\", { protocol });\n // logger.Warn().Msg(`protocol ${protocol} already registered`);\n return () => {\n /* no-op */\n };\n }\n }\n // we need to clear the overrideBaseURL if it is set\n if (item.overrideBaseURL) {\n Array.from(storeFactory.values()).forEach((items) => {\n (\n items as {\n overrideBaseURL?: string;\n }\n ).overrideBaseURL = undefined;\n });\n }\n storeFactory.set(protocol, item);\n return () => {\n storeFactory.delete(protocol);\n };\n}\n\n// function runStoreFactory<T>(url: URI, logger: Logger, run: (item: StoreFactoryItem) => Promise<T>): Promise<T> {\n// // const store = url.getParam(\"store\");\n// // if (!store) {\n// // throw logger.Error().Url(url).Msg(\"store not found\").AsError();\n// // }\n// // const key = `${url.protocol}:${store}`;\n// const item = storeFactory.get(url.protocol);\n// if (!item) {\n// throw logger\n// .Error()\n// .Url(url.asURL())\n// .Str(\"protocol\", url.protocol)\n// .Any(\"keys\", Array(storeFactory.keys()))\n// .Msg(`unsupported protocol`)\n// .AsError();\n// }\n// logger.Debug().Str(\"protocol\", url.protocol).Msg(\"run\");\n// return run(item);\n// }\n\n// const onceLoadDataGateway = new KeyedResolvOnce<Gateway>();\n// function loadDataGateway(url: URI, logger: Logger) {\n// return onceLoadDataGateway.get(url.protocol).once(async () => {\n// return await getGatewayFromURL(url, logger).then((item) => {\n// if (!item) {\n// throw logger.Error().Url(url).Msg(\"unsupported protocol or store\").AsError();\n// }\n// return item;\n// });\n// })\n// }\n\nconst onceDataStoreFactory = new KeyedResolvOnce<DataStoreImpl>();\nasync function dataStoreFactory(loader: Loadable): Promise<DataStoreImpl> {\n const url = ensureName(loader.name, buildURL(loader.ebOpts.store.stores?.data, loader)).build().setParam(\"store\", \"data\").URI();\n const sthis = ensureSuperLog(loader.sthis, \"dataStoreFactory\", { url: url.toString() });\n return onceDataStoreFactory.get(url.toString()).once(async () => {\n const gateway = await getGatewayFromURL(url, sthis);\n if (!gateway) {\n throw sthis.logger.Error().Url(url).Msg(\"gateway not found\").AsError();\n }\n const store = new DataStoreImpl(sthis, loader.name, url, {\n gateway: gateway.gateway,\n keybag: () =>\n getKeyBag(loader.sthis, {\n ...loader.ebOpts.keyBag,\n }),\n });\n return store;\n });\n}\n\n// const onceLoadMetaGateway = new KeyedResolvOnce<Gateway>();\n// function loadMetaGateway(url: URI, logger: Logger) {\n// return onceLoadMetaGateway.get(url.protocol).once(async () => {\n// return await getGatewayFromURL(url, logger).then((item) => {\n// if (!item) {\n// throw logger.Error().Url(url).Msg(\"unsupported protocol or store\").AsError();\n// }\n// return item;\n// });\n// });\n// }\n\nconst onceMetaStoreFactory = new KeyedResolvOnce<MetaStoreImpl>();\nasync function metaStoreFactory(loader: Loadable): Promise<MetaStoreImpl> {\n const url = ensureName(loader.name, buildURL(loader.ebOpts.store.stores?.meta, loader)).build().setParam(\"store\", \"meta\").URI();\n const sthis = ensureSuperLog(loader.sthis, \"metaStoreFactory\", { url: () => url.toString() });\n return onceMetaStoreFactory.get(url.toString()).once(async () => {\n sthis.logger.Debug().Str(\"protocol\", url.protocol).Msg(\"pre-protocol switch\");\n const gateway = await getGatewayFromURL(url, sthis);\n if (!gateway) {\n throw sthis.logger.Error().Url(url).Msg(\"gateway not found\").AsError();\n }\n const store = new MetaStoreImpl(loader.sthis, loader.name, url, {\n gateway: gateway.gateway,\n keybag: () =>\n getKeyBag(loader.sthis, {\n ...loader.ebOpts.keyBag,\n }),\n });\n // const ret = await store.start();\n // if (ret.isErr()) {\n // throw logger.Error().Result(\"start\", ret).Msg(\"start failed\").AsError();\n // }\n // logger.Debug().Url(ret.Ok(), \"prepared\").Msg(\"produced\");\n return store;\n });\n}\n\n// const onceWalGateway = new KeyedResolvOnce<Gateway>();\n// function loadWalGateway(url: URI, logger: Logger) {\n// return onceWalGateway.get(url.protocol).once(async () => {\n// return await getGatewayFromURL(url, logger).then((item) => {\n// if (!item) {\n// throw logger.Error().Url(url).Msg(\"unsupported protocol or store\").AsError();\n// }\n// return item;\n// });\n// });\n// }\n\nconst onceRemoteWalFactory = new KeyedResolvOnce<WALStoreImpl>();\nasync function remoteWalFactory(loader: Loadable): Promise<WALStoreImpl> {\n const url = ensureName(loader.name, buildURL(loader.ebOpts.store.stores?.wal, loader)).build().setParam(\"store\", \"wal\").URI();\n const sthis = ensureSuperLog(loader.sthis, \"remoteWalFactory\", { url: url.toString() });\n return onceRemoteWalFactory.get(url.toString()).once(async () => {\n const gateway = await getGatewayFromURL(url, sthis);\n if (!gateway) {\n throw sthis.logger.Error().Url(url).Msg(\"gateway not found\").AsError();\n }\n sthis.logger.Debug().Str(\"prepared\", url.toString()).Msg(\"produced\");\n const store = new WALStoreImpl(loader, url, {\n gateway: gateway.gateway,\n keybag: () =>\n getKeyBag(loader.sthis, {\n ...loader.ebOpts.keyBag,\n }),\n });\n // const ret = await store.start();\n // if (ret.isErr()) {\n // throw logger.Error().Result(\"start\", ret).Msg(\"start failed\").AsError();\n // }\n // logger.Debug().Url(ret.Ok(), \"prepared\").Msg(\"produced\");\n return store;\n });\n}\n\nexport async function testStoreFactory(url: URI, sthis: SuperThis): Promise<TestGateway> {\n sthis = ensureSuperLog(sthis, \"testStoreFactory\");\n const gateway = await getGatewayFromURL(url, sthis);\n if (!gateway) {\n throw sthis.logger.Error().Url(url).Msg(\"gateway not found\").AsError();\n }\n return gateway.test;\n}\n\nexport async function ensureStart<T>(store: T & { start: () => Promise<Result<URI>> }, logger: Logger): Promise<T> {\n const ret = await store.start();\n if (ret.isErr()) {\n throw logger.Error().Result(\"start\", ret).Msg(\"start failed\").AsError();\n }\n logger.Debug().Url(ret.Ok(), \"prepared\").Msg(\"produced\");\n return store;\n}\n\nexport function toStoreRuntime(opts: StoreOpts, sthis: SuperThis): StoreRuntime {\n const logger = ensureLogger(sthis, \"toStoreRuntime\", {});\n return {\n makeMetaStore: async (loader: Loadable) => {\n logger\n .Debug()\n .Str(\"fromOpts\", \"\" + !!loader.ebOpts.store.makeMetaStore)\n .Msg(\"makeMetaStore\");\n return ensureStart(await (loader.ebOpts.store.makeMetaStore || metaStoreFactory)(loader), logger);\n },\n makeDataStore: async (loader: Loadable) => {\n logger\n .Debug()\n .Str(\"fromOpts\", \"\" + !!loader.ebOpts.store.makeDataStore)\n .Msg(\"makeDataStore\");\n return ensureStart(await (loader.ebOpts.store.makeDataStore || dataStoreFactory)(loader), logger);\n },\n makeWALStore: async (loader: Loadable) => {\n logger\n .Debug()\n .Str(\"fromOpts\", \"\" + !!loader.ebOpts.store.makeWALStore)\n .Msg(\"makeRemoteWAL\");\n return ensureStart(await (loader.ebOpts.store.makeWALStore || remoteWalFactory)(loader), logger);\n },\n\n encodeFile: opts.encodeFile || encodeFile,\n decodeFile: opts.decodeFile || decodeFile,\n };\n}\n\nregisterStoreProtocol({\n protocol: \"file:\",\n gateway: async (sthis) => {\n const { FileGateway } = await import(\"../runtime/gateways/file/gateway.js\");\n return new FileGateway(sthis);\n },\n test: async (sthis) => {\n const { FileTestStore } = await import(\"../runtime/gateways/file/gateway.js\");\n return new FileTestStore(sthis);\n },\n});\n\nregisterStoreProtocol({\n protocol: \"indexdb:\",\n gateway: async (sthis) => {\n const { IndexDBGateway } = await import(\"../runtime/gateways/indexdb/gateway.js\");\n return new IndexDBGateway(sthis);\n },\n test: async (sthis) => {\n const { IndexDBTestStore } = await import(\"../runtime/gateways/indexdb/gateway.js\");\n return new IndexDBTestStore(sthis);\n },\n});\n","import * as UnixFS from \"@ipld/unixfs\";\nimport * as raw from \"multiformats/codecs/raw\";\nimport { withMaxChunkSize } from \"@ipld/unixfs/file/chunker/fixed\";\nimport { withWidth } from \"@ipld/unixfs/file/layout/balanced\";\n\nimport type { View } from \"@ipld/unixfs\";\nimport { DocFileMeta } from \"../types.js\";\n\nimport { exporter, ReadableStorage } from \"ipfs-unixfs-exporter\";\nimport { BlobLike, AnyLink, AnyBlock } from \"../blockstore/index.js\";\n\nconst queuingStrategy = UnixFS.withCapacity();\n\nconst settings = UnixFS.configure({\n fileChunkEncoder: raw,\n smallFileEncoder: raw,\n chunker: withMaxChunkSize(1024 * 1024),\n fileLayout: withWidth(1024),\n});\n\nasync function collect<T>(collectable: ReadableStream<T>): Promise<T[]> {\n const chunks: T[] = [];\n await collectable.pipeTo(\n new WritableStream({\n write(chunk) {\n chunks.push(chunk);\n },\n }),\n );\n return chunks;\n}\n\nexport async function encodeFile(blob: BlobLike): Promise<{ cid: AnyLink; blocks: AnyBlock[] }> {\n const readable = createFileEncoderStream(blob);\n const blocks = await collect(readable);\n return { cid: blocks.at(-1).cid, blocks };\n}\n\nexport async function decodeFile(blocks: unknown, cid: AnyLink, meta: DocFileMeta): Promise<File> {\n const entry = await exporter(cid.toString(), blocks as ReadableStorage, { length: meta.size });\n const chunks = [];\n for await (const chunk of entry.content()) {\n chunks.push(chunk);\n }\n return new File(chunks, entry.name, { type: meta.type, lastModified: 0 });\n}\n\nfunction createFileEncoderStream(blob: BlobLike) {\n const { readable, writable } = new TransformStream({}, queuingStrategy);\n const unixfsWriter = UnixFS.createWriter({ writable, settings });\n const fileBuilder = new UnixFSFileBuilder(\"\", blob);\n void (async () => {\n await fileBuilder.finalize(unixfsWriter);\n await unixfsWriter.close();\n })();\n return readable;\n}\n\nclass UnixFSFileBuilder {\n #file;\n readonly name: string;\n constructor(name: string, file: BlobLike) {\n this.name = name;\n this.#file = file;\n }\n\n async finalize(writer: View) {\n const unixfsFileWriter = UnixFS.createFileWriter(writer);\n await this.#file.stream().pipeTo(\n new WritableStream({\n async write(chunk) {\n await unixfsFileWriter.write(chunk as Uint8Array);\n },\n }),\n );\n return await unixfsFileWriter.close();\n }\n}\n","import { format, parse, ToString } from \"@ipld/dag-json\";\nimport { exception2Result, Logger, ResolveOnce, Result, URI } from \"@adviser/cement\";\nimport type {\n AnyBlock,\n AnyLink,\n CommitOpts,\n DataSaveOpts,\n DataStore,\n DbMeta,\n WALStore as WALStore,\n WALState,\n KeyedCrypto,\n Loadable,\n MetaStore,\n LoadHandler,\n CarClockHead,\n CarClockLink,\n} from \"./types.js\";\nimport { Falsy, StoreType, SuperThis, throwFalsy } from \"../types.js\";\nimport { Gateway } from \"./gateway.js\";\nimport { ensureLogger, isNotFoundError } from \"../utils.js\";\nimport { carLogIncludesGroup } from \"./loader.js\";\nimport { CommitQueue } from \"./commit-queue.js\";\nimport { keyedCryptoFactory } from \"../runtime/keyed-crypto.js\";\nimport { KeyBag } from \"../runtime/key-bag.js\";\nimport { FragmentGateway } from \"./fragment-gateway.js\";\nimport { createDbMetaEventBlock, decodeGatewayMetaBytesToDbMeta, encodeEventsWithParents } from \"./meta-key-helper.js\";\nimport pRetry from \"p-retry\";\nimport pMap from \"p-map\";\n\nfunction guardVersion(url: URI): Result<URI> {\n if (!url.hasParam(\"version\")) {\n return Result.Err(`missing version: ${url.toString()}`);\n }\n return Result.Ok(url);\n}\n\nexport interface StoreOpts {\n readonly gateway: Gateway;\n readonly keybag: () => Promise<KeyBag>;\n readonly loader?: Loadable;\n}\n\nexport abstract class BaseStoreImpl {\n // should be injectable\n\n abstract readonly storeType: StoreType;\n readonly name: string;\n\n private _url: URI;\n readonly logger: Logger;\n readonly sthis: SuperThis;\n readonly gateway: FragmentGateway;\n readonly keybag: () => Promise<KeyBag>;\n readonly loader?: Loadable;\n constructor(name: string, url: URI, opts: StoreOpts, sthis: SuperThis, logger: Logger) {\n this.name = name;\n this._url = url;\n this.keybag = opts.keybag;\n this.sthis = sthis;\n this.logger = logger\n .With()\n .Ref(\"url\", () => this._url.toString())\n .Str(\"name\", name)\n .Logger();\n this.gateway = new FragmentGateway(this.sthis, opts.gateway);\n this.loader = opts.loader;\n }\n\n url(): URI {\n return this._url;\n }\n\n readonly _onStarted: (() => void)[] = [];\n onStarted(fn: () => void) {\n this._onStarted.push(fn);\n }\n readonly _onClosed: (() => void)[] = [];\n onClosed(fn: () => void) {\n this._onClosed.push(fn);\n }\n abstract close(): Promise<Result<void>>;\n\n async ready() {\n return;\n }\n\n async keyedCrypto(): Promise<KeyedCrypto> {\n return keyedCryptoFactory(this._url, await this.keybag(), this.sthis);\n }\n\n async start(): Promise<Result<URI>> {\n this.logger.Debug().Str(\"storeType\", this.storeType).Msg(\"starting-gateway-pre\");\n this._url = this._url.build().setParam(\"store\", this.storeType).URI();\n const res = await this.gateway.start(this._url);\n if (res.isErr()) {\n this.logger.Error().Result(\"gw-start\", res).Msg(\"started-gateway\");\n return res as Result<URI>;\n }\n this._url = res.Ok();\n // add storekey to url\n const kb = await this.keybag();\n const skRes = await kb.ensureKeyFromUrl(this._url, () => {\n const idx = this._url.getParam(\"index\");\n const storeKeyName = [this.name];\n if (idx) {\n storeKeyName.push(idx);\n }\n storeKeyName.push(this.storeType);\n return storeKeyName.join(\":\");\n });\n if (skRes.isErr()) {\n return skRes as Result<URI>;\n }\n this._url = skRes.Ok();\n const version = guardVersion(this._url);\n if (version.isErr()) {\n this.logger.Error().Result(\"version\", version).Msg(\"guardVersion\");\n await this.close();\n return version;\n }\n if (this.ready) {\n const fn = this.ready.bind(this);\n const ready = await exception2Result(fn);\n if (ready.isErr()) {\n await this.close();\n return ready as Result<URI>;\n }\n }\n this._onStarted.forEach((fn) => fn());\n this.logger.Debug().Msg(\"started\");\n return version;\n }\n}\n\nexport class MetaStoreImpl extends BaseStoreImpl implements MetaStore {\n readonly storeType = \"meta\";\n readonly subscribers = new Map<string, LoadHandler[]>();\n parents: CarClockHead = [];\n // remote: boolean;\n\n constructor(sthis: SuperThis, name: string, url: URI, opts: StoreOpts) {\n // const my = new URL(url.toString());\n // my.searchParams.set(\"storekey\", 'insecure');\n super(name, url, { ...opts }, sthis, ensureLogger(sthis, \"MetaStoreImpl\"));\n // this.remote = !!remote;\n if (/*this.remote && */ opts.gateway.subscribe) {\n this.onStarted(async () => {\n this.logger.Debug().Str(\"url\", this.url().toString()).Msg(\"Subscribing to the gateway\");\n opts.gateway.subscribe?.(this.url(), async (message: Uint8Array) => {\n this.logger.Debug().Msg(\"Received message from gateway\");\n const dbMetas = await decodeGatewayMetaBytesToDbMeta(this.sthis, message);\n await Promise.all(\n dbMetas.map((dbMeta) => this.loader?.taskManager?.handleEvent(dbMeta.eventCid, dbMeta.parents, dbMeta.dbMeta)),\n );\n this.updateParentsFromDbMetas(dbMetas);\n });\n });\n }\n }\n\n private updateParentsFromDbMetas(dbMetas: { eventCid: CarClockLink; parents: string[] }[]) {\n const cids = dbMetas.map((m) => m.eventCid);\n const dbMetaParents = dbMetas.flatMap((m) => m.parents);\n const uniqueParentsMap = new Map([...this.parents, ...cids].map((p) => [p.toString(), p]));\n const dbMetaParentsSet = new Set(dbMetaParents.map((p) => p.toString()));\n this.parents = Array.from(uniqueParentsMap.values()).filter((p) => !dbMetaParentsSet.has(p.toString()));\n }\n\n async handleByteHeads(byteHeads: Uint8Array) {\n return await decodeGatewayMetaBytesToDbMeta(this.sthis, byteHeads);\n }\n\n async load(): Promise<DbMeta[] | Falsy> {\n const branch = \"main\";\n const url = await this.gateway.buildUrl(this.url(), branch);\n if (url.isErr()) {\n throw this.logger.Error().Result(\"buildUrl\", url).Str(\"branch\", branch).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n const bytes = await this.gateway.get(url.Ok());\n if (bytes.isErr()) {\n if (isNotFoundError(bytes)) {\n return undefined;\n }\n throw this.logger.Error().Url(url.Ok()).Result(\"bytes:\", bytes).Msg(\"gateway get\").AsError();\n }\n const dbMetas = await this.handleByteHeads(bytes.Ok());\n await this.loader?.handleDbMetasFromStore(dbMetas.map((m) => m.dbMeta)); // the old one didn't await\n this.updateParentsFromDbMetas(dbMetas);\n return dbMetas.map((m) => m.dbMeta);\n }\n\n async save(meta: DbMeta, branch?: string): Promise<Result<void>> {\n branch = branch || \"main\";\n this.logger.Debug().Str(\"branch\", branch).Any(\"meta\", meta).Msg(\"saving meta\");\n const event = await createDbMetaEventBlock(this.sthis, meta, this.parents);\n const bytes = await encodeEventsWithParents(this.sthis, [event], this.parents);\n const url = await this.gateway.buildUrl(this.url(), branch);\n if (url.isErr()) {\n throw this.logger.Error().Err(url.Err()).Str(\"branch\", branch).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n this.parents = [event.cid];\n const res = await this.gateway.put(url.Ok(), bytes);\n if (res.isErr()) {\n throw this.logger.Error().Err(res.Err()).Msg(\"got error from gateway.put\").AsError();\n }\n // await this.loader?.handleDbMetasFromStore([meta]);\n // this.loader?.taskManager?.eventsWeHandled.add(event.cid.toString());\n return res;\n }\n\n async close(): Promise<Result<void>> {\n await this.gateway.close(this.url());\n this._onClosed.forEach((fn) => fn());\n return Result.Ok(undefined);\n }\n async destroy(): Promise<Result<void>> {\n return this.gateway.destroy(this.url());\n }\n}\n\nexport class DataStoreImpl extends BaseStoreImpl implements DataStore {\n readonly storeType = \"data\";\n // readonly tag: string = \"car-base\";\n\n constructor(sthis: SuperThis, name: string, url: URI, opts: StoreOpts) {\n super(name, url, { ...opts }, sthis, ensureLogger(sthis, \"DataStoreImpl\"));\n }\n\n async load(cid: AnyLink): Promise<AnyBlock> {\n this.logger.Debug().Any(\"cid\", cid).Msg(\"loading\");\n const url = await this.gateway.buildUrl(this.url(), cid.toString());\n if (url.isErr()) {\n throw this.logger.Error().Err(url.Err()).Str(\"cid\", cid.toString()).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n const res = await this.gateway.get(url.Ok());\n if (res.isErr()) {\n throw res.Err();\n }\n return { cid, bytes: res.Ok() };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async save(car: AnyBlock, opts?: DataSaveOpts): Promise</*AnyLink | */ void> {\n this.logger.Debug().Any(\"cid\", car.cid.toString()).Msg(\"saving\");\n const url = await this.gateway.buildUrl(this.url(), car.cid.toString());\n if (url.isErr()) {\n throw this.logger.Error().Err(url.Err()).Ref(\"cid\", car.cid).Msg(\"got error from gateway.buildUrl\").AsError();\n }\n const res = await this.gateway.put(url.Ok(), car.bytes);\n if (res.isErr()) {\n throw this.logger.Error().Err(res.Err()).Msg(\"got error from gateway.put\").AsError();\n }\n return res.Ok();\n }\n async remove(cid: AnyLink): Promise<Result<void>> {\n const url = await this.gateway.buildUrl(this.url(), cid.toString());\n if (url.isErr()) {\n return url;\n }\n return this.gateway.delete(url.Ok());\n }\n async close(): Promise<Result<void>> {\n await this.gateway.close(this.url());\n this._onClosed.forEach((fn) => fn());\n return Result.Ok(undefined);\n }\n destroy(): Promise<Result<void>> {\n return this.gateway.destroy(this.url());\n }\n}\n\nexport class WALStoreImpl extends BaseStoreImpl implements WALStore {\n readonly storeType = \"wal\";\n // readonly tag: string = \"rwal-base\";\n\n readonly loader: Loadable;\n\n readonly _ready = new ResolveOnce<void>();\n\n walState: WALState = { operations: [], noLoaderOps: [], fileOperations: [] };\n readonly processing: Promise<void> | undefined = undefined;\n readonly processQueue: CommitQueue<void> = new CommitQueue<void>();\n\n constructor(loader: Loadable, url: URI, opts: StoreOpts) {\n // const my = new URL(url.toString());\n // my.searchParams.set(\"storekey\", 'insecure');\n super(loader.name, url, { ...opts }, loader.sthis, ensureLogger(loader.sthis, \"WALStoreImpl\"));\n this.loader = loader;\n }\n\n async ready(): Promise<void> {\n return this._ready.once(async () => {\n const walState = await this.load().catch((e) => {\n this.logger.Error().Any(\"error\", e).Msg(\"error loading wal\");\n return undefined;\n });\n if (!walState) {\n this.walState.operations = [];\n this.walState.fileOperations = [];\n } else {\n this.walState.operations = walState.operations || [];\n this.walState.fileOperations = walState.fileOperations || [];\n }\n });\n }\n\n async enqueue(dbMeta: DbMeta, opts: CommitOpts) {\n await this.ready();\n if (opts.compact) {\n this.walState.operations = [];\n this.walState.noLoaderOps = [dbMeta];\n } else if (opts.noLoader) {\n this.walState.noLoaderOps.push(dbMeta);\n } else {\n this.walState.operations.push(dbMeta);\n }\n await this.save(this.walState);\n if (!opts.noLoader) {\n void this.process();\n }\n }\n\n async enqueueFile(fileCid: AnyLink, publicFile = false) {\n await this.ready();\n this.walState.fileOperations.push({ cid: fileCid, public: publicFile });\n // await this.save(this.walState)\n }\n\n async process() {\n await this.ready();\n if (!this.loader.remoteCarStore) return;\n await this.processQueue.enqueue(async () => {\n try {\n await this._doProcess();\n } catch (e) {\n this.logger.Error().Any(\"error\", e).Msg(\"error processing wal\");\n }\n if (this.walState.operations.length || this.walState.fileOperations.length || this.walState.noLoaderOps.length) {\n setTimeout(() => void this.process(), 0);\n }\n });\n }\n\n async _doProcess() {\n if (!this.loader.remoteCarStore) return;\n\n const operations = [...this.walState.operations];\n const noLoaderOps = [...this.walState.noLoaderOps];\n const fileOperations = [...this.walState.fileOperations];\n\n if (operations.length + noLoaderOps.length + fileOperations.length === 0) return;\n\n const concurrencyLimit = 3;\n\n // Helper function to retry uploads\n const retryableUpload = <T>(fn: () => Promise<T>, description: string) =>\n pRetry(fn, {\n retries: 5,\n onFailedAttempt: (error) => {\n this.logger\n .Warn()\n .Msg(`Attempt ${error.attemptNumber} failed for ${description}. There are ${error.retriesLeft} retries left.`);\n },\n });\n\n try {\n // Process noLoaderOps\n await pMap(\n noLoaderOps,\n async (dbMeta) => {\n await retryableUpload(async () => {\n for (const cid of dbMeta.cars) {\n const car = await (await this.loader.carStore()).load(cid);\n if (!car) {\n if (carLogIncludesGroup(this.loader.carLog, dbMeta.cars)) {\n throw this.logger.Error().Ref(\"cid\", cid).Msg(\"missing local car\").AsError();\n }\n } else {\n await throwFalsy(this.loader.remoteCarStore).save(car);\n }\n }\n // Remove from walState after successful upload\n this.walState.noLoaderOps = this.walState.noLoaderOps.filter((op) => op !== dbMeta);\n }, `noLoaderOp with dbMeta.cars=${dbMeta.cars.toString()}`);\n },\n { concurrency: concurrencyLimit },\n );\n\n // Process operations\n await pMap(\n operations,\n async (dbMeta) => {\n await retryableUpload(async () => {\n for (const cid of dbMeta.cars) {\n const car = await (await this.loader.carStore()).load(cid);\n if (!car) {\n if (carLogIncludesGroup(this.loader.carLog, dbMeta.cars)) {\n throw this.logger.Error().Ref(\"cid\", cid).Msg(`missing local car`).AsError();\n }\n } else {\n await throwFalsy(this.loader.remoteCarStore).save(car);\n }\n }\n // Remove from walState after successful upload\n this.walState.operations = this.walState.operations.filter((op) => op !== dbMeta);\n }, `operation with dbMeta.cars=${dbMeta.cars.toString()}`);\n },\n { concurrency: concurrencyLimit },\n );\n\n // Process fileOperations\n await pMap(\n fileOperations,\n async ({ cid: fileCid, public: publicFile }) => {\n await retryableUpload(async () => {\n const fileBlock = await (await this.loader.fileStore()).load(fileCid);\n if (!fileBlock) {\n throw this.logger.Error().Ref(\"cid\", fileCid).Msg(\"missing file block\").AsError();\n }\n await this.loader.remoteFileStore?.save(fileBlock, { public: publicFile });\n // Remove from walState after successful upload\n this.walState.fileOperations = this.walState.fileOperations.filter((op) => op.cid !== fileCid);\n }, `fileOperation with cid=${fileCid.toString()}`);\n },\n { concurrency: concurrencyLimit },\n );\n\n // If all uploads succeeded, send the last dbMeta to remoteMetaStore\n if (operations.length) {\n const lastOp = operations[operations.length - 1];\n await retryableUpload(async () => {\n await this.loader.remoteMetaStore?.save(lastOp);\n }, `remoteMetaStore save with dbMeta.cars=${lastOp.cars.toString()}`);\n }\n } catch (error) {\n // Log the error\n this.logger.Error().Any(\"error\", error).Msg(\"Processing failed\");\n // Do not proceed to send metadata if any uploads failed\n return;\n } finally {\n // Always save the WAL state\n await this.save(this.walState);\n }\n }\n\n async load(): Promise<WALState | Falsy> {\n this.logger.Debug().Msg(\"loading\");\n const filepath = await this.gateway.buildUrl(this.url(), \"main\");\n if (filepath.isErr()) {\n throw this.logger.Error().Err(filepath.Err()).Url(this.url()).Msg(\"error building url\").AsError();\n }\n const bytes = await this.gateway.get(filepath.Ok());\n if (bytes.isErr()) {\n if (isNotFoundError(bytes)) {\n return undefined;\n }\n throw this.logger.Error().Err(bytes.Err()).Msg(\"error get\").AsError();\n }\n try {\n return bytes && parse<WALState>(this.sthis.txt.decode(bytes.Ok()));\n } catch (e) {\n throw this.logger.Error().Err(e).Msg(\"error parse\").AsError();\n }\n }\n\n async save(state: WALState) {\n const filepath = await this.gateway.buildUrl(this.url(), \"main\");\n if (filepath.isErr()) {\n throw this.logger.Error().Err(filepath.Err()).Url(this.url()).Msg(\"error building url\").AsError();\n }\n let encoded: ToString<WALState>;\n try {\n encoded = format(state);\n } catch (e) {\n throw this.logger.Error().Err(e).Any(\"state\", state).Msg(\"error format\").AsError();\n }\n const res = await this.gateway.put(filepath.Ok(), this.sthis.txt.encode(encoded));\n if (res.isErr()) {\n throw this.logger.Error().Err(res.Err()).Str(\"filePath\", filepath.Ok().toString()).Msg(\"error saving\").AsError();\n }\n }\n\n async close() {\n await this.gateway.close(this.url());\n this._onClosed.forEach((fn) => fn());\n return Result.Ok(undefined);\n }\n\n destroy() {\n return this.gateway.destroy(this.url());\n }\n}\n","import type { EventLink } from \"@web3-storage/pail/clock/api\";\nimport type { Operation } from \"@web3-storage/pail/crdt/api\";\n\nimport type { DbMeta, StoreOpts, AnyLink } from \"./blockstore/index.js\";\nimport { EnvFactoryOpts, Env, Logger, CryptoRuntime } from \"@adviser/cement\";\n\nimport type { MakeDirectoryOptions, PathLike, Stats } from \"fs\";\n\nexport type Falsy = false | null | undefined;\n\nexport function isFalsy(value: unknown): value is Falsy {\n return value === false && value === null && value === undefined;\n}\n\nexport function throwFalsy<T>(value: T | Falsy): T {\n if (isFalsy(value)) {\n throw new Error(\"value is Falsy\");\n }\n return value;\n}\n\nexport function falsyToUndef<T>(value: T | Falsy): T | undefined {\n if (isFalsy(value)) {\n return undefined;\n }\n return value;\n}\n\nexport type StoreType = \"data\" | \"wal\" | \"meta\";\n\nexport interface SysFileSystem {\n start(): Promise<SysFileSystem>;\n mkdir(path: PathLike, options?: { recursive: boolean }): Promise<string | undefined>;\n readdir(path: PathLike, options?: unknown): Promise<string[]>;\n rm(path: PathLike, options?: MakeDirectoryOptions & { recursive: boolean }): Promise<void>;\n copyFile(source: PathLike, destination: PathLike): Promise<void>;\n readfile(path: PathLike, options?: { encoding: BufferEncoding; flag?: string }): Promise<Uint8Array>;\n stat(path: PathLike): Promise<Stats>;\n unlink(path: PathLike): Promise<void>;\n writefile(path: PathLike, data: Uint8Array | string): Promise<void>;\n}\n\nexport interface PathOps {\n join(...args: string[]): string;\n dirname(path: string): string;\n // homedir(): string;\n}\n\n// export interface Sys {\n// // fs: SysFileSystem;\n// fsHelper: PathOps;\n// }\nexport interface TextEndeCoder {\n encode(input: string): Uint8Array;\n decode(input: Uint8Array): string;\n}\nexport interface SuperThisOpts {\n // readonly crypto?: CryptoRuntime;\n readonly logger: Logger;\n readonly pathOps: PathOps;\n readonly crypto: CryptoRuntime;\n readonly env: EnvFactoryOpts;\n readonly txt: TextEndeCoder;\n readonly ctx: Record<string, unknown>;\n}\n\nexport interface SuperThis {\n readonly logger: Logger;\n readonly env: Env;\n readonly pathOps: PathOps;\n readonly ctx: Record<string, unknown>;\n readonly txt: TextEndeCoder;\n nextId(bytes?: number): { str: string; bin: Uint8Array };\n timeOrderedNextId(time?: number): { str: string };\n start(): Promise<void>;\n clone(override: Partial<SuperThisOpts>): SuperThis;\n}\n\nexport interface ConfigOpts extends Partial<SuperThisOpts> {\n readonly public?: boolean;\n readonly meta?: DbMeta;\n readonly persistIndexes?: boolean;\n readonly autoCompact?: number;\n readonly store?: StoreOpts;\n readonly threshold?: number;\n}\n\nexport type ClockLink = EventLink<Operation>;\n\nexport type ClockHead = ClockLink[];\n\nexport type DocFragment = Uint8Array | string | number | boolean | null | AnyLink | DocFragment[] | object;\n// | { [key: string]: DocFragment };\n\nexport type DocLiteral = string | number | boolean | Uint8Array | unknown;\n\nexport type DocObject = NonNullable<unknown>;\nexport type DocTypes = DocObject;\n\nexport type DocRecord<T extends DocObject> = T;\n\nexport type UnknownDoc = DocRecord<never>;\n\nexport type DocFiles = Record<string, DocFileMeta | File>;\n\nexport interface DocBase {\n readonly _id: string;\n readonly _files?: DocFiles;\n readonly _publicFiles?: DocFiles;\n readonly _deleted?: boolean;\n}\n\nexport type DocWithId<T extends DocTypes> = DocBase & T;\n\nexport type DocSet<T extends DocTypes> = Partial<DocBase> & T;\n\nexport interface DocFileMeta {\n readonly type: string;\n readonly size: number;\n readonly cid: AnyLink;\n readonly car?: AnyLink;\n url?: string;\n file?: () => Promise<File>;\n}\n\nexport interface DocUpdate<T extends DocTypes> {\n readonly id: string;\n readonly value?: DocSet<T>;\n readonly del?: boolean;\n readonly clock?: ClockLink; // would be useful to give ClockLinks a type\n}\n\n// todo merge into above\nexport interface DocValue<T extends DocTypes> {\n readonly doc: DocWithId<T>;\n readonly del: boolean;\n readonly cid: AnyLink;\n}\n\nexport type KeyLiteral = string | number | boolean;\nexport type IndexKeyType = KeyLiteral | KeyLiteral[];\nexport type IndexKey<K extends IndexKeyType> = [K, string];\n\nexport interface IndexUpdate<K extends IndexKeyType> {\n readonly key: IndexKey<K>;\n readonly value?: DocFragment;\n readonly del?: boolean;\n}\n\nexport interface IndexUpdateString {\n readonly key: string;\n readonly value?: DocFragment;\n readonly del?: boolean;\n}\n\n// export interface IndexRowObject<K extends IndexKeyType, T extends DocObject> {\n// readonly id: string;\n// readonly key: K;\n// readonly value: T\n// // readonly row: T // DocFragment;\n// // readonly doc?: DocWithId<T>;\n// // value?: T;\n// // readonly del?: boolean;\n// }\n\n// export interface IndexRowLiteral<K extends IndexKeyType, T extends DocLiteral> {\n// readonly id: string;\n// readonly key: IndexKey<K>;\n// readonly value: T\n// }\n\n// export type IndexRow<K extends IndexKeyType, T extends DocTypes> =\n// T extends DocLiteral ? IndexRowLiteral<K, T> : IndexRowObject<K, T>\n\nexport interface IndexRow<K extends IndexKeyType, T extends DocObject, R extends DocFragment> {\n readonly id: string;\n readonly key: K; // IndexKey<K>;\n readonly value: R;\n readonly doc?: DocWithId<T>;\n}\n\nexport interface IndexRows<K extends IndexKeyType, T extends DocObject, R extends DocFragment = T> {\n readonly rows: IndexRow<K, T, R>[];\n}\nexport interface CRDTMeta {\n readonly head: ClockHead;\n}\n\nexport interface IndexTransactionMeta {\n readonly indexes: Record<string, IdxMeta>;\n}\n\nexport interface FileTransactionMeta {\n readonly files?: AnyLink[];\n}\n\nexport type MetaType = CRDTMeta | IndexTransactionMeta | FileTransactionMeta;\n\nexport interface IdxMeta {\n readonly byId: AnyLink;\n readonly byKey: AnyLink;\n readonly map: string;\n readonly name: string;\n readonly head: ClockHead;\n}\n\nexport interface IdxMetaMap {\n readonly indexes?: Map<string, IdxMeta>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface QueryOpts<K extends IndexKeyType> {\n readonly descending?: boolean;\n readonly limit?: number;\n includeDocs?: boolean;\n readonly range?: [IndexKeyType, IndexKeyType];\n readonly key?: DocFragment;\n readonly keys?: DocFragment[];\n prefix?: IndexKeyType;\n}\n\nexport interface AllDocsQueryOpts extends QueryOpts<string> {\n readonly key?: string;\n readonly keys?: string[];\n prefix?: string;\n}\n\nexport interface AllDocsResponse<T extends DocTypes> {\n readonly rows: {\n readonly key: string;\n readonly value: DocWithId<T>;\n }[];\n readonly clock: ClockHead;\n readonly name?: string;\n}\n\ntype EmitFn = (k: IndexKeyType, v?: DocFragment) => void;\nexport type MapFn<T extends DocTypes> = (doc: DocWithId<T>, emit: EmitFn) => DocFragment | unknown;\n\nexport interface ChangesOptions {\n readonly dirty?: boolean;\n readonly limit?: number;\n}\n\nexport interface ChangesResponseRow<T extends DocTypes> {\n readonly key: string;\n readonly value: DocWithId<T>;\n readonly clock?: ClockLink;\n}\n\nexport interface ChangesResponse<T extends DocTypes> {\n readonly clock: ClockHead;\n readonly rows: ChangesResponseRow<T>[];\n readonly name?: string;\n}\n\nexport interface DocResponse {\n readonly id: string;\n readonly clock: ClockHead;\n readonly name?: string;\n}\n\nexport type UpdateListenerFn<T extends DocTypes> = (docs: DocWithId<T>[]) => Promise<void> | void;\nexport type NoUpdateListenerFn = () => Promise<void> | void;\nexport type ListenerFn<T extends DocTypes> = UpdateListenerFn<T> | NoUpdateListenerFn;\n\nexport interface CRDTEntry {\n data: string;\n parents: string[];\n cid: string;\n}\n","import pLimit from \"p-limit\";\nimport { CarReader } from \"@ipld/car\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n// import { uuidv4 } from \"uuidv7\";\n\nimport {\n type AnyBlock,\n type AnyLink,\n type CarHeader,\n type CommitOpts,\n type DbMeta,\n type TransactionMeta,\n type CarGroup,\n type CarLog,\n DataStore,\n WALStore,\n // RemoteMetaStore,\n MetaStore,\n BaseStore,\n type Loadable,\n BlockstoreRuntime,\n BlockstoreOpts,\n} from \"./types.js\";\n\nimport { parseCarFile } from \"./loader-helpers.js\";\n\nimport { CarTransaction, defaultedBlockstoreRuntime } from \"./transaction.js\";\nimport { CommitQueue } from \"./commit-queue.js\";\nimport type { Falsy, SuperThis } from \"../types.js\";\nimport { getKeyBag, KeyBag } from \"../runtime/key-bag.js\";\nimport { commit, commitFiles, CommitParams } from \"./commitor.js\";\nimport { decode } from \"../runtime/wait-pr-multiformats/block.js\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport { TaskManager } from \"./task-manager.js\";\n\nexport function carLogIncludesGroup(list: CarLog, cids: CarGroup) {\n return list.some((arr: CarGroup) => {\n return arr.toString() === cids.toString();\n });\n}\n\n// this works for car groups because toString looks like bafy,bafy\nfunction uniqueCids(list: CarLog, remove = new Set<string>()): CarLog {\n const byString = new Map<string, CarGroup>();\n for (const cid of list) {\n if (remove.has(cid.toString())) continue;\n byString.set(cid.toString(), cid);\n }\n return [...byString.values()];\n}\n\n// export interface DecoderAndCarReader extends CarReader {\n// readonly decoder: BlockDecoder<number, Uint8Array>;\n// }\n\nexport class Loader implements Loadable {\n readonly name: string;\n readonly ebOpts: BlockstoreRuntime;\n readonly commitQueue: CommitQueue<CarGroup> = new CommitQueue<CarGroup>();\n readonly isCompacting = false;\n readonly carReaders: Map<string, Promise<CarReader>> = new Map<string, Promise<CarReader>>();\n readonly seenCompacted: Set<string> = new Set<string>();\n readonly processedCars: Set<string> = new Set<string>();\n readonly sthis: SuperThis;\n readonly taskManager?: TaskManager;\n\n carLog: CarLog = [];\n // key?: string;\n // keyId?: string;\n remoteMetaStore?: MetaStore;\n remoteCarStore?: DataStore;\n remoteFileStore?: DataStore;\n\n private getBlockCache = new Map<string, AnyBlock>();\n private seenMeta = new Set<string>();\n private writeLimit = pLimit(1);\n\n // readonly id = uuidv4();\n\n async keyBag(): Promise<KeyBag> {\n return getKeyBag(this.sthis, this.ebOpts.keyBag);\n }\n\n async carStore(): Promise<DataStore> {\n return this.ebOpts.storeRuntime.makeDataStore(this);\n }\n\n async fileStore(): Promise<DataStore> {\n return this.ebOpts.storeRuntime.makeDataStore(this);\n }\n async WALStore(): Promise<WALStore> {\n return this.ebOpts.storeRuntime.makeWALStore(this);\n }\n\n async metaStore(): Promise<MetaStore> {\n return this.ebOpts.storeRuntime.makeMetaStore(this);\n }\n\n readonly onceReady: ResolveOnce<void> = new ResolveOnce<void>();\n async ready(): Promise<void> {\n return this.onceReady.once(async () => {\n const metas = await (await this.metaStore()).load();\n if (this.ebOpts.meta) {\n await this.handleDbMetasFromStore([this.ebOpts.meta]);\n } else if (metas) {\n await this.handleDbMetasFromStore(metas);\n }\n });\n }\n\n async close() {\n const toClose = await Promise.all([this.carStore(), this.metaStore(), this.fileStore(), this.WALStore()]);\n await Promise.all(toClose.map((store) => store.close()));\n }\n\n async destroy() {\n const toDestroy = await Promise.all([this.carStore(), this.metaStore(), this.fileStore(), this.WALStore()]);\n await Promise.all(toDestroy.map((store) => store.destroy()));\n }\n\n readonly logger: Logger;\n constructor(name: string, ebOpts: BlockstoreOpts, sthis: SuperThis) {\n this.name = name;\n // console.log(\"Loader\", name, ebOpts)\n this.sthis = sthis;\n this.ebOpts = defaultedBlockstoreRuntime(\n sthis,\n {\n ...ebOpts,\n name,\n },\n \"Loader\",\n );\n this.logger = this.ebOpts.logger;\n this.taskManager = new TaskManager(sthis, async (dbMeta: DbMeta) => {\n await this.handleDbMetasFromStore([dbMeta]);\n });\n }\n\n // async snapToCar(carCid: AnyLink | string) {\n // await this.ready\n // if (typeof carCid === 'string') {\n // carCid = CID.parse(carCid)\n // }\n // const carHeader = await this.loadCarHeaderFromMeta({ car: carCid, key: this.key || null })\n // this.carLog = [carCid, ...carHeader.cars]\n // await this.getMoreReaders(carHeader.cars)\n // await this._applyCarHeader(carHeader, true)\n // }\n\n async handleDbMetasFromStore(metas: DbMeta[]): Promise<void> {\n this.logger.Debug().Any(\"metas\", metas).Msg(\"handleDbMetasFromStore\");\n for (const meta of metas) {\n await this.writeLimit(async () => {\n await this.mergeDbMetaIntoClock(meta);\n });\n }\n }\n\n async mergeDbMetaIntoClock(meta: DbMeta): Promise<void> {\n if (this.isCompacting) {\n throw this.logger.Error().Msg(\"cannot merge while compacting\").AsError();\n }\n\n if (this.seenMeta.has(meta.cars.toString())) return;\n this.seenMeta.add(meta.cars.toString());\n\n // if (meta.key) {\n // await this.setKey(meta.key);\n // }\n if (carLogIncludesGroup(this.carLog, meta.cars)) {\n return;\n }\n const carHeader = await this.loadCarHeaderFromMeta<TransactionMeta>(meta);\n // fetch other cars down the compact log?\n // todo we should use a CID set for the compacted cids (how to expire?)\n // console.log('merge carHeader', carHeader.head.length, carHeader.head.toString(), meta.car.toString())\n carHeader.compact.map((c) => c.toString()).forEach(this.seenCompacted.add, this.seenCompacted);\n await this.getMoreReaders(carHeader.cars.flat());\n this.carLog = [...uniqueCids([meta.cars, ...this.carLog, ...carHeader.cars], this.seenCompacted)];\n await this.ebOpts.applyMeta?.(carHeader.meta);\n }\n\n // protected async ingestKeyFromMeta(meta: DbMeta): Promise<void> {\n // const { key } = meta;\n // if (key) {\n // await this.setKey(key);\n // }\n // }\n\n async loadCarHeaderFromMeta<T>({ cars: cids }: DbMeta): Promise<CarHeader<T>> {\n //Call loadCar for every cid\n const reader = await this.loadCar(cids[0]);\n return await parseCarFile(reader, this.logger);\n }\n\n // async _getKey(): Promise<string | undefined> {\n // if (this.key) return this.key;\n // // generate a random key\n // if (!this.ebOpts.public) {\n // await this.setKey(toHexString(this.ebOpts.crypto.randomBytes(32)));\n // }\n // return this.key || undefined;\n // }\n\n async commitFiles(\n t: CarTransaction,\n done: TransactionMeta,\n // opts: CommitOpts = { noLoader: false, compact: false },\n ): Promise<CarGroup> {\n await this.ready();\n const fstore = await this.fileStore();\n const wstore = await this.WALStore();\n return this.commitQueue.enqueue(() => commitFiles(fstore, wstore, t, done));\n }\n\n async loadFileCar(cid: AnyLink /*, isPublic = false*/): Promise<CarReader> {\n return await this.storesLoadCar(cid, await this.fileStore(), this.remoteFileStore);\n }\n\n async commit<T = TransactionMeta>(\n t: CarTransaction,\n done: T,\n opts: CommitOpts = { noLoader: false, compact: false },\n ): Promise<CarGroup> {\n await this.ready();\n const fstore = await this.fileStore();\n const params: CommitParams = {\n encoder: (await fstore.keyedCrypto()).codec(),\n carLog: this.carLog,\n carStore: fstore,\n WALStore: await this.WALStore(),\n metaStore: await this.metaStore(),\n threshold: this.ebOpts.threshold,\n };\n return this.commitQueue.enqueue(async () => {\n await this.cacheTransaction(t);\n const ret = await commit(params, t, done, opts);\n await this.updateCarLog(ret.cgrp, ret.header, !!opts.compact);\n return ret.cgrp;\n });\n }\n\n async updateCarLog<T>(cids: CarGroup, fp: CarHeader<T>, compact: boolean): Promise<void> {\n if (compact) {\n const previousCompactCid = fp.compact[fp.compact.length - 1];\n fp.compact.map((c) => c.toString()).forEach(this.seenCompacted.add, this.seenCompacted);\n this.carLog = [...uniqueCids([...this.carLog, ...fp.cars, cids], this.seenCompacted)];\n await this.removeCidsForCompact(previousCompactCid[0]).catch((e) => e);\n } else {\n this.carLog.unshift(cids);\n }\n }\n\n async cacheTransaction(t: CarTransaction) {\n for await (const block of t.entries()) {\n const sBlock = block.cid.toString();\n if (!this.getBlockCache.has(sBlock)) {\n this.getBlockCache.set(sBlock, block);\n }\n }\n }\n\n async cacheCarReader(carCidStr: string, reader: CarReader) {\n if (this.processedCars.has(carCidStr)) return;\n this.processedCars.add(carCidStr);\n for await (const block of reader.blocks()) {\n const sBlock = block.cid.toString();\n if (!this.getBlockCache.has(sBlock)) {\n this.getBlockCache.set(sBlock, block);\n }\n }\n }\n\n async removeCidsForCompact(cid: AnyLink) {\n const carHeader = await this.loadCarHeaderFromMeta({\n cars: [cid],\n } as unknown as DbMeta);\n for (const cids of carHeader.compact) {\n for (const cid of cids) {\n await (await this.carStore()).remove(cid);\n }\n }\n }\n\n // async flushCars() {\n // await this.ready\n // // for each cid in car log, make a dbMeta\n // for (const cid of this.carLog) {\n // const dbMeta = { car: cid, key: this.key || null } as DbMeta\n // await this.remoteWAL!.enqueue(dbMeta, { public: false })\n // }\n // }\n\n async *entries(cache = true): AsyncIterableIterator<AnyBlock> {\n await this.ready();\n if (cache) {\n for (const [, block] of this.getBlockCache) {\n yield block;\n }\n } else {\n for (const [, block] of this.getBlockCache) {\n yield block;\n }\n for (const cids of this.carLog) {\n for (const cid of cids) {\n const reader = await this.loadCar(cid);\n if (!reader) throw this.logger.Error().Ref(\"cid\", cid).Msg(\"missing car reader\").AsError();\n for await (const block of reader.blocks()) {\n const sCid = block.cid.toString();\n if (!this.getBlockCache.has(sCid)) {\n yield block;\n }\n }\n }\n }\n }\n }\n\n async getBlock(cid: AnyLink): Promise<AnyBlock | Falsy> {\n await this.ready();\n const sCid = cid.toString();\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n\n const getCarCid = async (carCid: AnyLink) => {\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n const reader = await this.loadCar(carCid);\n if (!reader) {\n throw this.logger.Error().Ref(\"cid\", carCid).Msg(\"missing car reader\").AsError();\n }\n await this.cacheCarReader(carCid.toString(), reader).catch(() => {\n return;\n });\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n throw this.logger.Error().Str(\"cid\", sCid).Msg(\"block not in reader\").AsError();\n };\n\n const getCompactCarCids = async (carCid: AnyLink) => {\n // console.log(\"getCompactCarCids\", carCid.toString())\n\n const reader = await this.loadCar(carCid);\n if (!reader) {\n throw this.logger.Error().Str(\"cid\", carCid.toString()).Msg(\"missing car reader\").AsError();\n }\n\n const header = await parseCarFile(reader, this.logger);\n\n const compacts = header.compact;\n\n let got: AnyBlock | undefined;\n const batchSize = 5;\n for (let i = 0; i < compacts.length; i += batchSize) {\n const promises: Promise<AnyBlock | undefined>[] = [];\n for (let j = i; j < Math.min(i + batchSize, compacts.length); j++) {\n for (const cid of compacts[j]) {\n promises.push(getCarCid(cid));\n }\n }\n try {\n got = await Promise.any(promises);\n } catch {\n // Ignore the error and continue with the next iteration\n }\n if (got) break;\n }\n\n if (this.getBlockCache.has(sCid)) return this.getBlockCache.get(sCid);\n throw this.logger.Error().Str(\"cid\", sCid).Msg(\"block not in compact reader\").AsError();\n };\n\n let got;\n const batchSize = 5;\n for (let i = 0; i < this.carLog.length; i += batchSize) {\n const batch = this.carLog.slice(i, i + batchSize);\n const promises: Promise<AnyBlock | undefined>[] = batch.flatMap((slice) => slice.map(getCarCid));\n try {\n got = await Promise.any(promises);\n } catch {\n // Ignore the error and continue with the next iteration\n }\n if (got) break;\n }\n\n if (!got) {\n try {\n got = await getCompactCarCids(this.carLog[this.carLog.length - 1][0]);\n } catch {\n // Ignore the error and continue with the next iteration\n }\n }\n\n return got;\n }\n\n async loadCar(cid: AnyLink): Promise<CarReader> {\n if (!this.carStore) {\n throw this.logger.Error().Msg(\"car store not initialized\").AsError();\n }\n const loaded = await this.storesLoadCar(cid, await this.carStore(), this.remoteCarStore);\n return loaded;\n }\n\n async makeDecoderAndCarReader(cid: AnyLink, local: DataStore, remote?: DataStore): Promise<CarReader> {\n const cidsString = cid.toString();\n let loadedCar: AnyBlock | undefined = undefined;\n let activeStore: BaseStore = local;\n try {\n //loadedCar now is an array of AnyBlocks\n this.logger.Debug().Str(\"cid\", cidsString).Msg(\"loading car\");\n loadedCar = await local.load(cid);\n this.logger.Debug().Bool(\"loadedCar\", loadedCar).Msg(\"loaded\");\n } catch (e) {\n if (remote) {\n const remoteCar = await remote.load(cid);\n if (remoteCar) {\n // todo test for this\n this.logger.Debug().Ref(\"cid\", remoteCar.cid).Msg(\"saving remote car locally\");\n await local.save(remoteCar);\n loadedCar = remoteCar;\n activeStore = remote;\n }\n } else {\n this.logger.Error().Str(\"cid\", cidsString).Err(e).Msg(\"loading car\");\n }\n }\n if (!loadedCar) {\n throw this.logger.Error().Url(local.url()).Str(\"cid\", cidsString).Msg(\"missing car files\").AsError();\n }\n //This needs a fix as well as the fromBytes function expects a Uint8Array\n //Either we can merge the bytes or return an array of rawReaders\n const bytes = await decode({ bytes: loadedCar.bytes, hasher, codec: (await activeStore.keyedCrypto()).codec() }); // as Uint8Array,\n const rawReader = await CarReader.fromBytes(bytes.value);\n const readerP = Promise.resolve(rawReader);\n // const kc = await activeStore.keyedCrypto()\n // const readerP = !kc.isEncrypting ? Promise.resolve(rawReader) : this.ensureDecryptedReader(activeStore, rawReader);\n\n const cachedReaderP = readerP.then(async (reader) => {\n await this.cacheCarReader(cidsString, reader).catch((e) => {\n this.logger.Error().Err(e).Str(\"cid\", cidsString).Msg(\"error caching car reader\");\n return;\n });\n return reader;\n });\n this.carReaders.set(cidsString, cachedReaderP);\n return readerP;\n }\n\n //What if instead it returns an Array of CarHeader\n protected async storesLoadCar(cid: AnyLink, local: DataStore, remote?: DataStore): Promise<CarReader> {\n const cidsString = cid.toString();\n let dacr = this.carReaders.get(cidsString);\n if (!dacr) {\n dacr = this.makeDecoderAndCarReader(cid, local, remote);\n this.carReaders.set(cidsString, dacr);\n }\n return dacr;\n }\n\n protected async getMoreReaders(cids: AnyLink[]) {\n const limit = pLimit(5);\n const missing = cids.filter((cid) => !this.carReaders.has(cid.toString()));\n await Promise.all(missing.map((cid) => limit(() => this.loadCar(cid))));\n }\n}\n","import { decode } from \"../runtime/wait-pr-multiformats/block.js\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as dagCodec from \"@ipld/dag-cbor\";\nimport type { Logger } from \"@adviser/cement\";\n\nimport { CarHeader } from \"./types.js\";\n// import { decodeRunLength } from \"../runtime/keyed-crypto.js\";\n// import { base58btc } from \"multiformats/bases/base58\";\nimport { CarReader } from \"@ipld/car\";\n\n// export async function encodeCarHeader<T>(fp: CarHeader<T>) {\n// return (await encode({\n// value: { fp },\n// hasher,\n// codec: dagCodec,\n// })) as AnyBlock;\n// }\n\n// function wrapDagDecoder<T>(dec: BlockDecoder<number, Uint8Array>): BlockDecoder<number, CarDecoded<T>> {\n// return {\n// code: dec.code,\n// decode: async (block: Uint8Array) => dagCodec.decode(await dec.decode(block))\n// }\n// }\n\ninterface CarDecoded<T> {\n readonly fp: CarHeader<T>;\n}\n\nexport async function parseCarFile<T>(reader: CarReader, logger: Logger): Promise<CarHeader<T>> {\n const roots = await reader.getRoots();\n const header = await reader.get(roots[0]);\n if (!header) throw logger.Error().Msg(\"missing header block\").AsError();\n const dec = await decode({ bytes: header.bytes, hasher, codec: dagCodec });\n // console.log(\"parseCarFile-done\", roots[0].toString(), header)\n // const { value } = await decode({\n // bytes: header.bytes,\n // hasher,\n // codec: await wrapDagDecoder<T>({\n // code: dagCodec.code,\n // decode: (block) => {\n // const ui = new Uint8Array(block);\n // const iv = decodeRunLength(ui, 0, logger);\n // const key = decodeRunLength(ui, iv.next, logger);\n // // const fp = decodeRunLength(ui, key.next, logger);\n // console.log(\"parseCarFile\", { iv: iv.data.length, key: base58btc.encode(key.data) }, (new Error()).stack);\n // return ui\n // }\n // })\n // });\n const fpvalue = dec.value as CarDecoded<T>;\n // @jchris where is the fp attribute coming from?\n if (fpvalue && !fpvalue.fp) {\n throw logger.Error().Msg(\"missing fp\").AsError();\n }\n return fpvalue.fp;\n}\n","import { MemoryBlockstore } from \"@web3-storage/pail/block\";\nimport { BlockFetcher as BlockFetcherApi } from \"@web3-storage/pail/api\";\n\nimport {\n AnyAnyLink,\n AnyBlock,\n AnyLink,\n CarMakeable,\n TransactionMeta,\n TransactionWrapper,\n BlockstoreOpts,\n BlockstoreRuntime,\n} from \"./types.js\";\n\nimport { Loader } from \"./loader.js\";\nimport type { CID, Block, Version } from \"multiformats\";\nimport { falsyToUndef, SuperThis } from \"../types.js\";\nimport { toStoreRuntime } from \"./store-factory.js\";\nimport { Logger, toCryptoRuntime } from \"@adviser/cement\";\nimport { ensureLogger, ensureSuperThis } from \"../utils.js\";\n\nexport type BlockFetcher = BlockFetcherApi;\n\nexport interface CarTransactionOpts {\n readonly add: boolean;\n readonly noLoader: boolean;\n}\n\nexport class CarTransaction extends MemoryBlockstore implements CarMakeable {\n readonly parent: BaseBlockstore;\n constructor(parent: BaseBlockstore, opts: CarTransactionOpts = { add: true, noLoader: false }) {\n super();\n if (opts.add) {\n parent.transactions.add(this);\n }\n this.parent = parent;\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyLink): Promise<Block<T, C, A, V> | undefined> {\n return ((await this.superGet(cid)) || falsyToUndef(await this.parent.get(cid))) as Block<T, C, A, V>;\n }\n\n async superGet(cid: AnyLink): Promise<AnyBlock | undefined> {\n return super.get(cid);\n }\n}\n\nexport function defaultedBlockstoreRuntime(\n sthis: SuperThis,\n opts: BlockstoreOpts,\n component: string,\n ctx?: Record<string, unknown>,\n): BlockstoreRuntime {\n const logger = ensureLogger(sthis, component, ctx);\n const store = opts.store || {};\n return {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n applyMeta: (meta: TransactionMeta, snap?: boolean): Promise<void> => {\n return Promise.resolve();\n },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n compact: async (blocks: BlockFetcher) => {\n return {} as unknown as TransactionMeta;\n },\n autoCompact: 100,\n public: false,\n name: undefined,\n threshold: 1000 * 1000,\n ...opts,\n logger,\n keyBag: opts.keyBag || {},\n crypto: toCryptoRuntime(opts.crypto),\n store,\n storeRuntime: toStoreRuntime(store, sthis),\n };\n}\n\nexport function blockstoreFactory(sthis: SuperThis, opts: BlockstoreOpts): BaseBlockstore | EncryptedBlockstore {\n if (opts.name) {\n return new EncryptedBlockstore(sthis, opts);\n } else {\n return new BaseBlockstore(opts);\n }\n}\n\nexport class BaseBlockstore implements BlockFetcher {\n readonly transactions: Set<CarTransaction> = new Set<CarTransaction>();\n readonly ebOpts: BlockstoreRuntime;\n readonly sthis: SuperThis;\n\n readonly loader?: Loader;\n readonly name?: string;\n\n // ready: Promise<void>;\n ready(): Promise<void> {\n return Promise.resolve();\n }\n\n async close(): Promise<void> {\n // no-op\n }\n\n async destroy(): Promise<void> {\n // no-op\n }\n\n readonly logger: Logger;\n constructor(ebOpts: BlockstoreOpts = {}) {\n // console.log(\"BaseBlockstore\", ebOpts)\n this.sthis = ensureSuperThis(ebOpts);\n this.ebOpts = defaultedBlockstoreRuntime(this.sthis, ebOpts, \"BaseBlockstore\");\n this.logger = this.ebOpts.logger;\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyAnyLink): Promise<Block<T, C, A, V> | undefined> {\n if (!cid) throw this.logger.Error().Msg(\"required cid\").AsError();\n for (const f of this.transactions) {\n // if (Math.random() < 0.001) console.log('get', cid.toString(), this.transactions.size)\n const v = await f.superGet(cid);\n if (v) return v as Block<T, C, A, V>;\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async put(cid: AnyAnyLink, block: Uint8Array): Promise<void> {\n throw this.logger.Error().Msg(\"use a transaction to put\").AsError();\n }\n\n lastTxMeta?: unknown; // TransactionMeta\n\n async transaction<M extends TransactionMeta>(\n fn: (t: CarTransaction) => Promise<M>,\n _opts?: CarTransactionOpts,\n ): Promise<TransactionWrapper<M>> {\n const t = new CarTransaction(this, _opts);\n const done: M = await fn(t);\n this.lastTxMeta = done;\n return { t, meta: done };\n }\n\n async *entries(): AsyncIterableIterator<AnyBlock> {\n const seen = new Set<string>();\n for (const t of this.transactions) {\n for await (const blk of t.entries()) {\n if (seen.has(blk.cid.toString())) continue;\n seen.add(blk.cid.toString());\n yield blk;\n }\n }\n }\n}\n\nexport class EncryptedBlockstore extends BaseBlockstore {\n readonly name: string;\n readonly loader: Loader;\n\n ready(): Promise<void> {\n return this.loader.ready();\n }\n\n close(): Promise<void> {\n return this.loader.close();\n }\n\n destroy(): Promise<void> {\n return this.loader.destroy();\n }\n\n compacting = false;\n readonly logger: Logger;\n\n constructor(sthis: SuperThis, ebOpts: BlockstoreOpts) {\n super(ebOpts);\n this.logger = ensureLogger(this.sthis, \"EncryptedBlockstore\");\n const { name } = ebOpts;\n if (!name) {\n throw this.logger.Error().Msg(\"name required\").AsError();\n }\n this.name = name;\n this.loader = new Loader(this.name, ebOpts, sthis);\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyAnyLink): Promise<Block<T, C, A, V> | undefined> {\n const got = await super.get(cid);\n if (got) return got as Block<T, C, A, V>;\n if (!this.loader) {\n return;\n }\n return falsyToUndef(await this.loader.getBlock(cid)) as Block<T, C, A, V>;\n }\n\n async transaction<M extends TransactionMeta>(\n fn: (t: CarTransaction) => Promise<M>,\n opts = { noLoader: false },\n ): Promise<TransactionWrapper<M>> {\n const { t, meta: done } = await super.transaction<M>(fn);\n const cars = await this.loader.commit<M>(t, done, opts);\n if (this.ebOpts.autoCompact && this.loader.carLog.length > this.ebOpts.autoCompact) {\n setTimeout(() => void this.compact(), 10);\n }\n if (cars) {\n this.transactions.delete(t);\n return { meta: done, cars, t };\n }\n throw this.logger.Error().Msg(\"failed to commit car files\").AsError();\n }\n\n async getFile(car: AnyLink, cid: AnyLink /*, isPublic = false*/): Promise<Uint8Array> {\n await this.ready();\n if (!this.loader) throw this.logger.Error().Msg(\"loader required to get file, database must be named\").AsError();\n const reader = await this.loader.loadFileCar(car /*, isPublic */);\n const block = await reader.get(cid as CID);\n if (!block) throw this.logger.Error().Str(\"cid\", cid.toString()).Msg(`Missing block`).AsError();\n return block.bytes;\n }\n\n async compact() {\n await this.ready();\n if (!this.loader) throw this.logger.Error().Msg(\"loader required to compact\").AsError();\n if (this.loader.carLog.length < 2) return;\n const compactFn = this.ebOpts.compact || ((blocks: CompactionFetcher) => this.defaultCompact(blocks, this.logger));\n if (!compactFn || this.compacting) return;\n const blockLog = new CompactionFetcher(this);\n this.compacting = true;\n const meta = await compactFn(blockLog);\n await this.loader?.commit(blockLog.loggedBlocks, meta, {\n compact: true,\n noLoader: true,\n });\n this.compacting = false;\n }\n\n async defaultCompact(blocks: CompactionFetcher, logger: Logger): Promise<TransactionMeta> {\n // console.log('eb compact')\n if (!this.loader) {\n throw logger.Error().Msg(\"no loader\").AsError();\n }\n if (!this.lastTxMeta) {\n throw logger.Error().Msg(\"no lastTxMeta\").AsError();\n }\n for await (const blk of this.loader.entries(false)) {\n blocks.loggedBlocks.putSync(blk.cid, blk.bytes);\n }\n for (const t of this.transactions) {\n for await (const blk of t.entries()) {\n blocks.loggedBlocks.putSync(blk.cid, blk.bytes);\n }\n }\n return this.lastTxMeta as TransactionMeta;\n }\n\n async *entries(): AsyncIterableIterator<AnyBlock> {\n // const seen = new Set<string>();\n for await (const blk of this.loader.entries()) {\n // if (seen.has(blk.cid.toString())) continue\n // seen.add(blk.cid.toString())\n yield blk;\n }\n }\n}\n\nexport class CompactionFetcher implements BlockFetcher {\n readonly blockstore: EncryptedBlockstore;\n // loader: Loader | null = null\n readonly loggedBlocks: CarTransaction;\n\n constructor(blocks: EncryptedBlockstore) {\n this.blockstore = blocks;\n // this.loader = blocks.loader\n this.loggedBlocks = new CarTransaction(blocks);\n }\n\n async get<T, C extends number, A extends number, V extends Version>(cid: AnyLink): Promise<Block<T, C, A, V> | undefined> {\n const block = await this.blockstore.get(cid);\n if (block) this.loggedBlocks.putSync(cid, block.bytes);\n return falsyToUndef(block) as Block<T, C, A, V>;\n }\n}\n","import { Future } from \"@adviser/cement\";\n\ntype QueueFunction<T = void> = () => Promise<T>;\n\nexport class CommitQueue<T = void> {\n readonly queue: QueueFunction<void>[] = [];\n processing = false;\n\n readonly _waitIdleItems: Set<Future<void>> = new Set<Future<void>>();\n waitIdle(): Promise<void> {\n if (this.queue.length === 0 && !this.processing) {\n return Promise.resolve();\n }\n const fn = new Future<void>();\n this._waitIdleItems.add(fn);\n return fn.asPromise();\n }\n\n async enqueue(fn: QueueFunction<T>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const queueFn = async () => {\n try {\n resolve(await fn());\n } catch (e) {\n reject(e);\n } finally {\n this.processing = false;\n this.processNext();\n }\n };\n this.queue.push(queueFn);\n if (!this.processing) {\n this.processNext();\n }\n });\n }\n\n processNext() {\n if (this.queue.length > 0 && !this.processing) {\n this.processing = true;\n const queueFn = this.queue.shift();\n if (queueFn) {\n queueFn().finally(() => {\n /**/\n });\n }\n }\n if (this.queue.length === 0 && !this.processing) {\n const toResolve = Array.from(this._waitIdleItems);\n this._waitIdleItems.clear();\n toResolve.map((fn) => fn.resolve());\n }\n }\n}\n","import {\n CoerceURI,\n CryptoRuntime,\n KeyedResolvOnce,\n Logger,\n ResolveOnce,\n ResolveSeq,\n Result,\n runtimeFn,\n toCryptoRuntime,\n URI,\n} from \"@adviser/cement\";\nimport { KeyWithFingerExtract, KeyWithFingerPrint } from \"../blockstore/types.js\";\nimport { ensureLogger } from \"../utils.js\";\nimport { base58btc } from \"multiformats/bases/base58\";\nimport { SuperThis } from \"../types.js\";\n\nexport type { KeyBagProviderFile } from \"./key-bag-file.js\";\nexport type { KeyBagProviderIndexDB } from \"./key-bag-indexdb.js\";\n\nexport class KeyBag {\n readonly logger: Logger;\n constructor(readonly rt: KeyBagRuntime) {\n this.logger = ensureLogger(rt.sthis, \"KeyBag\");\n this.logger.Debug().Msg(\"KeyBag created\");\n }\n\n readonly _warnOnce: ResolveOnce<void> = new ResolveOnce<void>();\n async subtleKey(key: string): Promise<CryptoKey> {\n const extractable = this.rt.url.getParam(\"extractKey\") === \"_deprecated_internal_api\";\n if (extractable) {\n this._warnOnce.once(() =>\n this.logger.Warn().Msg(\"extractKey is enabled via _deprecated_internal_api --- handle keys safely!!!\"),\n );\n }\n return await this.rt.crypto.importKey(\n \"raw\", // raw or jwk\n base58btc.decode(key),\n // hexStringToUint8Array(key), // raw data\n \"AES-GCM\",\n extractable,\n [\"encrypt\", \"decrypt\"],\n );\n }\n\n async ensureKeyFromUrl(url: URI, keyFactory: () => string): Promise<Result<URI>> {\n // add storekey to url\n const storeKey = url.getParam(\"storekey\");\n if (storeKey === \"insecure\") {\n return Result.Ok(url);\n }\n if (!storeKey) {\n const keyName = `@${keyFactory()}@`;\n const ret = await this.getNamedKey(keyName);\n if (ret.isErr()) {\n return ret as unknown as Result<URI>;\n }\n const urb = url.build().setParam(\"storekey\", keyName);\n return Result.Ok(urb.URI());\n }\n if (storeKey.startsWith(\"@\") && storeKey.endsWith(\"@\")) {\n const ret = await this.getNamedKey(storeKey);\n if (ret.isErr()) {\n return ret as unknown as Result<URI>;\n }\n }\n return Result.Ok(url);\n }\n\n async toKeyWithFingerPrint(keyStr: string): Promise<Result<KeyWithFingerPrint>> {\n const material = base58btc.decode(keyStr); //\n const key = await this.subtleKey(keyStr);\n const fpr = await this.rt.crypto.digestSHA256(material);\n return Result.Ok({\n key,\n fingerPrint: base58btc.encode(new Uint8Array(fpr)),\n });\n }\n\n readonly _seq: ResolveSeq<Result<KeyWithFingerPrint>> = new ResolveSeq<Result<KeyWithFingerPrint>>();\n async setNamedKey(name: string, key: string): Promise<Result<KeyWithFingerPrint>> {\n return this._seq.add(() => this._setNamedKey(name, key));\n }\n\n // avoid deadlock\n async _setNamedKey(name: string, key: string): Promise<Result<KeyWithFingerPrint>> {\n const item = {\n name,\n key: key,\n };\n const bag = await this.rt.getBag();\n this.logger.Debug().Str(\"name\", name).Msg(\"setNamedKey\");\n // there should be a version that throws if key exists\n await bag.set(name, item);\n return await this.toKeyWithFingerPrint(item.key);\n }\n\n async getNamedExtractableKey(name: string, failIfNotFound = false): Promise<Result<KeyWithFingerExtract>> {\n const ret = await this.getNamedKey(name, failIfNotFound);\n if (ret.isErr()) {\n return ret as unknown as Result<KeyWithFingerExtract>;\n }\n const named = ret.Ok();\n return Result.Ok({\n ...named,\n extract: async () => {\n const ext = new Uint8Array((await this.rt.crypto.exportKey(\"raw\", named.key)) as ArrayBuffer);\n return {\n key: ext,\n keyStr: base58btc.encode(ext),\n };\n },\n });\n }\n\n async getNamedKey(name: string, failIfNotFound = false): Promise<Result<KeyWithFingerPrint>> {\n const id = this.rt.sthis.nextId(4).str;\n return this._seq.add(async () => {\n const bag = await this.rt.getBag();\n const named = await bag.get(name);\n if (named) {\n const fpr = await this.toKeyWithFingerPrint(named.key);\n this.logger.Debug().Str(\"id\", id).Str(\"name\", name).Result(\"fpr\", fpr).Msg(\"fingerPrint getNamedKey\");\n return fpr;\n }\n if (failIfNotFound) {\n this.logger.Debug().Str(\"id\", id).Str(\"name\", name).Msg(\"failIfNotFound getNamedKey\");\n return Result.Err(new Error(`Key not found: ${name}`));\n }\n // this.logger.Debug().Str(\"id\", id).Str(\"name\", name).Msg(\"createKey getNamedKey-pre\");\n const ret = await this._setNamedKey(name, base58btc.encode(this.rt.crypto.randomBytes(this.rt.keyLength)));\n this.logger.Debug().Str(\"id\", id).Str(\"name\", name).Result(\"fpr\", ret).Msg(\"createKey getNamedKey-post\");\n return ret;\n });\n }\n}\n\nexport interface KeyItem {\n readonly name: string;\n readonly key: string;\n}\nexport type KeyBagFile = Record<string, KeyItem>;\n\nexport interface KeyBagOpts {\n // in future you can encrypt the keybag with ?masterkey=xxxxx\n readonly url: CoerceURI;\n // readonly key: string; // key to encrypt the keybag\n readonly crypto: CryptoRuntime;\n readonly keyLength: number; // default: 16\n // readonly logger: Logger;\n readonly keyRuntime: KeyBagRuntime;\n}\n\nexport interface KeyBagProvider {\n get(id: string): Promise<KeyItem | undefined>;\n set(id: string, item: KeyItem): Promise<void>;\n}\nexport interface KeyBagRuntime {\n readonly url: URI;\n readonly crypto: CryptoRuntime;\n readonly logger: Logger;\n readonly sthis: SuperThis;\n readonly keyLength: number;\n // readonly key?: FPCryptoKey;\n getBag(): Promise<KeyBagProvider>;\n id(): string;\n}\n\nexport type KeyBackProviderFactory = (url: URI, sthis: SuperThis) => Promise<KeyBagProvider>;\n\nexport interface KeyBagProviderFactoryItem {\n readonly protocol: string;\n // if this is set the default protocol selection is overridden\n readonly override?: boolean;\n readonly factory: KeyBackProviderFactory;\n}\n\nconst keyBagProviderFactories = new Map<string, KeyBagProviderFactoryItem>(\n [\n {\n protocol: \"file:\",\n factory: async (url: URI, sthis: SuperThis) => {\n const { KeyBagProviderFile } = await import(\"./key-bag-file.js\");\n return new KeyBagProviderFile(url, sthis);\n },\n },\n {\n protocol: \"indexdb:\",\n factory: async (url: URI, sthis: SuperThis) => {\n const { KeyBagProviderIndexDB } = await import(\"./key-bag-indexdb.js\");\n return new KeyBagProviderIndexDB(url, sthis);\n },\n },\n ].map((i) => [i.protocol, i]),\n);\n\nexport function registerKeyBagProviderFactory(item: KeyBagProviderFactoryItem) {\n const protocol = item.protocol.endsWith(\":\") ? item.protocol : item.protocol + \":\";\n keyBagProviderFactories.set(protocol, {\n ...item,\n protocol,\n });\n}\n\nfunction defaultKeyBagOpts(sthis: SuperThis, kbo: Partial<KeyBagOpts>): KeyBagRuntime {\n if (kbo.keyRuntime) {\n return kbo.keyRuntime;\n }\n const logger = ensureLogger(sthis, \"KeyBag\");\n let url: URI;\n if (kbo.url) {\n url = URI.from(kbo.url);\n logger.Debug().Url(url).Msg(\"from opts\");\n } else {\n let bagFnameOrUrl = sthis.env.get(\"FP_KEYBAG_URL\");\n if (runtimeFn().isBrowser) {\n url = URI.from(bagFnameOrUrl || \"indexdb://fp-keybag\");\n } else {\n if (!bagFnameOrUrl) {\n const home = sthis.env.get(\"HOME\");\n bagFnameOrUrl = `${home}/.fireproof/keybag`;\n url = URI.from(`file://${bagFnameOrUrl}`);\n } else {\n url = URI.from(bagFnameOrUrl);\n }\n }\n logger.Debug().Url(url).Msg(\"from env\");\n }\n const kitem = keyBagProviderFactories.get(url.protocol);\n if (!kitem) {\n throw logger.Error().Url(url).Msg(\"unsupported protocol\").AsError();\n }\n const getBag = async () => kitem.factory(url, sthis);\n\n if (url.hasParam(\"masterkey\")) {\n throw logger.Error().Url(url).Msg(\"masterkey is not supported\").AsError();\n }\n return {\n url,\n crypto: kbo.crypto || toCryptoRuntime({}),\n sthis,\n logger,\n keyLength: kbo.keyLength || 16,\n getBag,\n id: () => {\n return url.toString();\n },\n };\n}\n\nconst _keyBags = new KeyedResolvOnce<KeyBag>();\nexport async function getKeyBag(sthis: SuperThis, kbo: Partial<KeyBagOpts> = {}): Promise<KeyBag> {\n await sthis.start();\n const rt = defaultKeyBagOpts(sthis, kbo);\n return _keyBags.get(rt.id()).once(async () => new KeyBag(rt));\n}\n","import { FileTransactionMeta } from \"../types\";\nimport { CarTransaction } from \"./transaction\";\nimport {\n AnyBlock,\n AnyLink,\n CarGroup,\n CarHeader,\n CarLog,\n CarMakeable,\n CommitOpts,\n DataStore,\n DbMeta,\n MetaStore,\n toCIDBlock,\n TransactionMeta,\n WALStore,\n} from \"./types\";\nimport * as CBW from \"@ipld/car/buffer-writer\";\nimport { CID } from \"multiformats\";\nimport { encode } from \"../runtime/wait-pr-multiformats/block.js\";\nimport { BlockEncoder } from \"../runtime/wait-pr-multiformats/codec-interface.js\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as dagCodec from \"@ipld/dag-cbor\";\n\nasync function encodeCarFile(roots: AnyLink[], t: CarMakeable, codec: BlockEncoder<number, Uint8Array>): Promise<AnyBlock> {\n let size = 0;\n const headerSize = CBW.headerLength({ roots } as { roots: CID<unknown, number, number, 1>[] });\n size += headerSize;\n for (const { cid, bytes } of t.entries()) {\n size += CBW.blockLength({ cid, bytes } as CBW.Block);\n }\n const buffer = new Uint8Array(size);\n const writer = CBW.createWriter(buffer, { headerSize });\n\n for (const r of roots) {\n writer.addRoot(r as CID<unknown, number, number, 1>);\n }\n\n for (const { cid, bytes } of t.entries()) {\n writer.write({ cid, bytes } as CBW.Block);\n }\n writer.close();\n return await encode({ value: writer.bytes, hasher, codec });\n}\n\nexport async function createCarFile(\n encoder: BlockEncoder<number, Uint8Array>,\n cid: AnyLink,\n t: CarTransaction,\n): Promise<{ cid: AnyLink; bytes: Uint8Array }> {\n // try {\n return encodeCarFile([cid], t, encoder);\n // const keycr = await store.keyedCrypto()\n // return keycr.isEncrypting\n // ? await encryptedEncodeCarFile(this.logger, keycr, cid, t)\n // : await encodeCarFile([cid], t);\n // } catch (e) {\n // throw store.logger.Error().Err(e).Msg(\"error creating car file\").AsError();\n // }\n}\n\nexport async function commitFiles(\n fileStore: DataStore,\n walStore: WALStore,\n t: CarTransaction,\n done: TransactionMeta,\n // opts: CommitOpts = { noLoader: false, compact: false },\n): Promise<CarGroup> {\n const { files: roots } = makeFileCarHeader(done as FileTransactionMeta) as {\n files: AnyLink[];\n };\n const cids: AnyLink[] = [];\n // const fileStore = await this.fileStore();\n const codec = (await fileStore.keyedCrypto()).codec();\n const cars = await prepareCarFilesFiles(codec, roots, t);\n for (const car of cars) {\n const { cid, bytes } = car;\n // real deal\n await fileStore.save({ cid, bytes });\n await walStore.enqueueFile(cid /*, !!opts.public*/);\n cids.push(cid);\n }\n return cids;\n}\n\nfunction makeFileCarHeader(result: FileTransactionMeta): TransactionMeta {\n const files: AnyLink[] = [];\n for (const [, meta] of Object.entries(result.files || {})) {\n if (meta && typeof meta === \"object\" && \"cid\" in meta && meta !== null) {\n files.push(meta.cid as AnyLink);\n }\n }\n return { ...result, files };\n}\n\nasync function prepareCarFilesFiles(\n encoder: BlockEncoder<number, Uint8Array>,\n roots: AnyLink[],\n t: CarTransaction,\n // isPublic: boolean,\n): Promise<{ cid: AnyLink; bytes: Uint8Array }[]> {\n // const theKey = isPublic ? null : await this._getKey();\n // const kc = await store.keyedCrypto()\n // const car = kc.isEncrypting\n // ? await encryptedEncodeCarFile(this.logger, kc, roots[0], t)\n // : await encodeCarFile(roots, t);\n return [await encodeCarFile(roots, t, encoder)];\n}\n\n// PUR Commit\n\nfunction makeCarHeader<T>(meta: T, cars: CarLog, compact = false): CarHeader<T> {\n const coreHeader = compact ? { cars: [], compact: cars } : { cars, compact: [] };\n return { ...coreHeader, meta };\n}\n\nasync function encodeCarHeader<T>(fp: CarHeader<T>) {\n return (await encode({\n value: { fp },\n hasher,\n codec: dagCodec,\n })) as AnyBlock;\n}\n\nexport interface CommitParams {\n readonly encoder: BlockEncoder<number, Uint8Array>;\n readonly carLog: CarLog;\n readonly carStore: DataStore;\n readonly WALStore: WALStore;\n readonly metaStore: MetaStore;\n readonly threshold?: number;\n}\n\nexport async function commit<T>(\n params: CommitParams,\n t: CarTransaction,\n done: T,\n opts: CommitOpts = { noLoader: false, compact: false },\n): Promise<{ cgrp: CarGroup; header: CarHeader<T> }> {\n const fp = makeCarHeader<T>(done, params.carLog, !!opts.compact);\n const rootBlock = await encodeCarHeader(fp);\n\n const cars = await prepareCarFiles(params.encoder, params.threshold, rootBlock, t);\n const cids: AnyLink[] = [];\n for (const car of cars) {\n const { cid, bytes } = car;\n await params.carStore.save({ cid, bytes });\n cids.push(cid);\n }\n\n // await this.cacheTransaction(t);\n const newDbMeta = { cars: cids } as DbMeta;\n await params.WALStore.enqueue(newDbMeta, opts);\n await params.metaStore.save(newDbMeta);\n return { cgrp: cids, header: fp };\n}\n\nasync function prepareCarFiles(\n encoder: BlockEncoder<number, Uint8Array>,\n threshold: number | undefined,\n rootBlock: AnyBlock,\n t: CarTransaction,\n): Promise<{ cid: AnyLink; bytes: Uint8Array }[]> {\n // const theKey = isPublic ? undefined : await this._getKey();\n const carFiles: { cid: AnyLink; bytes: Uint8Array }[] = [];\n threshold = threshold || 128000 * 8; // remove the * 8 to fit partykit\n let clonedt = new CarTransaction(t.parent, { add: false, noLoader: false });\n clonedt.putSync(rootBlock.cid, rootBlock.bytes);\n let newsize = CBW.blockLength(toCIDBlock(rootBlock));\n let cidRootBlock = rootBlock;\n for (const { cid, bytes } of t.entries()) {\n newsize += CBW.blockLength(toCIDBlock({ cid: cid, bytes }));\n if (newsize >= threshold) {\n carFiles.push(await createCarFile(encoder, cidRootBlock.cid, clonedt));\n clonedt = new CarTransaction(t.parent, { add: false, noLoader: false });\n clonedt.putSync(cid, bytes);\n cidRootBlock = { cid, bytes };\n newsize = CBW.blockLength(toCIDBlock({ cid, bytes })); //+ CBW.blockLength(rootBlock)\n } else {\n clonedt.putSync(cid, bytes);\n }\n }\n // HEREMENO\n carFiles.push(await createCarFile(encoder, cidRootBlock.cid, clonedt));\n // console.log(\"split to \", carFiles.length, \"files\")\n return carFiles;\n}\n","import { Logger } from \"@adviser/cement\";\nimport type { CarClockLink, DbMeta } from \"./types.js\";\nimport { ensureLogger } from \"../utils.js\";\nimport { SuperThis } from \"../types.js\";\n\ninterface TaskItem {\n readonly cid: string;\n readonly dbMeta: DbMeta;\n retries: number;\n}\n\nexport class TaskManager {\n private readonly eventsWeHandled = new Set<string>();\n\n private queue: TaskItem[] = [];\n private isProcessing = false;\n\n readonly logger: Logger;\n readonly callback: (dbMeta: DbMeta) => Promise<void>;\n constructor(sthis: SuperThis, callback: (dbMeta: DbMeta) => Promise<void>) {\n this.logger = ensureLogger(sthis, \"TaskManager\");\n this.callback = callback;\n }\n\n async handleEvent(cid: CarClockLink, parents: string[], dbMeta: DbMeta) {\n for (const parent of parents) {\n this.eventsWeHandled.add(parent.toString());\n }\n this.queue.push({ cid: cid.toString(), dbMeta, retries: 0 });\n this.queue = this.queue.filter(({ cid }) => !this.eventsWeHandled.has(cid));\n void this.processQueue();\n }\n\n private async processQueue() {\n if (this.isProcessing) return;\n this.isProcessing = true;\n const filteredQueue = this.queue.filter(({ cid }) => !this.eventsWeHandled.has(cid));\n const first = filteredQueue[0];\n if (!first) {\n return;\n }\n try {\n await this.callback(first.dbMeta);\n this.eventsWeHandled.add(first.cid);\n this.queue = this.queue.filter(({ cid }) => !this.eventsWeHandled.has(cid));\n } catch (err) {\n if (first.retries++ > 3) {\n this.logger.Error().Str(\"cid\", first.cid).Msg(\"failed to process event block after 3 retries\");\n this.queue = this.queue.filter(({ cid }) => cid !== first.cid);\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n throw this.logger.Error().Err(err).Msg(\"failed to process event block\").AsError();\n } finally {\n this.isProcessing = false;\n if (this.queue.length > 0) {\n void this.processQueue();\n }\n }\n }\n}\n","import { CryptoRuntime, Logger, URI } from \"@adviser/cement\";\nimport { BytesWithIv, CodecOpts, IvAndBytes, IvKeyIdData, KeyedCrypto, KeyWithFingerPrint } from \"../blockstore\";\nimport { ensureLogger, UInt8ArrayEqual } from \"../utils.js\";\nimport { KeyBag } from \"./key-bag\";\nimport type { BlockCodec } from \"./wait-pr-multiformats/codec-interface\";\nimport { base58btc } from \"multiformats/bases/base58\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as CBOR from \"cborg\";\nimport { SuperThis } from \"../types.js\";\n\ninterface GenerateIVFn {\n calc(ko: KeyedCrypto, crypto: CryptoRuntime, data: Uint8Array): Promise<Uint8Array>;\n verify(ko: KeyedCrypto, crypto: CryptoRuntime, iv: Uint8Array, data: Uint8Array): Promise<boolean>;\n}\n\nconst generateIV: Record<string, GenerateIVFn> = {\n random: {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n calc: async (ko: KeyedCrypto, crypto: CryptoRuntime, data: Uint8Array): Promise<Uint8Array> => {\n return crypto.randomBytes(ko.ivLength);\n },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n verify: async (ko: KeyedCrypto, crypto: CryptoRuntime, iv: Uint8Array, data: Uint8Array): Promise<boolean> => {\n return true;\n },\n },\n hash: {\n calc: async (ko: KeyedCrypto, crypto: CryptoRuntime, data: Uint8Array): Promise<Uint8Array> => {\n const hash = await hasher.digest(data);\n const hashBytes = new Uint8Array(hash.bytes);\n const hashArray = new Uint8Array(ko.ivLength);\n for (let i = 0; i < hashBytes.length; i++) {\n hashArray[i % ko.ivLength] ^= hashBytes[i];\n }\n return hashArray;\n },\n verify: async function (ko: KeyedCrypto, crypto: CryptoRuntime, iv: Uint8Array, data: Uint8Array): Promise<boolean> {\n return ko.url.getParam(\"ivverify\") !== \"disable\" && UInt8ArrayEqual(iv, await this.calc(ko, crypto, data));\n },\n },\n};\n\nfunction getGenerateIVFn(url: URI, opts: Partial<CodecOpts>): GenerateIVFn {\n const ivhash = opts.ivCalc || url.getParam(\"ivhash\") || \"hash\";\n return generateIV[ivhash] || generateIV[\"hash\"];\n}\n\nexport class BlockIvKeyIdCodec implements BlockCodec<0x300539, Uint8Array> {\n readonly code = 0x300539;\n readonly name = \"Fireproof@encrypted-block:aes-gcm\";\n\n readonly ko: KeyedCrypto;\n readonly iv?: Uint8Array;\n readonly opts: Partial<CodecOpts>;\n constructor(ko: KeyedCrypto, iv?: Uint8Array, opts?: CodecOpts) {\n this.ko = ko;\n this.iv = iv;\n this.opts = opts || {};\n }\n\n async encode(data: Uint8Array): Promise<Uint8Array> {\n const calcIv = this.iv || (await getGenerateIVFn(this.ko.url, this.opts).calc(this.ko, this.ko.crypto, data));\n const { iv } = this.ko.algo(calcIv);\n const fprt = await this.ko.fingerPrint();\n const keyId = base58btc.decode(fprt);\n this.ko.logger.Debug().Str(\"fp\", fprt).Msg(\"encode\");\n return CBOR.encode({\n iv: iv,\n keyId: keyId,\n data: await this.ko._encrypt({ iv, bytes: data }),\n } as IvKeyIdData);\n }\n\n async decode(abytes: Uint8Array | ArrayBuffer): Promise<Uint8Array> {\n let bytes: Uint8Array;\n if (abytes instanceof Uint8Array) {\n bytes = abytes;\n } else {\n bytes = new Uint8Array(abytes);\n }\n const { iv, keyId, data } = CBOR.decode(bytes) as IvKeyIdData;\n const fprt = await this.ko.fingerPrint();\n this.ko.logger.Debug().Str(\"fp\", base58btc.encode(keyId)).Msg(\"decode\");\n if (base58btc.encode(keyId) !== fprt) {\n throw this.ko.logger.Error().Str(\"fp\", fprt).Str(\"keyId\", base58btc.encode(keyId)).Msg(\"keyId mismatch\").AsError();\n }\n const result = await this.ko._decrypt({ iv: iv, bytes: data });\n if (!this.opts?.noIVVerify && !(await getGenerateIVFn(this.ko.url, this.opts).verify(this.ko, this.ko.crypto, iv, result))) {\n throw this.ko.logger.Error().Msg(\"iv missmatch\").AsError();\n }\n return result;\n }\n}\n\nclass keyedCrypto implements KeyedCrypto {\n readonly ivLength = 12;\n readonly logger: Logger;\n readonly crypto: CryptoRuntime;\n readonly key: KeyWithFingerPrint;\n readonly isEncrypting = true;\n readonly url: URI;\n constructor(url: URI, key: KeyWithFingerPrint, cyopt: CryptoRuntime, sthis: SuperThis) {\n this.logger = ensureLogger(sthis, \"keyedCrypto\");\n this.crypto = cyopt;\n this.key = key;\n this.url = url;\n }\n fingerPrint(): Promise<string> {\n return Promise.resolve(this.key.fingerPrint);\n }\n codec(iv?: Uint8Array, opts?: CodecOpts): BlockCodec<number, Uint8Array> {\n return new BlockIvKeyIdCodec(this, iv, opts);\n }\n algo(iv?: Uint8Array) {\n return {\n name: \"AES-GCM\",\n iv: iv || this.crypto.randomBytes(this.ivLength),\n tagLength: 128,\n };\n }\n async _decrypt(data: IvAndBytes): Promise<Uint8Array> {\n this.logger.Debug().Len(data.bytes, \"bytes\").Len(data.iv, \"iv\").Str(\"fp\", this.key.fingerPrint).Msg(\"decrypting\");\n return new Uint8Array(await this.crypto.decrypt(this.algo(data.iv), this.key.key, data.bytes));\n }\n async _encrypt(data: BytesWithIv): Promise<Uint8Array> {\n this.logger.Debug().Len(data.bytes).Str(\"fp\", this.key.fingerPrint).Msg(\"encrypting\");\n const a = this.algo(data.iv);\n return new Uint8Array(await this.crypto.encrypt(a, this.key.key, data.bytes));\n }\n}\n\nclass nullCodec implements BlockCodec<0x0, Uint8Array> {\n readonly code = 0x0;\n readonly name = \"Fireproof@unencrypted-block\";\n\n encode(data: Uint8Array): Uint8Array {\n return data;\n }\n decode(data: Uint8Array): Uint8Array {\n return data;\n }\n}\n\nclass noCrypto implements KeyedCrypto {\n readonly ivLength = 0;\n readonly code = 0x0;\n readonly name = \"Fireproof@unencrypted-block\";\n readonly logger: Logger;\n readonly crypto: CryptoRuntime;\n readonly isEncrypting = false;\n readonly _fingerPrint = \"noCrypto:\" + Math.random();\n readonly url: URI;\n constructor(url: URI, cyrt: CryptoRuntime, sthis: SuperThis) {\n this.logger = ensureLogger(sthis, \"noCrypto\");\n this.crypto = cyrt;\n this.url = url;\n }\n\n fingerPrint(): Promise<string> {\n return Promise.resolve(this._fingerPrint);\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n codec(iv?: Uint8Array): BlockCodec<number, Uint8Array> {\n return new nullCodec();\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n algo(iv?: Uint8Array): { name: string; iv: Uint8Array; tagLength: number } {\n return {\n name: \"noCrypto\",\n iv: new Uint8Array(),\n tagLength: 0,\n };\n }\n _decrypt(): Promise<Uint8Array> {\n throw this.logger.Error().Msg(\"noCrypto.decrypt not implemented\").AsError();\n }\n _encrypt(): Promise<Uint8Array> {\n throw this.logger.Error().Msg(\"noCrypto.decrypt not implemented\").AsError();\n }\n}\n\nexport async function keyedCryptoFactory(url: URI, kb: KeyBag, sthis: SuperThis): Promise<KeyedCrypto> {\n const storekey = url.getParam(\"storekey\");\n if (storekey && storekey !== \"insecure\") {\n let rkey = await kb.getNamedKey(storekey, true);\n if (rkey.isErr()) {\n try {\n rkey = await kb.toKeyWithFingerPrint(storekey);\n } catch (e) {\n throw (\n sthis.logger\n .Error()\n .Err(e)\n .Str(\"keybag\", kb.rt.id())\n // .Result(\"key\", rkey)\n .Str(\"name\", storekey)\n .Msg(\"getNamedKey failed\")\n .AsError()\n );\n }\n }\n return new keyedCrypto(url, rkey.Ok(), kb.rt.crypto, sthis);\n }\n return new noCrypto(url, kb.rt.crypto, sthis);\n}\n","import { Logger, Result, URI } from \"@adviser/cement\";\n\nimport { base58btc } from \"multiformats/bases/base58\";\nimport { encode, decode } from \"cborg\";\nimport { Gateway, GetResult, UnsubscribeResult, VoidResult } from \"./gateway.js\";\nimport { SuperThis } from \"../types.js\";\nimport { ensureSuperLog } from \"../utils.js\";\n\nfunction getFragSize(url: URI): number {\n const fragSize = url.getParam(\"fragSize\");\n let ret = 0;\n if (fragSize) {\n ret = parseInt(fragSize);\n }\n if (isNaN(ret) || ret <= 0) {\n ret = 0;\n }\n return ret;\n}\n\nasync function getFrags(url: URI, innerGW: Gateway, headerSize: number, logger: Logger): Promise<Result<Fragment>[]> {\n const fragSize = getFragSize(url);\n if (!fragSize) {\n const res = await innerGW.get(url);\n if (res.isErr()) {\n return [res as unknown as Result<Fragment>];\n }\n const data = res.unwrap();\n return [\n Result.Ok({\n fid: new Uint8Array(0),\n ofs: 0,\n len: data.length,\n data,\n }),\n ];\n }\n const firstRaw = await innerGW.get(url.build().setParam(\"ofs\", \"0\").URI());\n if (firstRaw.isErr()) {\n return [firstRaw as unknown as Result<Fragment>];\n }\n const firstFragment = decode(firstRaw.unwrap()) as Fragment;\n const blockSize = firstFragment.data.length;\n const ops: Promise<Result<Fragment>>[] = [Promise.resolve(Result.Ok(firstFragment))];\n const fidStr = base58btc.encode(firstFragment.fid);\n const fragUrl = url\n .build()\n .setParam(\"fid\", fidStr)\n .setParam(\"len\", firstFragment.len.toString())\n .setParam(\"headerSize\", headerSize.toString());\n\n for (let ofs = blockSize; ofs < firstFragment.len; ofs += blockSize) {\n ops.push(\n (async (furl, ofs): Promise<Result<Fragment>> => {\n const raw = await innerGW.get(furl);\n if (raw.isErr()) {\n return raw as unknown as Result<Fragment>;\n }\n const fragment = decode(raw.unwrap());\n if (base58btc.encode(fragment.fid) !== fidStr) {\n return Result.Err(logger.Error().Msg(\"Fragment fid mismatch\").AsError());\n }\n if (fragment.ofs !== ofs) {\n return Result.Err(logger.Error().Uint64(\"ofs\", ofs).Msg(\"Fragment ofs mismatch\").AsError());\n }\n return Result.Ok(fragment);\n })(fragUrl.setParam(\"ofs\", ofs.toString()).URI(), ofs),\n );\n }\n return Promise.all(ops);\n}\n\ninterface Fragment {\n readonly fid: Uint8Array;\n readonly ofs: number;\n readonly len: number;\n readonly data: Uint8Array;\n}\n\nexport class FragmentGateway implements Gateway {\n readonly sthis: SuperThis;\n readonly logger: Logger;\n readonly fidLength = 4;\n\n readonly innerGW: Gateway;\n headerSize = 32;\n\n constructor(sthis: SuperThis, innerGW: Gateway) {\n this.sthis = ensureSuperLog(sthis, \"FragmentGateway\");\n this.logger = this.sthis.logger;\n this.innerGW = innerGW;\n }\n\n slicer(url: URI, body: Uint8Array): Promise<VoidResult>[] {\n const fragSize = getFragSize(url);\n if (!fragSize) {\n return [this.innerGW.put(url, body)];\n }\n const blocksize = fragSize - this.headerSize;\n if (blocksize <= 0) {\n throw this.logger\n .Error()\n .Uint64(\"fragSize\", fragSize)\n .Uint64(\"headerSize\", this.headerSize)\n .Msg(\"Fragment size is too small\")\n .AsError();\n }\n const ops: Promise<VoidResult>[] = [];\n const fid = this.sthis.nextId(this.fidLength);\n const fragUrl = url\n .build()\n .setParam(\"fid\", fid.str)\n .setParam(\"len\", body.length.toString())\n .setParam(\"headerSize\", this.headerSize.toString());\n for (let ofs = 0; ofs < body.length; ofs += blocksize) {\n const block = encode({\n fid: fid.bin,\n ofs,\n len: body.length,\n data: body.slice(ofs, ofs + blocksize),\n } as Fragment);\n if (block.length > fragSize) {\n throw this.logger.Error().Uint64(\"block\", block.length).Uint64(\"fragSize\", fragSize).Msg(\"Block size to big\").AsError();\n }\n ops.push(this.innerGW.put(fragUrl.setParam(\"ofs\", ofs.toString()).URI(), block));\n }\n return ops;\n }\n\n buildUrl(baseUrl: URI, key: string): Promise<Result<URI>> {\n return this.innerGW.buildUrl(baseUrl, key);\n }\n\n async destroy(iurl: URI): Promise<Result<void>> {\n return this.innerGW.destroy(iurl);\n }\n\n async start(url: URI): Promise<Result<URI>> {\n this.headerSize =\n encode({\n fid: this.sthis.nextId(this.fidLength).bin,\n ofs: 1024 * 1024, // 32bit\n len: 16 * 1024 * 1024, // 32bit\n data: new Uint8Array(1024),\n }).length - 1024;\n return this.innerGW.start(url);\n }\n\n async close(url: URI): Promise<VoidResult> {\n return this.innerGW.close(url);\n }\n\n async put(url: URI, body: Uint8Array): Promise<VoidResult> {\n await Promise.all(this.slicer(url, body));\n return Result.Ok(undefined);\n }\n\n async get(url: URI): Promise<GetResult> {\n const rfrags = await getFrags(url, this.innerGW, this.headerSize, this.logger);\n let buffer: Uint8Array | undefined = undefined;\n for (const rfrag of rfrags) {\n if (rfrag.isErr()) {\n return Result.Err(rfrag.Err());\n }\n const frag = rfrag.Ok();\n buffer = buffer || new Uint8Array(frag.len);\n buffer.set(frag.data, frag.ofs);\n }\n return Result.Ok(buffer || new Uint8Array(0));\n }\n\n async subscribe(url: URI, callback: (msg: Uint8Array) => void): Promise<UnsubscribeResult> {\n if (this.innerGW.subscribe) {\n return this.innerGW.subscribe(url, callback);\n } else {\n return Result.Err(this.logger.Error().Url(url).Msg(\"subscribe not supported\").AsError());\n }\n }\n\n async delete(url: URI): Promise<VoidResult> {\n const rfrags = await getFrags(url, this.innerGW, this.headerSize, this.logger);\n for (const rfrag of rfrags) {\n if (rfrag.isErr()) {\n return Result.Err(rfrag.Err());\n }\n const frag = rfrag.Ok();\n const fidStr = base58btc.encode(frag.fid);\n const fragUrl = url\n .build()\n .setParam(\"fid\", fidStr)\n .setParam(\"len\", frag.len.toString())\n .setParam(\"headerSize\", this.headerSize.toString())\n .URI();\n await this.innerGW.delete(fragUrl);\n }\n return Result.Ok(undefined);\n }\n}\n","import { format, parse } from \"@ipld/dag-json\";\nimport { EventBlock, decodeEventBlock } from \"@web3-storage/pail/clock\";\nimport { EventView } from \"@web3-storage/pail/clock/api\";\nimport type { DbMeta, CarClockHead, DbMetaEventBlock, CarClockLink } from \"./types.js\";\nimport { SuperThis, CRDTEntry } from \"../types.js\";\nimport { CID, Link } from \"multiformats\";\nimport { base64pad } from \"multiformats/bases/base64\";\nimport { Result, URI } from \"@adviser/cement\";\nimport { getKeyBag } from \"../runtime/key-bag.js\";\n\nexport async function decodeGatewayMetaBytesToDbMeta(sthis: SuperThis, byteHeads: Uint8Array) {\n const crdtEntries = JSON.parse(sthis.txt.decode(byteHeads)) as CRDTEntry[];\n if (!crdtEntries.length) {\n sthis.logger.Debug().Str(\"byteHeads\", new TextDecoder().decode(byteHeads)).Msg(\"No CRDT entries found\");\n return [];\n }\n if (!crdtEntries.map) {\n sthis.logger.Debug().Str(\"crdtEntries\", JSON.stringify(crdtEntries)).Msg(\"No data in CRDT entries\");\n return [];\n }\n return Promise.all(\n crdtEntries.map(async (crdtEntry) => {\n const eventBlock = await decodeEventBlock<{ dbMeta: Uint8Array }>(base64pad.decode(crdtEntry.data));\n const dbMeta = parse<DbMeta>(sthis.txt.decode(eventBlock.value.data.dbMeta));\n return {\n eventCid: eventBlock.cid as CarClockLink,\n parents: crdtEntry.parents,\n dbMeta: dbMeta,\n };\n }),\n );\n}\n\nexport async function setCryptoKeyFromGatewayMetaPayload(\n uri: URI,\n sthis: SuperThis,\n data: Uint8Array,\n): Promise<Result<DbMeta | undefined>> {\n try {\n sthis.logger.Debug().Str(\"uri\", uri.toString()).Msg(\"Setting crypto key from gateway meta payload\");\n const keyInfo = await decodeGatewayMetaBytesToDbMeta(sthis, data);\n if (keyInfo.length) {\n const dbMeta = keyInfo[0].dbMeta;\n if (dbMeta.key) {\n const kb = await getKeyBag(sthis);\n const keyName = getStoreKeyName(uri);\n const res = await kb.setNamedKey(keyName, dbMeta.key);\n if (res.isErr()) {\n sthis.logger.Debug().Str(\"keyName\", keyName).Str(\"dbMeta.key\", dbMeta.key).Msg(\"Failed to set named key\");\n throw res.Err();\n }\n }\n sthis.logger.Debug().Str(\"dbMeta.key\", dbMeta.key).Str(\"uri\", uri.toString()).Msg(\"Set crypto key from gateway meta payload\");\n return Result.Ok(dbMeta);\n }\n sthis.logger.Debug().Str(\"data\", new TextDecoder().decode(data)).Msg(\"No crypto in gateway meta payload\");\n return Result.Ok(undefined);\n } catch (error) {\n sthis.logger.Debug().Err(error).Msg(\"Failed to set crypto key from gateway meta payload\");\n return Result.Err(error as Error);\n }\n}\n\nexport async function addCryptoKeyToGatewayMetaPayload(uri: URI, sthis: SuperThis, body: Uint8Array): Promise<Result<Uint8Array>> {\n try {\n sthis.logger.Debug().Str(\"uri\", uri.toString()).Msg(\"Adding crypto key to gateway meta payload\");\n const keyName = getStoreKeyName(uri);\n const kb = await getKeyBag(sthis);\n const res = await kb.getNamedExtractableKey(keyName, true);\n if (res.isErr()) {\n sthis.logger.Error().Str(\"keyName\", keyName).Msg(\"Failed to get named extractable key\");\n throw res.Err();\n }\n const keyData = await res.Ok().extract();\n const dbMetas = await decodeGatewayMetaBytesToDbMeta(sthis, body);\n const { dbMeta, parents } = dbMetas[0]; // as { dbMeta: DbMeta };\n const parentLinks = parents.map((p) => CID.parse(p) as CarClockLink);\n dbMeta.key = keyData.keyStr;\n const events = await Promise.all([dbMeta].map((dbMeta) => createDbMetaEventBlock(sthis, dbMeta, parentLinks)));\n const encoded = await encodeEventsWithParents(sthis, events, parentLinks);\n sthis.logger.Debug().Str(\"uri\", uri.toString()).Msg(\"Added crypto key to gateway meta payload\");\n return Result.Ok(encoded);\n } catch (error) {\n sthis.logger.Error().Err(error).Msg(\"Failed to add crypto key to gateway meta payload\");\n return Result.Err(error as Error);\n }\n}\n\nexport function getStoreKeyName(url: URI): string {\n const storeKeyName = [url.getParam(\"localName\") || url.getParam(\"name\")];\n const idx = url.getParam(\"index\");\n if (idx) {\n storeKeyName.push(idx);\n }\n storeKeyName.push(\"data\");\n return `@${storeKeyName.join(\":\")}@`;\n}\n\nexport async function createDbMetaEventBlock(sthis: SuperThis, dbMeta: DbMeta, parents: CarClockHead): Promise<DbMetaEventBlock> {\n const event = await EventBlock.create(\n {\n dbMeta: sthis.txt.encode(format(dbMeta)),\n },\n parents as unknown as Link<EventView<{ dbMeta: Uint8Array }>, number, number, 1>[],\n );\n return event as EventBlock<{ dbMeta: Uint8Array }>;\n}\n\nexport async function encodeEventsWithParents(\n sthis: SuperThis,\n events: EventBlock<{ dbMeta: Uint8Array }>[],\n parents: CarClockHead,\n): Promise<Uint8Array> {\n const crdtEntries = events.map((event) => {\n const base64String = base64pad.encode(event.bytes);\n return {\n cid: event.cid.toString(),\n data: base64String,\n parents: parents.map((p) => p.toString()),\n };\n });\n return sthis.txt.encode(JSON.stringify(crdtEntries));\n}\n","import { URI } from \"@adviser/cement\";\nimport { MetaStoreImpl, DataStoreImpl, StoreOpts } from \"./store.js\";\nimport { SuperThis } from \"../types.js\";\n\n// export type LoadHandler = (dbMetas: DbMeta[]) => Promise<void>;\n// export function validateDataParams(params: DownloadDataFnParams | UploadDataFnParams, logger: Logger) {\n// const { type, name, car } = params;\n// if (!name) throw logger.Error().Msg(\"name is required\").AsError();\n// if (!car) {\n// throw logger.Error().Msg(\"car is required\").AsError();\n// }\n// if (type !== \"file\" && type !== \"data\") {\n// throw logger.Error().Msg(\"type must be file or data\").AsError();\n// }\n// }\n\n// export function validateMetaParams(params: DownloadMetaFnParams | UploadMetaFnParams, logger: Logger) {\n// const { name, branch } = params;\n// if (!name) throw logger.Error().Msg(\"name is required\").AsError();\n// if (!branch) {\n// throw logger.Error().Msg(\"branch is required\").AsError();\n// }\n// }\n\n// export class RemoteDataStore extends DataStoreImpl {\n// // just for explaining the concept\n// }\n\n// export class RemoteMetaStore extends MetaStoreImpl {\n// // just for explaining the concept\n// }\n\nexport async function RemoteDataStore(sthis: SuperThis, name: string, url: URI, opts: StoreOpts) {\n const ds = new DataStoreImpl(sthis, name, url, opts);\n await ds.start();\n return ds;\n}\nexport async function RemoteMetaStore(sthis: SuperThis, name: string, url: URI, opts: StoreOpts) {\n const ms = new MetaStoreImpl(sthis, name, url, opts /* , true*/);\n await ms.start();\n return ms;\n}\n\n// export class RemoteWALStore extends WALStoreImpl {\n// // basicly do nothing write the WAL into memory\n// constructor(loader: Loadable) {\n\n// //import { FileWALGateway } from \"../runtime/gateways/file/gateway.js\";\n// // super(loader, new URL(\"file:///dummy?fs=mem\"), loader.logger, new FileWALGateway(loader.logger));\n// }\n\n// }\n","import { Logger, URI } from \"@adviser/cement\";\n\nimport { throwFalsy } from \"../types.js\";\nimport { TaskManager } from \"./task-manager.js\";\nimport type { BlockstoreRuntime, Connection, Loadable } from \"./types.js\";\nimport { type Loader } from \"./loader.js\";\nimport { RemoteDataStore, RemoteMetaStore } from \"./store-remote.js\";\nimport { getGatewayFromURL } from \"./store-factory.js\";\nimport { getKeyBag } from \"../runtime/key-bag.js\";\n\nexport interface Connectable {\n readonly blockstore: {\n readonly loader?: Loader;\n readonly ebOpts: BlockstoreRuntime;\n };\n readonly name?: string;\n // readonly sthis: SuperThis;\n}\n\nexport abstract class ConnectionBase implements Connection {\n // readonly ready: Promise<unknown>;\n // todo move to LRU blockstore https://github.com/web3-storage/w3clock/blob/main/src/worker/block.js\n // readonly eventBlocks = new MemoryBlockstore();\n loader?: Loadable;\n taskManager?: TaskManager;\n loaded: Promise<void> = Promise.resolve();\n\n readonly url: URI;\n\n // abstract metaUpload(bytes: Uint8Array, params: UploadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n // abstract dataUpload(bytes: Uint8Array, params: UploadDataFnParams, opts?: { public?: boolean }): Promise<void>;\n // abstract metaDownload(params: DownloadMetaFnParams): Promise<Uint8Array[] | Falsy>;\n // abstract dataDownload(params: DownloadDataFnParams): Promise<Uint8Array | Falsy>;\n\n readonly logger: Logger;\n constructor(url: URI, logger: Logger) {\n this.logger = logger;\n this.url = url;\n }\n\n async refresh() {\n await throwFalsy(throwFalsy(this.loader).remoteMetaStore).load();\n await (await throwFalsy(this.loader).WALStore()).process();\n }\n\n async connect_X({ loader }: { readonly loader?: Loadable }) {\n if (!loader) throw this.logger.Error().Msg(\"loader is required\").AsError();\n await this.connectMeta_X({ loader });\n await this.connectStorage_X({ loader });\n }\n\n async connectMeta_X({ loader }: { loader?: Loadable }) {\n if (!loader) throw this.logger.Error().Msg(\"connectMeta_X: loader is required\").AsError();\n this.loader = loader;\n await this.onConnect();\n const metaUrl = this.url.build().defParam(\"store\", \"meta\").URI();\n const gateway = await getGatewayFromURL(metaUrl, this.loader.sthis);\n if (!gateway) throw this.logger.Error().Url(metaUrl).Msg(\"connectMeta_X: gateway is required\").AsError();\n const dbName = metaUrl.getParam(\"name\");\n if (!dbName) throw this.logger.Error().Url(metaUrl).Msg(\"connectMeta_X: name is required\").AsError();\n const remote = await RemoteMetaStore(loader.sthis, dbName, metaUrl, {\n gateway: gateway.gateway,\n keybag: () => getKeyBag(loader.sthis, loader.ebOpts.keyBag),\n loader,\n });\n this.loader.remoteMetaStore = remote;\n this.loaded = this.loader.ready().then(async () => {\n remote.load().then(async () => {\n (await throwFalsy(this.loader).WALStore()).process();\n });\n });\n }\n\n abstract onConnect(): Promise<void>;\n\n async connectStorage_X({ loader }: { loader?: Loadable }) {\n if (!loader) throw this.logger.Error().Msg(\"connectStorage_X: loader is required\").AsError();\n this.loader = loader;\n // const dataUrl = this.url.build().defParam(\"store\", \"data\").defParam(\"fragSize\", \"128000\").URI();\n const dataUrl = this.url.build().defParam(\"store\", \"data\").URI();\n const gateway = await getGatewayFromURL(dataUrl, this.loader.sthis);\n if (!gateway) throw this.logger.Error().Url(dataUrl).Msg(\"connectStorage_X: gateway is required\").AsError();\n const name = dataUrl.getParam(\"name\");\n if (!name) throw this.logger.Error().Url(dataUrl).Msg(\"connectStorage_X: name is required\").AsError;\n loader.remoteCarStore = await RemoteDataStore(loader.sthis, name, this.url, {\n gateway: gateway.gateway,\n keybag: () => getKeyBag(loader.sthis, this.loader?.ebOpts.keyBag),\n });\n // @jchris why we have a differention between remoteCarStore and remoteFileStore? -- file store is for on-demand attachment loading\n // for now we don't have any difference but in superthis car store and\n // file store could have different urls/gateways\n loader.remoteFileStore = loader.remoteCarStore;\n }\n\n // move this stuff to connect\n // async getDashboardURL(compact = true) {\n // const baseUrl = 'https://dashboard.fireproof.storage/'\n // if (!this.loader?.remoteCarStore) return new URL('/howto', baseUrl)\n // // if (compact) {\n // // await this.compact()\n // // }\n // const currents = await this.loader?.metaStore?.load()\n // if (!currents) throw new Error(\"Can't sync empty database: save data first\")\n // if (currents.length > 1)\n // throw new Error(\"Can't sync database with split heads: make an update first\")\n // const current = currents[0]\n // const params = {\n // car: current.car.toString()\n // }\n // if (current.key) {\n // // @ts-ignore\n // params.key = current.key.toString()\n // }\n // // @ts-ignore\n // if (this.name) {\n // // @ts-ignore\n // params.name = this.name\n // }\n // const url = new URL('/import#' + new URLSearchParams(params).toString(), baseUrl)\n // console.log('Import to dashboard: ' + url.toString())\n // return url\n // }\n\n // openDashboard() {\n // void this.getDashboardURL().then(url => {\n // if (url) window.open(url.toString(), '_blank')\n // })\n // }\n}\n","import type { Block, Link } from \"multiformats\";\nimport { create } from \"./runtime/wait-pr-multiformats/block.js\";\nimport { sha256 as hasher } from \"multiformats/hashes/sha2\";\nimport * as codec from \"@ipld/dag-cbor\";\n\n// @ts-expect-error \"charwise\" has no types\nimport charwise from \"charwise\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport * as DbIndex from \"prolly-trees/db-index\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { bf, simpleCompare } from \"prolly-trees/utils\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { nocache as cache } from \"prolly-trees/cache\";\n// @ts-expect-error \"prolly-trees\" has no types\nimport { ProllyNode as BaseNode } from \"prolly-trees/db-index\";\n\nimport {\n DocUpdate,\n MapFn,\n DocFragment,\n IndexUpdate,\n QueryOpts,\n IndexRow,\n DocWithId,\n IndexKeyType,\n IndexKey,\n DocTypes,\n DocObject,\n IndexUpdateString,\n} from \"./types.js\";\nimport { CarTransaction, BlockFetcher, AnyLink, AnyBlock } from \"./blockstore/index.js\";\nimport { CRDT } from \"./crdt.js\";\n\nexport class IndexTree<K extends IndexKeyType, R extends DocFragment> {\n cid?: AnyLink;\n root?: ProllyNode<K, R>;\n}\n\ntype CompareRef = string | number;\nexport type CompareKey = [string | number, CompareRef];\n\nfunction refCompare(aRef: CompareRef, bRef: CompareRef) {\n if (Number.isNaN(aRef)) return -1;\n if (Number.isNaN(bRef)) throw new Error(\"ref may not be Infinity or NaN\");\n if (aRef === Infinity) return 1;\n // if (!Number.isFinite(bRef)) throw new Error('ref may not be Infinity or NaN')\n\n return simpleCompare(aRef, bRef) as number;\n}\n\nfunction compare(a: CompareKey, b: CompareKey) {\n const [aKey, aRef] = a;\n const [bKey, bRef] = b;\n\n const comp: number = simpleCompare(aKey, bKey);\n if (comp !== 0) return comp;\n return refCompare(aRef, bRef);\n}\n\nexport const byKeyOpts: StaticProllyOptions<CompareKey> = { cache, chunker: bf(30), codec, hasher, compare };\n\nexport const byIdOpts: StaticProllyOptions<unknown> = { cache, chunker: bf(30), codec, hasher, compare: simpleCompare };\n\nexport interface IndexDoc<K extends IndexKeyType> {\n readonly key: IndexKey<K>;\n readonly value: DocFragment;\n}\n\nexport interface IndexDocString {\n readonly key: string;\n readonly value: DocFragment;\n}\n\nexport function indexEntriesForChanges<T extends DocTypes, K extends IndexKeyType>(\n changes: DocUpdate<T>[],\n mapFn: MapFn<T>,\n): IndexDoc<K>[] {\n const indexEntries: IndexDoc<K>[] = [];\n changes.forEach(({ id: key, value, del }) => {\n if (del || !value) return;\n let mapCalled = false;\n const mapReturn = mapFn({ ...(value as DocWithId<T>), _id: key }, (k: IndexKeyType, v?: DocFragment) => {\n mapCalled = true;\n if (typeof k === \"undefined\") return;\n indexEntries.push({\n key: [charwise.encode(k) as K, key],\n value: v || null,\n });\n });\n if (!mapCalled && mapReturn) {\n indexEntries.push({\n key: [charwise.encode(mapReturn) as K, key],\n value: null,\n });\n }\n });\n return indexEntries;\n}\n\nfunction makeProllyGetBlock(blocks: BlockFetcher): (address: AnyLink) => Promise<AnyBlock> {\n return async (address: AnyLink) => {\n const block = await blocks.get(address);\n if (!block) throw new Error(`Missing block ${address.toString()}`);\n const { cid, bytes } = block;\n return create({ cid, bytes, hasher, codec }) as Promise<AnyBlock>;\n };\n}\n\nexport async function bulkIndex<K extends IndexKeyType, T extends DocFragment, CT>(\n tblocks: CarTransaction,\n inIndex: IndexTree<K, T>,\n indexEntries: (IndexUpdate<K> | IndexUpdateString)[],\n opts: StaticProllyOptions<CT>,\n): Promise<IndexTree<K, T>> {\n if (!indexEntries.length) return inIndex;\n if (!inIndex.root) {\n if (!inIndex.cid) {\n let returnRootBlock: Block | undefined = undefined;\n let returnNode: ProllyNode<K, T> | undefined = undefined;\n\n for await (const node of (await DbIndex.create({\n get: makeProllyGetBlock(tblocks),\n list: indexEntries,\n ...opts,\n })) as ProllyNode<K, T>[]) {\n const block = await node.block;\n await tblocks.put(block.cid, block.bytes);\n returnRootBlock = block;\n returnNode = node;\n }\n if (!returnNode || !returnRootBlock) throw new Error(\"failed to create index\");\n return { root: returnNode, cid: returnRootBlock.cid };\n } else {\n inIndex.root = (await DbIndex.load({ cid: inIndex.cid, get: makeProllyGetBlock(tblocks), ...opts })) as ProllyNode<K, T>;\n }\n }\n const { root, blocks: newBlocks } = await inIndex.root.bulk(indexEntries);\n if (root) {\n for await (const block of newBlocks) {\n await tblocks.put(block.cid, block.bytes);\n }\n return { root, cid: (await root.block).cid };\n } else {\n return { root: undefined, cid: undefined };\n }\n}\n\nexport async function loadIndex<K extends IndexKeyType, T extends DocFragment, CT>(\n tblocks: BlockFetcher,\n cid: AnyLink,\n opts: StaticProllyOptions<CT>,\n): Promise<ProllyNode<K, T>> {\n return (await DbIndex.load({ cid, get: makeProllyGetBlock(tblocks), ...opts })) as ProllyNode<K, T>;\n}\n\nexport async function applyQuery<K extends IndexKeyType, T extends DocObject, R extends DocFragment>(\n crdt: CRDT<T>,\n resp: { result: ProllyIndexRow<K, R>[] },\n query: QueryOpts<K>,\n): Promise<{\n rows: IndexRow<K, T, R>[];\n}> {\n if (query.descending) {\n resp.result = resp.result.reverse();\n }\n if (query.limit) {\n resp.result = resp.result.slice(0, query.limit);\n }\n if (query.includeDocs) {\n resp.result = await Promise.all(\n resp.result.map(async (row) => {\n const val = await crdt.get(row.id);\n const doc = val ? ({ ...val.doc, _id: row.id } as DocWithId<T>) : undefined;\n return { ...row, doc };\n }),\n );\n }\n return {\n rows: resp.result.map(({ key, ...row }) => {\n return {\n key: charwise.decode(key),\n ...row,\n };\n }),\n };\n}\n\nexport function encodeRange(range: [IndexKeyType, IndexKeyType]): [string, string] {\n return [charwise.encode(range[0]), charwise.encode(range[1])];\n}\n\nexport function encodeKey(key: DocFragment): string {\n return charwise.encode(key) as string;\n}\n\nexport interface ProllyIndexRow<K extends IndexKeyType, T extends DocFragment> {\n readonly id: string;\n readonly key: IndexKey<K>;\n readonly value: T;\n}\n\n// ProllyNode type based on the ProllyNode from 'prolly-trees/base'\ninterface ProllyNode<K extends IndexKeyType, T extends DocFragment> extends BaseNode {\n getAllEntries(): PromiseLike<{ [x: string]: unknown; result: ProllyIndexRow<K, T>[] }>;\n getMany<KI extends IndexKeyType>(removeIds: KI[]): Promise<{ /* [x: K]: unknown; */ result: IndexKey<K>[] }>;\n range(a: string, b: string): Promise<{ result: ProllyIndexRow<K, T>[] }>;\n get(key: string): Promise<{ result: ProllyIndexRow<K, T>[] }>;\n bulk(bulk: (IndexUpdate<K> | IndexUpdateString)[]): PromiseLike<{\n readonly root?: ProllyNode<K, T>;\n readonly blocks: Block[];\n }>;\n readonly address: Promise<Link>;\n readonly distance: number;\n compare: (a: unknown, b: unknown) => number;\n readonly cache: unknown;\n readonly block: Promise<Block>;\n}\n\ninterface StaticProllyOptions<T> {\n readonly cache: unknown;\n chunker: (entry: T, distance: number) => boolean;\n readonly codec: unknown;\n readonly hasher: unknown;\n compare: (a: T, b: T) => number;\n}\n","import {\n type ClockHead,\n type DocUpdate,\n type MapFn,\n type IndexUpdate,\n type QueryOpts,\n type IdxMeta,\n type DocFragment,\n type IdxMetaMap,\n type IndexKeyType,\n type IndexRows,\n type DocTypes,\n type IndexUpdateString,\n throwFalsy,\n IndexTransactionMeta,\n SuperThis,\n} from \"./types.js\";\nimport { BaseBlockstore } from \"./blockstore/index.js\";\n\nimport {\n bulkIndex,\n indexEntriesForChanges,\n byIdOpts,\n byKeyOpts,\n IndexTree,\n applyQuery,\n encodeRange,\n encodeKey,\n loadIndex,\n IndexDocString,\n CompareKey,\n} from \"./indexer-helpers.js\";\nimport { CRDT } from \"./crdt.js\";\nimport { ensureLogger } from \"./utils.js\";\nimport { Logger } from \"@adviser/cement\";\n\nexport function index<K extends IndexKeyType = string, T extends DocTypes = NonNullable<unknown>, R extends DocFragment = T>(\n sthis: SuperThis,\n { _crdt }: { _crdt: CRDT<T> | CRDT<NonNullable<unknown>> },\n name: string,\n mapFn?: MapFn<T>,\n meta?: IdxMeta,\n): Index<K, T, R> {\n if (mapFn && meta) throw _crdt.logger.Error().Msg(\"cannot provide both mapFn and meta\").AsError();\n if (mapFn && mapFn.constructor.name !== \"Function\") throw _crdt.logger.Error().Msg(\"mapFn must be a function\").AsError();\n if (_crdt.indexers.has(name)) {\n const idx = _crdt.indexers.get(name) as unknown as Index<K, T>;\n idx.applyMapFn(name, mapFn, meta);\n } else {\n const idx = new Index<K, T>(sthis, _crdt, name, mapFn, meta);\n _crdt.indexers.set(name, idx as unknown as Index<K, NonNullable<unknown>, NonNullable<unknown>>);\n }\n return _crdt.indexers.get(name) as unknown as Index<K, T, R>;\n}\n\n// interface ByIdIndexIten<K extends IndexKeyType> {\n// readonly key: K;\n// readonly value: [K, K];\n// }\n\nexport class Index<K extends IndexKeyType, T extends DocTypes, R extends DocFragment = T> {\n readonly blockstore: BaseBlockstore;\n readonly crdt: CRDT<T>;\n name: string;\n mapFn?: MapFn<T>;\n mapFnString = \"\";\n byKey: IndexTree<K, R> = new IndexTree<K, R>();\n byId: IndexTree<K, R> = new IndexTree<K, R>();\n indexHead?: ClockHead;\n includeDocsDefault = false;\n initError?: Error;\n\n ready(): Promise<void> {\n return Promise.all([this.blockstore.ready(), this.crdt.ready()]).then(() => {\n /* noop */\n });\n }\n\n close(): Promise<void> {\n return Promise.all([this.blockstore.close(), this.crdt.close()]).then(() => {\n /* noop */\n });\n }\n destroy(): Promise<void> {\n return Promise.all([this.blockstore.destroy(), this.crdt.destroy()]).then(() => {\n /* noop */\n });\n }\n\n readonly logger: Logger;\n\n constructor(sthis: SuperThis, crdt: CRDT<T> | CRDT<NonNullable<unknown>>, name: string, mapFn?: MapFn<T>, meta?: IdxMeta) {\n this.logger = ensureLogger(sthis, \"Index\");\n this.blockstore = crdt.indexBlockstore;\n this.crdt = crdt as CRDT<T>;\n this.applyMapFn(name, mapFn, meta);\n this.name = name;\n if (!(this.mapFnString || this.initError)) throw this.logger.Error().Msg(\"missing mapFnString\").AsError();\n // this.ready = this.blockstore.ready.then(() => {\n // return;\n // });\n // .then((header: IdxCarHeader) => {\n // // @ts-ignore\n // if (header.head) throw new Error('cannot have head in idx header')\n // if (header.indexes === undefined) throw new Error('missing indexes in idx header')\n // // for (const [name, idx] of Object.entries(header.indexes)) {\n // // index({ _crdt: crdt }, name, undefined, idx as IdxMeta)\n // // }\n // })\n }\n\n applyMapFn(name: string, mapFn?: MapFn<T>, meta?: IdxMeta) {\n if (mapFn && meta) throw this.logger.Error().Msg(\"cannot provide both mapFn and meta\").AsError();\n if (this.name && this.name !== name) throw this.logger.Error().Msg(\"cannot change name\").AsError();\n this.name = name;\n try {\n if (meta) {\n // hydrating from header\n if (this.indexHead && this.indexHead.map((c) => c.toString()).join() !== meta.head.map((c) => c.toString()).join()) {\n throw this.logger.Error().Msg(\"cannot apply different head meta\").AsError();\n }\n\n if (this.mapFnString) {\n // we already initialized from application code\n if (this.mapFnString !== meta.map) {\n this.logger\n .Warn()\n .Msg(`cannot apply different mapFn meta: old mapFnString ${this.mapFnString} new mapFnString ${meta.map}`);\n // throw new Error('cannot apply different mapFn meta')\n } else {\n this.byId.cid = meta.byId;\n this.byKey.cid = meta.byKey;\n this.indexHead = meta.head;\n }\n } else {\n // we are first\n this.mapFnString = meta.map;\n this.byId.cid = meta.byId;\n this.byKey.cid = meta.byKey;\n this.indexHead = meta.head;\n }\n } else {\n if (this.mapFn) {\n // we already initialized from application code\n if (mapFn) {\n if (this.mapFn.toString() !== mapFn.toString()) {\n throw this.logger.Error().Msg(\"cannot apply different mapFn app2\").AsError();\n }\n }\n } else {\n // application code is creating an index\n if (!mapFn) {\n mapFn = ((doc) => (doc as unknown as Record<string, unknown>)[name] ?? undefined) as MapFn<T>;\n }\n if (this.mapFnString) {\n // we already loaded from a header\n if (this.mapFnString !== mapFn.toString()) {\n throw this.logger\n .Error()\n .Str(\"mapFnString\", this.mapFnString)\n .Str(\"mapFn\", mapFn.toString())\n .Msg(\"cannot apply different mapFn app\")\n .AsError();\n }\n } else {\n // we are first\n this.mapFnString = mapFn.toString();\n }\n this.mapFn = mapFn;\n }\n }\n const matches = /=>\\s*(.*)/.test(this.mapFnString);\n this.includeDocsDefault = matches;\n } catch (e) {\n this.initError = e as Error;\n }\n }\n\n async query(opts: QueryOpts<K> = {}): Promise<IndexRows<K, T, R>> {\n await this.ready();\n // this._resetIndex();\n await this._updateIndex();\n await this._hydrateIndex();\n if (!this.byKey.root) {\n return await applyQuery<K, T, R>(this.crdt, { result: [] }, opts);\n }\n if (this.includeDocsDefault && opts.includeDocs === undefined) opts.includeDocs = true;\n if (opts.range) {\n const eRange = encodeRange(opts.range);\n return await applyQuery<K, T, R>(this.crdt, await throwFalsy(this.byKey.root).range(eRange[0], eRange[1]), opts);\n }\n if (opts.key) {\n const encodedKey = encodeKey(opts.key);\n return await applyQuery<K, T, R>(this.crdt, await throwFalsy(this.byKey.root).get(encodedKey), opts);\n }\n if (Array.isArray(opts.keys)) {\n const results = await Promise.all(\n opts.keys.map(async (key: DocFragment) => {\n const encodedKey = encodeKey(key);\n return (await applyQuery<K, T, R>(this.crdt, await throwFalsy(this.byKey.root).get(encodedKey), opts)).rows;\n }),\n );\n return { rows: results.flat() };\n }\n if (opts.prefix) {\n if (!Array.isArray(opts.prefix)) opts.prefix = [opts.prefix];\n // prefix should be always an array\n const start = [...opts.prefix, NaN];\n const end = [...opts.prefix, Infinity];\n const encodedR = encodeRange([start, end]);\n return await applyQuery<K, T, R>(this.crdt, await this.byKey.root.range(...encodedR), opts);\n }\n const all = await this.byKey.root.getAllEntries(); // funky return type\n return await applyQuery<K, T, R>(\n this.crdt,\n {\n // @ts-expect-error getAllEntries returns a different type than range\n result: all.result.map(({ key: [k, id], value }) => ({\n key: k,\n id,\n value,\n })),\n },\n opts,\n );\n }\n\n _resetIndex() {\n this.byId = new IndexTree();\n this.byKey = new IndexTree();\n this.indexHead = undefined;\n }\n\n async _hydrateIndex() {\n if (this.byId.root && this.byKey.root) return;\n if (!this.byId.cid || !this.byKey.cid) return;\n this.byId.root = await loadIndex<K, R, K>(this.blockstore, this.byId.cid, byIdOpts);\n this.byKey.root = await loadIndex<K, R, CompareKey>(this.blockstore, this.byKey.cid, byKeyOpts);\n }\n\n async _updateIndex(): Promise<IndexTransactionMeta> {\n await this.ready();\n if (this.initError) throw this.initError;\n if (!this.mapFn) throw this.logger.Error().Msg(\"No map function defined\").AsError();\n let result: DocUpdate<T>[], head: ClockHead;\n if (!this.indexHead || this.indexHead.length === 0) {\n ({ result, head } = await this.crdt.allDocs());\n } else {\n ({ result, head } = await this.crdt.changes(this.indexHead));\n }\n if (result.length === 0) {\n this.indexHead = head;\n // return { byId: this.byId, byKey: this.byKey } as IndexTransactionMeta;\n }\n let staleKeyIndexEntries: IndexUpdate<K>[] = [];\n let removeIdIndexEntries: IndexUpdateString[] = [];\n if (this.byId.root) {\n const removeIds = result.map(({ id: key }) => key);\n const { result: oldChangeEntries } = await this.byId.root.getMany(removeIds);\n staleKeyIndexEntries = oldChangeEntries.map((key) => ({ key, del: true }));\n removeIdIndexEntries = oldChangeEntries.map((key) => ({ key: key[1], del: true }));\n }\n const indexEntries = indexEntriesForChanges<T, K>(result, this.mapFn); // use a getter to translate from string\n const byIdIndexEntries: IndexDocString[] = indexEntries.map(({ key }) => ({\n key: key[1],\n value: key,\n }));\n const indexerMeta: IdxMetaMap = { indexes: new Map() };\n\n for (const [name, indexer] of this.crdt.indexers) {\n if (indexer.indexHead) {\n indexerMeta.indexes?.set(name, {\n byId: indexer.byId.cid,\n byKey: indexer.byKey.cid,\n head: indexer.indexHead,\n map: indexer.mapFnString,\n name: indexer.name,\n } as IdxMeta);\n }\n }\n if (result.length === 0) {\n return indexerMeta as unknown as IndexTransactionMeta;\n }\n const { meta } = await this.blockstore.transaction<IndexTransactionMeta>(async (tblocks): Promise<IndexTransactionMeta> => {\n this.byId = await bulkIndex<K, R, K>(tblocks, this.byId, removeIdIndexEntries.concat(byIdIndexEntries), byIdOpts);\n this.byKey = await bulkIndex<K, R, CompareKey>(tblocks, this.byKey, staleKeyIndexEntries.concat(indexEntries), byKeyOpts);\n this.indexHead = head;\n if (this.byId.cid && this.byKey.cid) {\n const idxMeta = {\n byId: this.byId.cid,\n byKey: this.byKey.cid,\n head,\n map: this.mapFnString,\n name: this.name,\n } as IdxMeta;\n indexerMeta.indexes?.set(this.name, idxMeta);\n }\n return indexerMeta as unknown as IndexTransactionMeta;\n });\n return meta;\n }\n}\n","import { advance } from \"@web3-storage/pail/clock\";\nimport { root } from \"@web3-storage/pail/crdt\";\nimport { Logger, ResolveOnce } from \"@adviser/cement\";\n\nimport { clockChangesSince } from \"./crdt-helpers.js\";\nimport type { BaseBlockstore, CarTransaction } from \"./blockstore/index.js\";\nimport { type DocUpdate, type ClockHead, type DocTypes, throwFalsy, CRDTMeta } from \"./types.js\";\nimport { applyHeadQueue, ApplyHeadQueue } from \"./apply-head-queue.js\";\nimport { ensureLogger } from \"./utils.js\";\n\nexport class CRDTClock<T extends DocTypes> {\n // todo: track local and remote clocks independently, merge on read\n // that way we can drop the whole remote if we need to\n // should go with making sure the local clock only references locally available blockstore on write\n head: ClockHead = [];\n\n readonly zoomers: Set<() => void> = new Set<() => void>();\n readonly watchers: Set<(updates: DocUpdate<T>[]) => void> = new Set<(updates: DocUpdate<T>[]) => void>();\n readonly emptyWatchers: Set<() => void> = new Set<() => void>();\n\n readonly blockstore: BaseBlockstore;\n\n readonly applyHeadQueue: ApplyHeadQueue<T>;\n\n readonly _ready: ResolveOnce<void> = new ResolveOnce<void>();\n async ready(): Promise<void> {\n return this._ready.once(async () => {\n await this.blockstore.ready();\n });\n }\n\n async close() {\n await this.blockstore.close();\n }\n\n readonly logger: Logger;\n constructor(blockstore: BaseBlockstore) {\n this.blockstore = blockstore;\n this.logger = ensureLogger(blockstore.sthis, \"CRDTClock\");\n this.applyHeadQueue = applyHeadQueue(this.int_applyHead.bind(this), this.logger);\n }\n\n setHead(head: ClockHead) {\n this.head = head;\n }\n\n async applyHead(newHead: ClockHead, prevHead: ClockHead, updates?: DocUpdate<T>[]): Promise<void> {\n for await (const { updates: updatesAcc, all } of this.applyHeadQueue.push({\n newHead,\n prevHead,\n updates,\n })) {\n return this.processUpdates(updatesAcc, all, prevHead);\n }\n }\n\n async processUpdates(updatesAcc: DocUpdate<T>[], all: boolean, prevHead: ClockHead) {\n let internalUpdates = updatesAcc;\n if (this.watchers.size && !all) {\n const changes = await clockChangesSince<T>(throwFalsy(this.blockstore), this.head, prevHead, {}, this.logger);\n internalUpdates = changes.result;\n }\n this.zoomers.forEach((fn) => fn());\n this.notifyWatchers(internalUpdates || []);\n }\n\n notifyWatchers(updates: DocUpdate<T>[]) {\n this.emptyWatchers.forEach((fn) => fn());\n this.watchers.forEach((fn) => fn(updates || []));\n }\n\n onTick(fn: (updates: DocUpdate<T>[]) => void) {\n this.watchers.add(fn);\n }\n\n onTock(fn: () => void) {\n this.emptyWatchers.add(fn);\n }\n\n onZoom(fn: () => void) {\n this.zoomers.add(fn);\n }\n\n async int_applyHead(newHead: ClockHead, prevHead: ClockHead, localUpdates: boolean) {\n // if (!(this.head && prevHead && newHead)) {\n // throw new Error(\"missing head\");\n // }\n const noLoader = !localUpdates;\n\n // console.log(\"int_applyHead\", this.applyHeadQueue.size(), this.head, newHead, prevHead, localUpdates);\n const ogHead = sortClockHead(this.head);\n newHead = sortClockHead(newHead);\n if (compareClockHeads(ogHead, newHead)) {\n return;\n }\n const ogPrev = sortClockHead(prevHead);\n if (compareClockHeads(ogHead, ogPrev)) {\n this.setHead(newHead);\n return;\n }\n\n // const noLoader = this.head.length === 1 && !updates?.length\n if (!this.blockstore) {\n throw this.logger.Error().Msg(\"missing blockstore\").AsError();\n }\n await validateBlocks(this.logger, newHead, this.blockstore);\n const { meta } = await this.blockstore.transaction<CRDTMeta>(\n async (tblocks: CarTransaction) => {\n const advancedHead = await advanceBlocks(this.logger, newHead, tblocks, this.head);\n const result = await root(tblocks, advancedHead);\n for (const { cid, bytes } of [\n ...result.additions,\n // ...result.removals\n ]) {\n tblocks.putSync(cid, bytes);\n }\n return { head: advancedHead };\n },\n { noLoader, add: false },\n );\n this.setHead(meta.head);\n }\n}\n\n// Helper functions\nfunction sortClockHead(clockHead: ClockHead) {\n return clockHead.sort((a, b) => a.toString().localeCompare(b.toString()));\n}\n\nasync function validateBlocks(logger: Logger, newHead: ClockHead, blockstore?: BaseBlockstore) {\n if (!blockstore) throw logger.Error().Msg(\"missing blockstore\");\n newHead.map(async (cid) => {\n const got = await blockstore.get(cid);\n if (!got) {\n throw logger.Error().Str(\"cid\", cid.toString()).Msg(\"int_applyHead missing block\").AsError();\n }\n });\n}\n\nfunction compareClockHeads(head1: ClockHead, head2: ClockHead) {\n return head1.toString() === head2.toString();\n}\n\nasync function advanceBlocks(logger: Logger, newHead: ClockHead, tblocks: CarTransaction, head: ClockHead) {\n for (const cid of newHead) {\n try {\n head = await advance(tblocks, head, cid);\n } catch (e) {\n logger.Debug().Err(e).Msg(\"failed to advance head\");\n // console.log('failed to advance head:', cid.toString(), e)\n continue;\n }\n }\n return head;\n}\n","import { Logger } from \"@adviser/cement\";\nimport { ClockHead, DocTypes, DocUpdate } from \"./types.js\";\n\ntype ApplyHeadWorkerFunction = (newHead: ClockHead, prevHead: ClockHead, localUpdates: boolean) => Promise<void>;\n\ninterface ApplyHeadTask<T extends DocTypes> {\n readonly newHead: ClockHead;\n readonly prevHead: ClockHead;\n readonly updates?: DocUpdate<T>[];\n}\n\nexport interface ApplyHeadQueue<T extends DocTypes> {\n push(task: ApplyHeadTask<T>): AsyncGenerator<\n {\n readonly updates: DocUpdate<T>[];\n readonly all: boolean;\n },\n void,\n unknown\n >;\n size(): number;\n}\n\nexport function applyHeadQueue<T extends DocTypes>(worker: ApplyHeadWorkerFunction, logger: Logger): ApplyHeadQueue<T> {\n const queue: ApplyHeadTask<T>[] = [];\n let isProcessing = false;\n\n async function* process() {\n if (isProcessing || queue.length === 0) return;\n isProcessing = true;\n const allUpdates: DocUpdate<T>[] = [];\n try {\n while (queue.length > 0) {\n queue.sort((a, b) => (b.updates ? 1 : -1));\n const task = queue.shift();\n if (!task) continue;\n\n await worker(task.newHead, task.prevHead, task.updates !== undefined).catch((e) => {\n throw logger.Error().Err(e).Msg(\"int_applyHead worker error\").AsError();\n });\n // console.timeEnd('int_applyHead worker')\n\n if (task.updates) {\n allUpdates.push(...task.updates);\n }\n // Yield the updates if there are no tasks with updates left in the queue or the current task has updates\n if (!queue.some((t) => t.updates) || task.updates) {\n const allTasksHaveUpdates = queue.every((task) => task.updates !== null);\n yield { updates: allUpdates, all: allTasksHaveUpdates };\n allUpdates.length = 0;\n }\n }\n } finally {\n isProcessing = false;\n const generator = process();\n let result = await generator.next();\n while (!result.done) {\n result = await generator.next();\n }\n }\n }\n\n return {\n push(task: ApplyHeadTask<T>): AsyncGenerator<{ updates: DocUpdate<T>[]; all: boolean }, void, unknown> {\n queue.push(task);\n return process();\n },\n size() {\n return queue.length;\n },\n };\n}\n","// export * from \"./sys-container.js\";\nexport * from \"./gateways/file/utils.js\";\n\n// export * as sql from \"./store-sql/index.js\";\nexport * as files from \"./files.js\";\n\nexport * as kb from \"./key-bag.js\";\nexport * as kc from \"./keyed-crypto.js\";\n\nexport * as mf from \"./wait-pr-multiformats/index.js\";\n\nexport { runtimeFn } from \"@adviser/cement\";\n\nexport { FILESTORE_VERSION } from \"./gateways/file/version.js\";\nexport { INDEXDB_VERSION } from \"./gateways/indexdb/version.js\";\n// export { V0_19SQL_VERSION } from \"./store-sql/v0.19/version.js\";\n","export * as block from \"./block.js\";\nexport * as codec from \"./codec-interface.js\";\n","import type { ArrayBufferView, ByteView } from \"multiformats\";\n\n/**\n * IPLD encoder part of the codec.\n */\nexport interface BlockEncoder<Code extends number, T> {\n name: string;\n code: Code;\n encode(data: T): ByteView<T> | PromiseLike<ByteView<T>>;\n}\n\n/**\n * IPLD decoder part of the codec.\n */\nexport interface BlockDecoder<Code extends number, T> {\n code: Code;\n decode(bytes: ByteView<T> | ArrayBufferView<T>): T | PromiseLike<T>;\n}\n\n/**\n * An IPLD codec is a combination of both encoder and decoder.\n */\nexport interface BlockCodec<Code extends number, T> extends BlockEncoder<Code, T>, BlockDecoder<Code, T> {}\n\nexport type { ArrayBufferView, ByteView };\n","export const PACKAGE_VERSION = Object.keys({\n \"0.19.8-dev-series-2\": \"xxxx\",\n})[0] as string;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6FA,SAAS,YAAY;AACnB,QAAM,OAAO,IAAI,IAAI;AAAA;AAAA;AAAA,IAGnB,GAAG,MAAM;AAAA,MACP,OAAO;AAAA;AAAA,QAEH,WAAmB,OAAO,IAAI,eAAe,CAAC,KAAK,CAAC;AAAA,MACxD;AAAA,IACF;AAAA;AAAA,EACF,CAAC;AAED,SAAO;AACT;AAsBO,SAAS,gBAAgB,QAA4C;AAC1E,QAAM,UAAM,0BAAW;AAAA,IACrB,QAAQ,QAAQ,KAAK,UAAU;AAAA,IAC/B,WAAW,QAAQ,KAAK,aAAa,UAAU;AAAA,EACjD,CAAC;AACD,SAAO,IAAI,UAAU;AAAA,IACnB,QAAQ,QAAQ,UAAU;AAAA,IAC1B;AAAA,IACA,QAAQ,QAAQ,cAAU,+BAAgB;AAAA,IAC1C,KAAK,QAAQ,OAAO,CAAC;AAAA,IACrB;AAAA,IACA,KAAK,QAAQ,OAAO;AAAA,EACtB,CAAC;AACH;AAGO,SAAS,eAAe,OAAkB,eAAuB,KAA0C;AAChH,SAAO,MAAM,MAAM;AAAA,IACjB,QAAQ,aAAa,OAAO,eAAe,GAAG;AAAA,EAChD,CAAC;AACH;AAEO,SAAS,aACd,OACA,eACA,KACQ;AAIR,MAAI,SAAS;AACb,UAAI,wBAAS,KAAK,GAAG;AACnB,aAAS;AAAA,EACX,WAAW,aAAS,wBAAS,MAAM,MAAM,GAAG;AAC1C,aAAS,MAAM;AAAA,EACjB;AACA,QAAM,UAAU,OAAO,KAAK,EAAE,OAAO,aAAa;AAClD,QAAM,QAAkB,CAAC;AACzB,MAAI,cAAc;AAClB,MAAI,KAAK;AACP,QAAI,WAAW,KAA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AAS,UAAU,MAAc,MAA6B;AACnE,QAAM,MAAM,KAAK;AAAA,IACf,cAAc;AAAA,MACZ;AAAA,MACA,QAAQ,cAAc,MAAM,OAAO,MAAM;AAAA,IAC3C,CAAC;AAAA,EACH;AACA,MAAI,KAAK,SAAS,UAAU,IAAI,GAAG;AACnC,MAAI,CAAC,IAAI;AACP,SAAK,IAAI,SAAS,MAAM,IAAI;AAC5B,aAAS,UAAU,IAAI,KAAK,EAAE;AAAA,EAChC;AACA,SAAO;AACT;AAEA,SAAS,SAAS,UAAkB;AAClC,QAAM,QAAQ;AACd,MAAI,QAAgC;AACpC,QAAM,UAAU,MAAM,KAAK,SAAS,SAAS,KAAK,GAAG,CAAC,UAAU,MAAM,CAAC,EAAE,KAAK,CAAC;AAC/E,MAAI,QAAQ,WAAW,GAAG;AACxB,YAAQ,0BAA0B,KAAK,QAAQ;AAC/C,QAAI,SAAS,MAAM,CAAC,EAAE,SAAS,QAAQ,GAAG;AACxC,cAAQ;AAAA,IACV;AAAA,EACF;AACA,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT,OAAO;AAEL,WAAO,MAAM,CAAC;AAAA,EAChB;AACF;;;A2B/PA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACAC;;;ACDA;AAAA;AAAA;AAAA;AAAA;;;ACAA;;;AFWA,IAAAC,kBAA0B;AAE1B;AACAC;;;A5BEA;;;A+BhBO,IAAM,kBAAkB,OAAO,KAAK;AAAA,EACzC,uBAAuB;AACzB,CAAC,EAAE,CAAC;","names":["init_utils","import_cement","init_utils","fs","MemFileSystem","NodeFileSystem","init_utils","getFileSystem","import_cement","init_utils","import_cement","init_utils","init_version","gateway_exports","db","import_idb","import_cement","init_gateway","init_version","import_cement","index","import_cement","mfBlock","codec","hasher","binary","import_sha2","import_clock","import_cement","import_dag_json","import_cement","import_cement","hasher","import_block","import_cement","import_cement","import_cement","import_base58","KeyBagProviderFile","KeyBagProviderIndexDB","import_sha2","dagCodec","codec","hasher","import_sha2","cid","pLimit","cid","cache","got","batchSize","hasher","import_base58","import_sha2","hasher","import_cement","import_base58","ofs","raw","import_multiformats","import_cement","dbMeta","pRetry","pMap","FileGateway","FileTestStore","IndexDBGateway","IndexDBTestStore","hasher","import_sha2","codec","import_utils","cache","hasher","charwise","root","import_clock","import_crdt","import_cement","task","name","updates","init_utils","import_cement","init_version"]}