@xyo-network/diviner-payload-indexeddb 3.6.0-rc.6 → 3.6.0-rc.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/Diviner.d.ts +1 -4
- package/dist/browser/Diviner.d.ts.map +1 -1
- package/dist/browser/index.mjs +10 -39
- package/dist/browser/index.mjs.map +1 -1
- package/package.json +18 -18
- package/src/Diviner.ts +24 -66
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import type { DivinerInstance, DivinerModuleEventData } from '@xyo-network/diviner-model';
|
|
2
2
|
import { PayloadDiviner } from '@xyo-network/diviner-payload-abstract';
|
|
3
3
|
import type { PayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model';
|
|
4
|
-
import {
|
|
4
|
+
import type { Payload, Schema } from '@xyo-network/payload-model';
|
|
5
5
|
import type { IndexedDbPayloadDivinerParams } from './Params.ts';
|
|
6
6
|
export declare class IndexedDbPayloadDiviner<TParams extends IndexedDbPayloadDivinerParams = IndexedDbPayloadDivinerParams, TIn extends PayloadDivinerQueryPayload = PayloadDivinerQueryPayload, TOut extends Payload = Payload, TEventData extends DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut> = DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut>> extends PayloadDiviner<TParams, TIn, TOut, TEventData> {
|
|
7
7
|
static readonly configSchemas: Schema[];
|
|
8
8
|
static readonly defaultConfigSchema: Schema;
|
|
9
|
-
private _db;
|
|
10
9
|
/**
|
|
11
10
|
* The database name. If not supplied via config, it defaults
|
|
12
11
|
* to the archivist's name and if archivist's name is not supplied,
|
|
@@ -26,8 +25,6 @@ export declare class IndexedDbPayloadDiviner<TParams extends IndexedDbPayloadDiv
|
|
|
26
25
|
get storeName(): string;
|
|
27
26
|
protected divineHandler(payloads?: TIn[]): Promise<TOut[]>;
|
|
28
27
|
protected startHandler(): Promise<boolean>;
|
|
29
|
-
private getKeyRangeValue;
|
|
30
|
-
private selectBestIndex;
|
|
31
28
|
/**
|
|
32
29
|
* Checks that the desired DB/objectStore exists and is initialized to the correct version
|
|
33
30
|
* @returns The initialized DB or undefined if it does not exist in the desired state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Diviner.d.ts","sourceRoot":"","sources":["../../src/Diviner.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Diviner.d.ts","sourceRoot":"","sources":["../../src/Diviner.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAA;AACzF,OAAO,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAA;AACtE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAA;AAEpF,OAAO,KAAK,EACV,OAAO,EAAE,MAAM,EAChB,MAAM,4BAA4B,CAAA;AAKnC,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAA;AAoBhE,qBAAa,uBAAuB,CAClC,OAAO,SAAS,6BAA6B,GAAG,6BAA6B,EAC7E,GAAG,SAAS,0BAA0B,GAAG,0BAA0B,EACnE,IAAI,SAAS,OAAO,GAAG,OAAO,EAC9B,UAAU,SAAS,sBAAsB,CAAC,eAAe,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,sBAAsB,CAChH,eAAe,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,EACnC,GAAG,EACH,IAAI,CACL,CACD,SAAQ,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,CAAC;IACtD,gBAAyB,aAAa,EAAE,MAAM,EAAE,CAAgE;IAChH,gBAAyB,mBAAmB,EAAE,MAAM,CAAsC;IAE1F;;;;;;OAMG;IACH,IAAI,MAAM,WAET;IAED;;OAEG;IACH,IAAI,SAAS,WAEZ;IAED;;;OAGG;IACH,IAAI,SAAS,WAEZ;cAEwB,aAAa,CAAC,QAAQ,CAAC,EAAE,GAAG,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;cAqEhD,YAAY;IAKrC;;;OAGG;YACW,mBAAmB;IAwBjC;;;;OAIG;YACW,QAAQ;CAcvB"}
|
package/dist/browser/index.mjs
CHANGED
|
@@ -14,10 +14,8 @@ import { assertEx } from "@xylabs/assert";
|
|
|
14
14
|
import { exists } from "@xylabs/exists";
|
|
15
15
|
import { removeFields } from "@xylabs/object";
|
|
16
16
|
import { IndexedDbArchivist } from "@xyo-network/archivist-indexeddb";
|
|
17
|
-
import { IndexSeparator } from "@xyo-network/archivist-model";
|
|
18
17
|
import { PayloadDiviner } from "@xyo-network/diviner-payload-abstract";
|
|
19
18
|
import { isPayloadDivinerQueryPayload } from "@xyo-network/diviner-payload-model";
|
|
20
|
-
import { SequenceConstants } from "@xyo-network/payload-model";
|
|
21
19
|
import { openDB } from "idb";
|
|
22
20
|
var payloadValueFilter = /* @__PURE__ */ __name((key, value) => {
|
|
23
21
|
if (!value) return void 0;
|
|
@@ -28,9 +26,6 @@ var payloadValueFilter = /* @__PURE__ */ __name((key, value) => {
|
|
|
28
26
|
return Array.isArray(sourceValue) && Array.isArray(value) ? containsAll(sourceValue, value) : sourceValue == value;
|
|
29
27
|
};
|
|
30
28
|
}, "payloadValueFilter");
|
|
31
|
-
var extractFields = /* @__PURE__ */ __name((indexName) => {
|
|
32
|
-
return indexName.slice(3).split(IndexSeparator).map((field) => field.toLowerCase());
|
|
33
|
-
}, "extractFields");
|
|
34
29
|
var IndexedDbPayloadDiviner = class extends PayloadDiviner {
|
|
35
30
|
static {
|
|
36
31
|
__name(this, "IndexedDbPayloadDiviner");
|
|
@@ -40,7 +35,6 @@ var IndexedDbPayloadDiviner = class extends PayloadDiviner {
|
|
|
40
35
|
IndexedDbPayloadDivinerConfigSchema
|
|
41
36
|
];
|
|
42
37
|
static defaultConfigSchema = IndexedDbPayloadDivinerConfigSchema;
|
|
43
|
-
_db;
|
|
44
38
|
/**
|
|
45
39
|
* The database name. If not supplied via config, it defaults
|
|
46
40
|
* to the archivist's name and if archivist's name is not supplied,
|
|
@@ -75,7 +69,7 @@ var IndexedDbPayloadDiviner = class extends PayloadDiviner {
|
|
|
75
69
|
const tx = db.transaction(this.storeName, "readonly");
|
|
76
70
|
const store = tx.objectStore(this.storeName);
|
|
77
71
|
const results = [];
|
|
78
|
-
let parsedCursor = cursor
|
|
72
|
+
let parsedCursor = cursor;
|
|
79
73
|
const parsedLimit = limit ?? 10;
|
|
80
74
|
assertEx((schemas?.length ?? 1) === 1, () => "IndexedDbPayloadDiviner: Only one filter schema supported");
|
|
81
75
|
const filterSchema = schemas?.[0];
|
|
@@ -85,14 +79,16 @@ var IndexedDbPayloadDiviner = class extends PayloadDiviner {
|
|
|
85
79
|
} : {
|
|
86
80
|
...props
|
|
87
81
|
};
|
|
82
|
+
const valueFilters = Object.entries(filter).map(([key, value]) => payloadValueFilter(key, value)).filter(exists);
|
|
88
83
|
const direction = order === "desc" ? "prev" : "next";
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
84
|
+
const sequenceIndex = assertEx(store.index(IndexedDbArchivist.sequenceIndexName), () => "Failed to get sequence index");
|
|
85
|
+
let dbCursor = assertEx(await sequenceIndex.openCursor(null, direction), () => `Failed to get cursor [${parsedCursor}, ${cursor}]`);
|
|
86
|
+
if (parsedCursor !== void 0) {
|
|
87
|
+
let currentSequence;
|
|
88
|
+
while (dbCursor && currentSequence !== parsedCursor) {
|
|
89
|
+
currentSequence = await dbCursor.value?.sequence;
|
|
90
|
+
dbCursor = await dbCursor.advance(1);
|
|
91
|
+
}
|
|
96
92
|
}
|
|
97
93
|
while (dbCursor && results.length < parsedLimit) {
|
|
98
94
|
const value = dbCursor.value;
|
|
@@ -120,31 +116,6 @@ var IndexedDbPayloadDiviner = class extends PayloadDiviner {
|
|
|
120
116
|
await super.startHandler();
|
|
121
117
|
return true;
|
|
122
118
|
}
|
|
123
|
-
getKeyRangeValue(indexName, query) {
|
|
124
|
-
if (!indexName) return [];
|
|
125
|
-
const indexFields = extractFields(indexName);
|
|
126
|
-
const keyRangeValue = indexFields.map((field) => query[field]);
|
|
127
|
-
return keyRangeValue.length === 1 ? keyRangeValue[0] : keyRangeValue;
|
|
128
|
-
}
|
|
129
|
-
selectBestIndex(query, store) {
|
|
130
|
-
const { indexNames } = store;
|
|
131
|
-
const queryKeys = new Set(Object.keys(query).map((key) => key.toLowerCase()));
|
|
132
|
-
let bestMatch = {
|
|
133
|
-
indexName: "",
|
|
134
|
-
matchCount: 0
|
|
135
|
-
};
|
|
136
|
-
for (const indexName of indexNames) {
|
|
137
|
-
const indexFields = extractFields(indexName);
|
|
138
|
-
const matchCount = indexFields.filter((field) => queryKeys.has(field)).length;
|
|
139
|
-
if (matchCount > bestMatch.matchCount) {
|
|
140
|
-
bestMatch = {
|
|
141
|
-
indexName,
|
|
142
|
-
matchCount
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
return bestMatch.matchCount > 0 ? bestMatch.indexName : null;
|
|
147
|
-
}
|
|
148
119
|
/**
|
|
149
120
|
* Checks that the desired DB/objectStore exists and is initialized to the correct version
|
|
150
121
|
* @returns The initialized DB or undefined if it does not exist in the desired state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Schema.ts","../../src/Config.ts","../../src/Diviner.ts"],"sourcesContent":["import { PayloadDivinerSchema } from '@xyo-network/diviner-payload-model'\n\nexport const IndexedDbPayloadDivinerSchema = `${PayloadDivinerSchema}.indexeddb` as const\nexport type IndexedDbPayloadDivinerSchema = typeof IndexedDbPayloadDivinerSchema\n","import type { IndexDescription } from '@xyo-network/archivist-model'\nimport type { DivinerConfig } from '@xyo-network/diviner-model'\n\nimport { IndexedDbPayloadDivinerSchema } from './Schema.ts'\n\nexport const IndexedDbPayloadDivinerConfigSchema = `${IndexedDbPayloadDivinerSchema}.config` as const\nexport type IndexedDbPayloadDivinerConfigSchema = typeof IndexedDbPayloadDivinerConfigSchema\n\nexport type IndexedDbPayloadDivinerConfig = DivinerConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbPayloadDivinerConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main diviner config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n","import { containsAll } from '@xylabs/array'\nimport { assertEx } from '@xylabs/assert'\nimport { exists } from '@xylabs/exists'\nimport type { Hash } from '@xylabs/hex'\nimport type { AnyObject } from '@xylabs/object'\nimport { removeFields } from '@xylabs/object'\nimport { IndexedDbArchivist } from '@xyo-network/archivist-indexeddb'\nimport { IndexSeparator } from '@xyo-network/archivist-model'\nimport type { DivinerInstance, DivinerModuleEventData } from '@xyo-network/diviner-model'\nimport { PayloadDiviner } from '@xyo-network/diviner-payload-abstract'\nimport type { PayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model'\nimport { isPayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model'\nimport {\n type Payload, type Schema, SequenceConstants,\n} from '@xyo-network/payload-model'\nimport type { IDBPDatabase, IDBPObjectStore } from 'idb'\nimport { openDB } from 'idb'\n\nimport { IndexedDbPayloadDivinerConfigSchema } from './Config.ts'\nimport type { IndexedDbPayloadDivinerParams } from './Params.ts'\n\ninterface PayloadStore {\n [s: string]: Payload\n}\n\ntype AnyPayload = Payload<Record<string, unknown>>\n\ntype ValueFilter = (payload?: AnyPayload | null) => boolean\n\nconst payloadValueFilter = (key: keyof AnyPayload, value?: unknown | unknown[]): ValueFilter | undefined => {\n if (!value) return undefined\n return (payload) => {\n if (!payload) return false\n const sourceValue = payload?.[key]\n if (sourceValue === undefined) return false\n return Array.isArray(sourceValue) && Array.isArray(value) ? containsAll(sourceValue, value) : sourceValue == value\n }\n}\n\n// Function to extract fields from an index name\nconst extractFields = (indexName: string): string[] => {\n return indexName\n .slice(3)\n .split(IndexSeparator)\n .map(field => field.toLowerCase())\n}\n\nexport class IndexedDbPayloadDiviner<\n TParams extends IndexedDbPayloadDivinerParams = IndexedDbPayloadDivinerParams,\n TIn extends PayloadDivinerQueryPayload = PayloadDivinerQueryPayload,\n TOut extends Payload = Payload,\n TEventData extends DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut> = DivinerModuleEventData<\n DivinerInstance<TParams, TIn, TOut>,\n TIn,\n TOut\n >,\n> extends PayloadDiviner<TParams, TIn, TOut, TEventData> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, IndexedDbPayloadDivinerConfigSchema]\n static override readonly defaultConfigSchema: Schema = IndexedDbPayloadDivinerConfigSchema\n\n private _db: IDBPDatabase<PayloadStore> | undefined\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the archivist's name and if archivist's name is not supplied,\n * it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.archivist ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to the archivist default version.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n protected override async divineHandler(payloads?: TIn[]): Promise<TOut[]> {\n const query = payloads?.find(isPayloadDivinerQueryPayload) as TIn\n if (!query) return []\n const result = await this.tryUseDb(async (db) => {\n const {\n schemas, limit, cursor, order, ...props\n } = removeFields(query as unknown as TIn & { sources?: Hash[] }, [\n 'hash',\n 'schema',\n ])\n const tx = db.transaction(this.storeName, 'readonly')\n const store = tx.objectStore(this.storeName)\n const results: TOut[] = []\n let parsedCursor = cursor ?? SequenceConstants.minLocalSequence\n const parsedLimit = limit ?? 10\n assertEx((schemas?.length ?? 1) === 1, () => 'IndexedDbPayloadDiviner: Only one filter schema supported')\n const filterSchema = schemas?.[0]\n const filter = filterSchema ? { schema: filterSchema, ...props } : { ...props }\n const direction: IDBCursorDirection = order === 'desc' ? 'prev' : 'next'\n const suggestedIndex = this.selectBestIndex(filter, store)\n const keyRangeValue = this.getKeyRangeValue(suggestedIndex, filter)\n const valueFilters: ValueFilter[]\n = props\n ? Object.entries(props)\n .map(([key, value]) => payloadValueFilter(key, value))\n .filter(exists)\n : []\n let dbCursor\n = suggestedIndex\n // Conditionally filter on schemas\n ? await store.index(suggestedIndex).openCursor(IDBKeyRange.only(keyRangeValue), direction)\n // Just iterate all records\n : await store.openCursor(suggestedIndex, direction)\n\n // Skip records until the offset is reached\n while (dbCursor && parsedCursor) {\n dbCursor = await dbCursor.advance(1)\n parsedCursor = SequenceConstants.minLocalSequence // Reset offset after skipping\n }\n // Collect results up to the limit\n while (dbCursor && results.length < parsedLimit) {\n const value = dbCursor.value\n if (value) {\n // If we're filtering on more than just the schema\n if (valueFilters.length > 0) {\n // Ensure all filters pass\n if (valueFilters.every(filter => filter(value))) {\n // Then save the value\n results.push(value)\n }\n } else {\n // Otherwise just save the value\n results.push(value)\n }\n }\n try {\n dbCursor = await dbCursor.continue()\n } catch {\n break\n }\n }\n await tx.done\n // Remove any metadata before returning to the client\n return results\n })\n return result ?? []\n }\n\n protected override async startHandler() {\n await super.startHandler()\n return true\n }\n\n private getKeyRangeValue(indexName: string | null, query: AnyObject): unknown | unknown[] {\n if (!indexName) return []\n\n // Extracting the relevant fields from the index name\n const indexFields = extractFields(indexName)\n\n // Collecting the values for these fields from the query object\n const keyRangeValue = indexFields.map(field => query[field as keyof AnyObject])\n return keyRangeValue.length === 1 ? keyRangeValue[0] : keyRangeValue\n }\n\n private selectBestIndex(query: AnyObject, store: IDBPObjectStore<PayloadStore>): string | null {\n // List of available indexes\n const { indexNames } = store\n\n // Convert query object keys to a set for easier comparison\n const queryKeys = new Set(Object.keys(query).map(key => key.toLowerCase()))\n\n // Find the best matching index\n let bestMatch: { indexName: string; matchCount: number } = { indexName: '', matchCount: 0 }\n\n for (const indexName of indexNames) {\n const indexFields = extractFields(indexName)\n const matchCount = indexFields.filter(field => queryKeys.has(field)).length\n if (matchCount > bestMatch.matchCount) {\n bestMatch = { indexName, matchCount }\n }\n }\n return bestMatch.matchCount > 0 ? bestMatch.indexName : null\n }\n\n /**\n * Checks that the desired DB/objectStore exists and is initialized to the correct version\n * @returns The initialized DB or undefined if it does not exist in the desired state\n */\n private async tryGetInitializedDb(): Promise<IDBPDatabase<PayloadStore> | undefined> {\n // Enumerate the DBs\n const dbs = await indexedDB.databases()\n // Check that the DB exists at the desired version\n const dbExists = dbs.some((db) => {\n return db.name === this.dbName && db.version === this.dbVersion\n })\n // If the DB exists at the desired version\n if (dbExists) {\n // If the db does exist, open it\n const db = await openDB<PayloadStore>(this.dbName, this.dbVersion)\n // Check that the desired objectStore exists\n const storeExists = db.objectStoreNames.contains(this.storeName)\n // If the correct db/version/objectStore exists\n if (storeExists) {\n return db\n } else {\n // Otherwise close the db so the process that is going to update the\n // db can open it\n db.close()\n }\n }\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async tryUseDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T | undefined> {\n // Get the initialized DB\n const db = await this.tryGetInitializedDb()\n if (db) {\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n return undefined\n }\n}\n"],"mappings":";;;;AAAA,SAASA,4BAA4B;AAE9B,IAAMC,gCAAgC,GAAGD,oBAAAA;;;ACGzC,IAAME,sCAAsC,GAAGC,6BAAAA;;;ACLtD,SAASC,mBAAmB;AAC5B,SAASC,gBAAgB;AACzB,SAASC,cAAc;AAGvB,S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,QAAIgE,UAAU;AAEZ,YAAMrD,KAAK,MAAMyD,OAAqB,KAAKzE,QAAQ,KAAKK,SAAS;AAEjE,YAAMqE,cAAc1D,GAAG2D,iBAAiBC,SAAS,KAAKrE,SAAS;AAE/D,UAAImE,aAAa;AACf,eAAO1D;MACT,OAAO;AAGLA,WAAG6D,MAAK;MACV;IACF;EACF;;;;;;EAOA,MAAc9D,SAAY+D,UAAsF;AAE9G,UAAM9D,KAAK,MAAM,KAAKiD,oBAAmB;AACzC,QAAIjD,IAAI;AACN,UAAI;AAEF,eAAO,MAAM8D,SAAS9D,EAAAA;MACxB,UAAA;AAEEA,WAAG6D,MAAK;MACV;IACF;AACA,WAAOjG;EACT;AACF;","names":["PayloadDivinerSchema","IndexedDbPayloadDivinerSchema","IndexedDbPayloadDivinerConfigSchema","IndexedDbPayloadDivinerSchema","containsAll","assertEx","exists","removeFields","IndexedDbArchivist","IndexSeparator","PayloadDiviner","isPayloadDivinerQueryPayload","SequenceConstants","openDB","payloadValueFilter","key","value","undefined","payload","sourceValue","Array","isArray","containsAll","extractFields","indexName","slice","split","IndexSeparator","map","field","toLowerCase","IndexedDbPayloadDiviner","PayloadDiviner","configSchemas","IndexedDbPayloadDivinerConfigSchema","defaultConfigSchema","_db","dbName","config","archivist","IndexedDbArchivist","defaultDbName","dbVersion","defaultDbVersion","storeName","defaultStoreName","divineHandler","payloads","query","find","isPayloadDivinerQueryPayload","result","tryUseDb","db","schemas","limit","cursor","order","props","removeFields","tx","transaction","store","objectStore","results","parsedCursor","SequenceConstants","minLocalSequence","parsedLimit","assertEx","length","filterSchema","filter","schema","direction","suggestedIndex","selectBestIndex","keyRangeValue","getKeyRangeValue","valueFilters","Object","entries","exists","dbCursor","index","openCursor","IDBKeyRange","only","advance","every","push","continue","done","startHandler","indexFields","indexNames","queryKeys","Set","keys","bestMatch","matchCount","has","tryGetInitializedDb","dbs","indexedDB","databases","dbExists","some","name","version","openDB","storeExists","objectStoreNames","contains","close","callback"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Schema.ts","../../src/Config.ts","../../src/Diviner.ts"],"sourcesContent":["import { PayloadDivinerSchema } from '@xyo-network/diviner-payload-model'\n\nexport const IndexedDbPayloadDivinerSchema = `${PayloadDivinerSchema}.indexeddb` as const\nexport type IndexedDbPayloadDivinerSchema = typeof IndexedDbPayloadDivinerSchema\n","import type { IndexDescription } from '@xyo-network/archivist-model'\nimport type { DivinerConfig } from '@xyo-network/diviner-model'\n\nimport { IndexedDbPayloadDivinerSchema } from './Schema.ts'\n\nexport const IndexedDbPayloadDivinerConfigSchema = `${IndexedDbPayloadDivinerSchema}.config` as const\nexport type IndexedDbPayloadDivinerConfigSchema = typeof IndexedDbPayloadDivinerConfigSchema\n\nexport type IndexedDbPayloadDivinerConfig = DivinerConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbPayloadDivinerConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main diviner config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n","import { containsAll } from '@xylabs/array'\nimport { assertEx } from '@xylabs/assert'\nimport { exists } from '@xylabs/exists'\nimport type { Hash } from '@xylabs/hex'\nimport { removeFields } from '@xylabs/object'\nimport { IndexedDbArchivist } from '@xyo-network/archivist-indexeddb'\nimport type { DivinerInstance, DivinerModuleEventData } from '@xyo-network/diviner-model'\nimport { PayloadDiviner } from '@xyo-network/diviner-payload-abstract'\nimport type { PayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model'\nimport { isPayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model'\nimport type {\n Payload, Schema, Sequence,\n} from '@xyo-network/payload-model'\nimport type { IDBPCursorWithValue, IDBPDatabase } from 'idb'\nimport { openDB } from 'idb'\n\nimport { IndexedDbPayloadDivinerConfigSchema } from './Config.ts'\nimport type { IndexedDbPayloadDivinerParams } from './Params.ts'\n\ninterface PayloadStore {\n [s: string]: Payload\n}\n\ntype AnyPayload = Payload<Record<string, unknown>>\n\ntype ValueFilter = (payload?: AnyPayload | null) => boolean\n\nconst payloadValueFilter = (key: keyof AnyPayload, value?: unknown | unknown[]): ValueFilter | undefined => {\n if (!value) return undefined\n return (payload) => {\n if (!payload) return false\n const sourceValue = payload?.[key]\n if (sourceValue === undefined) return false\n return Array.isArray(sourceValue) && Array.isArray(value) ? containsAll(sourceValue, value) : sourceValue == value\n }\n}\n\nexport class IndexedDbPayloadDiviner<\n TParams extends IndexedDbPayloadDivinerParams = IndexedDbPayloadDivinerParams,\n TIn extends PayloadDivinerQueryPayload = PayloadDivinerQueryPayload,\n TOut extends Payload = Payload,\n TEventData extends DivinerModuleEventData<DivinerInstance<TParams, TIn, TOut>, TIn, TOut> = DivinerModuleEventData<\n DivinerInstance<TParams, TIn, TOut>,\n TIn,\n TOut\n >,\n> extends PayloadDiviner<TParams, TIn, TOut, TEventData> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, IndexedDbPayloadDivinerConfigSchema]\n static override readonly defaultConfigSchema: Schema = IndexedDbPayloadDivinerConfigSchema\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the archivist's name and if archivist's name is not supplied,\n * it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.archivist ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to the archivist default version.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n protected override async divineHandler(payloads?: TIn[]): Promise<TOut[]> {\n const query = payloads?.find(isPayloadDivinerQueryPayload) as TIn\n if (!query) return []\n const result = await this.tryUseDb(async (db) => {\n const {\n schemas, limit, cursor, order, ...props\n } = removeFields(query as unknown as TIn & { sources?: Hash[] }, [\n 'hash',\n 'schema',\n ])\n const tx = db.transaction(this.storeName, 'readonly')\n const store = tx.objectStore(this.storeName)\n const results: TOut[] = []\n let parsedCursor = cursor\n const parsedLimit = limit ?? 10\n assertEx((schemas?.length ?? 1) === 1, () => 'IndexedDbPayloadDiviner: Only one filter schema supported')\n const filterSchema = schemas?.[0]\n const filter = filterSchema ? { schema: filterSchema, ...props } : { ...props }\n const valueFilters: ValueFilter[] = Object.entries(filter)\n .map(([key, value]) => payloadValueFilter(key, value))\n .filter(exists)\n const direction: IDBCursorDirection = order === 'desc' ? 'prev' : 'next'\n\n // Iterate all records using the sequence index\n const sequenceIndex = assertEx(store.index(IndexedDbArchivist.sequenceIndexName), () => 'Failed to get sequence index')\n let dbCursor: IDBPCursorWithValue<PayloadStore, [string], string, string, 'readonly'> | null\n = assertEx(await sequenceIndex.openCursor(null, direction), () => `Failed to get cursor [${parsedCursor}, ${cursor}]`)\n\n // If a cursor was supplied\n if (parsedCursor !== undefined) {\n let currentSequence: Sequence | undefined\n // Skip records until the supplied cursor offset is reached\n while (dbCursor && currentSequence !== parsedCursor) {\n // Find the sequence of the current record\n currentSequence = await dbCursor.value?.sequence\n // Advance one record beyond the cursor\n dbCursor = await dbCursor.advance(1)\n }\n }\n\n // Collect results up to the limit\n while (dbCursor && results.length < parsedLimit) {\n const value = dbCursor.value\n if (value) {\n // If we're filtering on more than just the schema\n if (valueFilters.length > 0) {\n // Ensure all filters pass\n if (valueFilters.every(filter => filter(value))) {\n // Then save the value\n results.push(value)\n }\n } else {\n // Otherwise just save the value\n results.push(value)\n }\n }\n try {\n dbCursor = await dbCursor.continue()\n } catch {\n break\n }\n }\n await tx.done\n // Remove any metadata before returning to the client\n return results\n })\n return result ?? []\n }\n\n protected override async startHandler() {\n await super.startHandler()\n return true\n }\n\n /**\n * Checks that the desired DB/objectStore exists and is initialized to the correct version\n * @returns The initialized DB or undefined if it does not exist in the desired state\n */\n private async tryGetInitializedDb(): Promise<IDBPDatabase<PayloadStore> | undefined> {\n // Enumerate the DBs\n const dbs = await indexedDB.databases()\n // Check that the DB exists at the desired version\n const dbExists = dbs.some((db) => {\n return db.name === this.dbName && db.version === this.dbVersion\n })\n // If the DB exists at the desired version\n if (dbExists) {\n // If the db does exist, open it\n const db = await openDB<PayloadStore>(this.dbName, this.dbVersion)\n // Check that the desired objectStore exists\n const storeExists = db.objectStoreNames.contains(this.storeName)\n // If the correct db/version/objectStore exists\n if (storeExists) {\n return db\n } else {\n // Otherwise close the db so the process that is going to update the\n // db can open it\n db.close()\n }\n }\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async tryUseDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T | undefined> {\n // Get the initialized DB\n const db = await this.tryGetInitializedDb()\n if (db) {\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n return undefined\n }\n}\n"],"mappings":";;;;AAAA,SAASA,4BAA4B;AAE9B,IAAMC,gCAAgC,GAAGD,oBAAAA;;;ACGzC,IAAME,sCAAsC,GAAGC,6BAAAA;;;ACLtD,SAASC,mBAAmB;AAC5B,SAASC,gBAAgB;AACzB,SAASC,cAAc;AAEvB,SAASC,oBAAoB;AAC7B,SAASC,0BAA0B;AAEnC,SAASC,sBAAsB;AAE/B,SAASC,oCAAoC;AAK7C,SAASC,cAAc;AAavB,IAAMC,qBAAqB,wBAACC,KAAuBC,UAAAA;AACjD,MAAI,CAACA,MAAO,QAAOC;AACnB,SAAO,CAACC,YAAAA;AACN,QAAI,CAACA,QAAS,QAAO;AACrB,UAAMC,cAAcD,UAAUH,GAAAA;AAC9B,QAAII,gBAAgBF,OAAW,QAAO;AACtC,WAAOG,MAAMC,QAAQF,WAAAA,KAAgBC,MAAMC,QAAQL,KAAAA,IAASM,YAAYH,aA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AAO/C;MACT,OAAO;AAGLA,WAAGkD,MAAK;MACV;IACF;EACF;;;;;;EAOA,MAAcnD,SAAYoD,UAAsF;AAE9G,UAAMnD,KAAK,MAAM,KAAKsC,oBAAmB;AACzC,QAAItC,IAAI;AACN,UAAI;AAEF,eAAO,MAAMmD,SAASnD,EAAAA;MACxB,UAAA;AAEEA,WAAGkD,MAAK;MACV;IACF;AACA,WAAO7E;EACT;AACF;","names":["PayloadDivinerSchema","IndexedDbPayloadDivinerSchema","IndexedDbPayloadDivinerConfigSchema","IndexedDbPayloadDivinerSchema","containsAll","assertEx","exists","removeFields","IndexedDbArchivist","PayloadDiviner","isPayloadDivinerQueryPayload","openDB","payloadValueFilter","key","value","undefined","payload","sourceValue","Array","isArray","containsAll","IndexedDbPayloadDiviner","PayloadDiviner","configSchemas","IndexedDbPayloadDivinerConfigSchema","defaultConfigSchema","dbName","config","archivist","IndexedDbArchivist","defaultDbName","dbVersion","defaultDbVersion","storeName","defaultStoreName","divineHandler","payloads","query","find","isPayloadDivinerQueryPayload","result","tryUseDb","db","schemas","limit","cursor","order","props","removeFields","tx","transaction","store","objectStore","results","parsedCursor","parsedLimit","assertEx","length","filterSchema","filter","schema","valueFilters","Object","entries","map","exists","direction","sequenceIndex","index","sequenceIndexName","dbCursor","openCursor","currentSequence","sequence","advance","every","push","continue","done","startHandler","tryGetInitializedDb","dbs","indexedDB","databases","dbExists","some","name","version","openDB","storeExists","objectStoreNames","contains","close","callback"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xyo-network/diviner-payload-indexeddb",
|
|
3
|
-
"version": "3.6.0-rc.
|
|
3
|
+
"version": "3.6.0-rc.8",
|
|
4
4
|
"description": "Primary SDK for using XYO Protocol 2.0",
|
|
5
5
|
"homepage": "https://xyo.network",
|
|
6
6
|
"bugs": {
|
|
@@ -29,28 +29,28 @@
|
|
|
29
29
|
"module": "dist/browser/index.mjs",
|
|
30
30
|
"types": "dist/browser/index.d.ts",
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@xylabs/array": "^4.4.
|
|
33
|
-
"@xylabs/assert": "^4.4.
|
|
34
|
-
"@xylabs/exists": "^4.4.
|
|
35
|
-
"@xylabs/hex": "^4.4.
|
|
36
|
-
"@xylabs/object": "^4.4.
|
|
37
|
-
"@xyo-network/archivist-indexeddb": "^3.6.0-rc.
|
|
38
|
-
"@xyo-network/archivist-model": "^3.6.0-rc.
|
|
39
|
-
"@xyo-network/diviner-model": "^3.6.0-rc.
|
|
40
|
-
"@xyo-network/diviner-payload-abstract": "^3.6.0-rc.
|
|
41
|
-
"@xyo-network/diviner-payload-model": "^3.6.0-rc.
|
|
42
|
-
"@xyo-network/module-model": "^3.6.0-rc.
|
|
43
|
-
"@xyo-network/payload-model": "^3.6.0-rc.
|
|
32
|
+
"@xylabs/array": "^4.4.16",
|
|
33
|
+
"@xylabs/assert": "^4.4.16",
|
|
34
|
+
"@xylabs/exists": "^4.4.16",
|
|
35
|
+
"@xylabs/hex": "^4.4.16",
|
|
36
|
+
"@xylabs/object": "^4.4.16",
|
|
37
|
+
"@xyo-network/archivist-indexeddb": "^3.6.0-rc.8",
|
|
38
|
+
"@xyo-network/archivist-model": "^3.6.0-rc.8",
|
|
39
|
+
"@xyo-network/diviner-model": "^3.6.0-rc.8",
|
|
40
|
+
"@xyo-network/diviner-payload-abstract": "^3.6.0-rc.8",
|
|
41
|
+
"@xyo-network/diviner-payload-model": "^3.6.0-rc.8",
|
|
42
|
+
"@xyo-network/module-model": "^3.6.0-rc.8",
|
|
43
|
+
"@xyo-network/payload-model": "^3.6.0-rc.8",
|
|
44
44
|
"idb": "^8.0.1"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@xylabs/delay": "^4.4.
|
|
47
|
+
"@xylabs/delay": "^4.4.16",
|
|
48
48
|
"@xylabs/ts-scripts-yarn3": "^4.2.4",
|
|
49
49
|
"@xylabs/tsconfig": "^4.2.4",
|
|
50
|
-
"@xylabs/vitest-extended": "^4.4.
|
|
51
|
-
"@xyo-network/archivist-indexeddb": "^3.6.0-rc.
|
|
52
|
-
"@xyo-network/node-memory": "^3.6.0-rc.
|
|
53
|
-
"@xyo-network/payload-builder": "^3.6.0-rc.
|
|
50
|
+
"@xylabs/vitest-extended": "^4.4.16",
|
|
51
|
+
"@xyo-network/archivist-indexeddb": "^3.6.0-rc.8",
|
|
52
|
+
"@xyo-network/node-memory": "^3.6.0-rc.8",
|
|
53
|
+
"@xyo-network/payload-builder": "^3.6.0-rc.8",
|
|
54
54
|
"fake-indexeddb": "^6.0.0",
|
|
55
55
|
"typescript": "^5.7.2",
|
|
56
56
|
"vitest": "^2.1.8"
|
package/src/Diviner.ts
CHANGED
|
@@ -2,18 +2,16 @@ import { containsAll } from '@xylabs/array'
|
|
|
2
2
|
import { assertEx } from '@xylabs/assert'
|
|
3
3
|
import { exists } from '@xylabs/exists'
|
|
4
4
|
import type { Hash } from '@xylabs/hex'
|
|
5
|
-
import type { AnyObject } from '@xylabs/object'
|
|
6
5
|
import { removeFields } from '@xylabs/object'
|
|
7
6
|
import { IndexedDbArchivist } from '@xyo-network/archivist-indexeddb'
|
|
8
|
-
import { IndexSeparator } from '@xyo-network/archivist-model'
|
|
9
7
|
import type { DivinerInstance, DivinerModuleEventData } from '@xyo-network/diviner-model'
|
|
10
8
|
import { PayloadDiviner } from '@xyo-network/diviner-payload-abstract'
|
|
11
9
|
import type { PayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model'
|
|
12
10
|
import { isPayloadDivinerQueryPayload } from '@xyo-network/diviner-payload-model'
|
|
13
|
-
import {
|
|
14
|
-
|
|
11
|
+
import type {
|
|
12
|
+
Payload, Schema, Sequence,
|
|
15
13
|
} from '@xyo-network/payload-model'
|
|
16
|
-
import type {
|
|
14
|
+
import type { IDBPCursorWithValue, IDBPDatabase } from 'idb'
|
|
17
15
|
import { openDB } from 'idb'
|
|
18
16
|
|
|
19
17
|
import { IndexedDbPayloadDivinerConfigSchema } from './Config.ts'
|
|
@@ -37,14 +35,6 @@ const payloadValueFilter = (key: keyof AnyPayload, value?: unknown | unknown[]):
|
|
|
37
35
|
}
|
|
38
36
|
}
|
|
39
37
|
|
|
40
|
-
// Function to extract fields from an index name
|
|
41
|
-
const extractFields = (indexName: string): string[] => {
|
|
42
|
-
return indexName
|
|
43
|
-
.slice(3)
|
|
44
|
-
.split(IndexSeparator)
|
|
45
|
-
.map(field => field.toLowerCase())
|
|
46
|
-
}
|
|
47
|
-
|
|
48
38
|
export class IndexedDbPayloadDiviner<
|
|
49
39
|
TParams extends IndexedDbPayloadDivinerParams = IndexedDbPayloadDivinerParams,
|
|
50
40
|
TIn extends PayloadDivinerQueryPayload = PayloadDivinerQueryPayload,
|
|
@@ -58,8 +48,6 @@ export class IndexedDbPayloadDiviner<
|
|
|
58
48
|
static override readonly configSchemas: Schema[] = [...super.configSchemas, IndexedDbPayloadDivinerConfigSchema]
|
|
59
49
|
static override readonly defaultConfigSchema: Schema = IndexedDbPayloadDivinerConfigSchema
|
|
60
50
|
|
|
61
|
-
private _db: IDBPDatabase<PayloadStore> | undefined
|
|
62
|
-
|
|
63
51
|
/**
|
|
64
52
|
* The database name. If not supplied via config, it defaults
|
|
65
53
|
* to the archivist's name and if archivist's name is not supplied,
|
|
@@ -99,32 +87,33 @@ export class IndexedDbPayloadDiviner<
|
|
|
99
87
|
const tx = db.transaction(this.storeName, 'readonly')
|
|
100
88
|
const store = tx.objectStore(this.storeName)
|
|
101
89
|
const results: TOut[] = []
|
|
102
|
-
let parsedCursor = cursor
|
|
90
|
+
let parsedCursor = cursor
|
|
103
91
|
const parsedLimit = limit ?? 10
|
|
104
92
|
assertEx((schemas?.length ?? 1) === 1, () => 'IndexedDbPayloadDiviner: Only one filter schema supported')
|
|
105
93
|
const filterSchema = schemas?.[0]
|
|
106
94
|
const filter = filterSchema ? { schema: filterSchema, ...props } : { ...props }
|
|
95
|
+
const valueFilters: ValueFilter[] = Object.entries(filter)
|
|
96
|
+
.map(([key, value]) => payloadValueFilter(key, value))
|
|
97
|
+
.filter(exists)
|
|
107
98
|
const direction: IDBCursorDirection = order === 'desc' ? 'prev' : 'next'
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
while (dbCursor && parsedCursor) {
|
|
125
|
-
dbCursor = await dbCursor.advance(1)
|
|
126
|
-
parsedCursor = SequenceConstants.minLocalSequence // Reset offset after skipping
|
|
99
|
+
|
|
100
|
+
// Iterate all records using the sequence index
|
|
101
|
+
const sequenceIndex = assertEx(store.index(IndexedDbArchivist.sequenceIndexName), () => 'Failed to get sequence index')
|
|
102
|
+
let dbCursor: IDBPCursorWithValue<PayloadStore, [string], string, string, 'readonly'> | null
|
|
103
|
+
= assertEx(await sequenceIndex.openCursor(null, direction), () => `Failed to get cursor [${parsedCursor}, ${cursor}]`)
|
|
104
|
+
|
|
105
|
+
// If a cursor was supplied
|
|
106
|
+
if (parsedCursor !== undefined) {
|
|
107
|
+
let currentSequence: Sequence | undefined
|
|
108
|
+
// Skip records until the supplied cursor offset is reached
|
|
109
|
+
while (dbCursor && currentSequence !== parsedCursor) {
|
|
110
|
+
// Find the sequence of the current record
|
|
111
|
+
currentSequence = await dbCursor.value?.sequence
|
|
112
|
+
// Advance one record beyond the cursor
|
|
113
|
+
dbCursor = await dbCursor.advance(1)
|
|
114
|
+
}
|
|
127
115
|
}
|
|
116
|
+
|
|
128
117
|
// Collect results up to the limit
|
|
129
118
|
while (dbCursor && results.length < parsedLimit) {
|
|
130
119
|
const value = dbCursor.value
|
|
@@ -159,37 +148,6 @@ export class IndexedDbPayloadDiviner<
|
|
|
159
148
|
return true
|
|
160
149
|
}
|
|
161
150
|
|
|
162
|
-
private getKeyRangeValue(indexName: string | null, query: AnyObject): unknown | unknown[] {
|
|
163
|
-
if (!indexName) return []
|
|
164
|
-
|
|
165
|
-
// Extracting the relevant fields from the index name
|
|
166
|
-
const indexFields = extractFields(indexName)
|
|
167
|
-
|
|
168
|
-
// Collecting the values for these fields from the query object
|
|
169
|
-
const keyRangeValue = indexFields.map(field => query[field as keyof AnyObject])
|
|
170
|
-
return keyRangeValue.length === 1 ? keyRangeValue[0] : keyRangeValue
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
private selectBestIndex(query: AnyObject, store: IDBPObjectStore<PayloadStore>): string | null {
|
|
174
|
-
// List of available indexes
|
|
175
|
-
const { indexNames } = store
|
|
176
|
-
|
|
177
|
-
// Convert query object keys to a set for easier comparison
|
|
178
|
-
const queryKeys = new Set(Object.keys(query).map(key => key.toLowerCase()))
|
|
179
|
-
|
|
180
|
-
// Find the best matching index
|
|
181
|
-
let bestMatch: { indexName: string; matchCount: number } = { indexName: '', matchCount: 0 }
|
|
182
|
-
|
|
183
|
-
for (const indexName of indexNames) {
|
|
184
|
-
const indexFields = extractFields(indexName)
|
|
185
|
-
const matchCount = indexFields.filter(field => queryKeys.has(field)).length
|
|
186
|
-
if (matchCount > bestMatch.matchCount) {
|
|
187
|
-
bestMatch = { indexName, matchCount }
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
return bestMatch.matchCount > 0 ? bestMatch.indexName : null
|
|
191
|
-
}
|
|
192
|
-
|
|
193
151
|
/**
|
|
194
152
|
* Checks that the desired DB/objectStore exists and is initialized to the correct version
|
|
195
153
|
* @returns The initialized DB or undefined if it does not exist in the desired state
|