@routier/pouchdb-plugin 0.3.0 → 0.5.0

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/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @routier/pouchdb-plugin
2
2
 
3
+ <p align="center">
4
+ <img src="https://routier.dev/routier.svg" alt="Routier" width="140" height="140" />
5
+ </p>
6
+
3
7
  Routier storage backed by PouchDB, with optional replication to CouchDB.
4
8
 
5
9
  ```ts
@@ -115,5 +119,5 @@ Node 18 or later, and any browser. PouchDB 9. CouchDB 3 for replication.
115
119
 
116
120
  ## See also
117
121
 
118
- - [PouchDB plugin guide](../../docs/integrations/plugins/built-in-plugins/pouchdb/README.md)
122
+ - [PouchDB plugin guide](https://routier.dev/integrations/plugins/built-in-plugins/pouchdb/README)
119
123
  - `e2e/src/couchdbReplication.test.ts` — replication against a real CouchDB
package/dist/index.cjs CHANGED
@@ -741,10 +741,24 @@ class PouchDbPlugin {
741
741
  }, done);
742
742
  }
743
743
  _validateSchemas(event) {
744
- for (const [, schema] of event.schemas){
744
+ for (const [schemaId, schema] of event.schemas){
745
+ // Only schemas this persist actually writes: a store may declare other collections,
746
+ // and an unused bad one should not block saves to the good ones.
747
+ if (event.operation.get(schemaId)?.hasItems !== true) {
748
+ continue;
749
+ }
745
750
  if (schema.idProperties.length > 1) {
746
751
  throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key");
747
752
  }
753
+ // An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an
754
+ // identity key under any other name is never filled in: every entity reads back with
755
+ // an undefined key and the change tracker merges them all into one. Corruption, not
756
+ // an error — so refuse the schema up front. A caller-supplied key (default/computed)
757
+ // is stored as an ordinary field and round-trips fine under any name.
758
+ const key = schema.idProperties[0];
759
+ if (key != null && key.isIdentity && key.name !== "_id") {
760
+ throw new Error(`PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` + `'${key.name}' as its identity key, which PouchDB cannot fill in. ` + `Declare the key as: _id: s.string().key().identity()`);
761
+ }
748
762
  }
749
763
  }
750
764
  _bulkPersist(event, done) {
@@ -917,6 +931,9 @@ class PouchDbPlugin {
917
931
  return;
918
932
  }
919
933
  try {
934
+ event.executedQueries.push({
935
+ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query`
936
+ });
920
937
  const translated = translator.translate(response.rows.map((w)=>w.doc));
921
938
  d(results_namespaceObject.Result.success(translated));
922
939
  } catch (e) {
@@ -940,6 +957,9 @@ class PouchDbPlugin {
940
957
  include_docs: true
941
958
  }).then((response)=>{
942
959
  try {
960
+ event.executedQueries.push({
961
+ text: "allDocs({ include_docs: true }): full database scan, no index"
962
+ });
943
963
  const data = response.rows.map((w)=>w.doc);
944
964
  const translated = translator.translate(data);
945
965
  d(results_namespaceObject.Result.success(translated));
@@ -962,6 +982,9 @@ class PouchDbPlugin {
962
982
  }).then((response)=>{
963
983
  const data = response.rows.map((w)=>w.doc);
964
984
  try {
985
+ event.executedQueries.push({
986
+ text: "allDocs({ include_docs: true }): full database scan, no index"
987
+ });
965
988
  const translated = translator.translate(data);
966
989
  d(results_namespaceObject.Result.success(translated));
967
990
  } catch (e) {
@@ -983,6 +1006,9 @@ class PouchDbPlugin {
983
1006
  }
984
1007
  const data = response.rows.map((w)=>w.value);
985
1008
  try {
1009
+ event.executedQueries.push({
1010
+ text: "view query"
1011
+ });
986
1012
  const translated = translator.translate(data);
987
1013
  d(results_namespaceObject.Result.success(translated));
988
1014
  } catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/compat_get_default_export","webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/webpack/runtime/make_namespace_object","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { CompiledSchema, InferType } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n private schema: CompiledSchema<TEntity>;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.schema = query.schema;\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const result: unknown[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const entity: any = data[i];\n\n // design docs can be included in the result, ignore them\n if (\"_id\" in entity && typeof entity._id === \"string\" && entity._id.startsWith(\"_design\")) {\n continue;\n }\n\n try {\n // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected\n result.push(this.schema.deserialize(entity as InferType<TEntity>));\n data[i] = null;\n } catch (e) {\n throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)\n }\n }\n\n return super.translate(result);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\" }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const property = index.properties[0];\n const path = property.getAssignmentPath({ parent: \"doc\" });\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [, schema] of event.schemas) {\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","result","i","length","entity","e","Error","JSON","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","db","documents","done","missing","document","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","property","path","matchingIndex","views","Object","schema","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,iCAAiC,WAAW;AAC5C;AACA;;;;;ACPA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;ACAA;AACA;AACA;AACA,uDAAuD,iBAAiB;AACxE;AACA,gDAAgD,aAAa;AAC7D,E;;;;;;;;;;;;;;;;;;;ACNyD;AAEwC;AAG1F,MAAME,0BAAgFD,sCAAcA;IAE/F,OAAgC;IAChC,gBAAqD,KAAK;IAElE,YAAYE,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,MAAM,GAAGA,MAAM,MAAM;IAC9B;IAEA,QAAQC,IAAa,EAAE;QACnB,mCAAmC;QACnC,MAAMC,cAAc,IAAI,CAAC,kBAAkB;QAE3C,8DAA8D;QAC9D,OAAOA,YAAYD;IACvB;IAEQ,qBAAiD;QACrD,mCAAmC;QACnC,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM;YAC7B,OAAO,IAAI,CAAC,aAAa;QAC7B;QAEA,mCAAmC;QACnC,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OAAO,CAAC,OAAO,CAAC;QAC5C,MAAMpF,UAAUoF,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC;QAE5C,4DAA4D;QAC5D,IAAIpF,QAAQ,MAAM,GAAG,GAAG;YACpB,OAAO;QACX;QAEA,IAAIoH,OAAO,QAAQA,IAAI,MAAM,KAAK,YAAY;YAC1C,OAAO;QACX;QAEA,IAAIA,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,KAAK,KAAKA,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ,IAAI,MAAM;YACvE,OAAO;QACX;QAEA,MAAM7B,WAAW6B,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ;QAE7C,MAAM,EAAEjC,QAAQ,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAACI;QAE7C,IAAID,KAAK,KAAK,IAAI,MAAM;YACpB,OAAO;QACX;QAEA,MAAMnF,QAAQmF,KAAK,KAAK,CAACH,SAAS;QAElC,IAAIhF,SAAS,MAAM;YACf,OAAO;QACX;QAEA,OAAO;YACHgF;YACA,YAAY;gBAAC;oBAAEI;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;ACppCgD"}
1
+ {"version":3,"file":"index.cjs","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/compat_get_default_export","webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/webpack/runtime/make_namespace_object","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["// getDefaultExport function for compatibility with non-ESM modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};\n","__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { CompiledSchema, InferType } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n private schema: CompiledSchema<TEntity>;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.schema = query.schema;\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const result: unknown[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const entity: any = data[i];\n\n // design docs can be included in the result, ignore them\n if (\"_id\" in entity && typeof entity._id === \"string\" && entity._id.startsWith(\"_design\")) {\n continue;\n }\n\n try {\n // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected\n result.push(this.schema.deserialize(entity as InferType<TEntity>));\n data[i] = null;\n } catch (e) {\n throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)\n }\n }\n\n return super.translate(result);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\" }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const property = index.properties[0];\n const path = property.getAssignmentPath({ parent: \"doc\" });\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [schemaId, schema] of event.schemas) {\n\n // Only schemas this persist actually writes: a store may declare other collections,\n // and an unused bad one should not block saves to the good ones.\n if (event.operation.get(schemaId)?.hasItems !== true) {\n continue;\n }\n\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n\n // An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an\n // identity key under any other name is never filled in: every entity reads back with\n // an undefined key and the change tracker merges them all into one. Corruption, not\n // an error — so refuse the schema up front. A caller-supplied key (default/computed)\n // is stored as an ordinary field and round-trips fine under any name.\n const key = schema.idProperties[0];\n if (key != null && key.isIdentity && key.name !== \"_id\") {\n throw new Error(\n `PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` +\n `'${key.name}' as its identity key, which PouchDB cannot fill in. ` +\n `Declare the key as: _id: s.string().key().identity()`\n );\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n event.executedQueries.push({ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query` });\n\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n event.executedQueries.push({ text: \"view query\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","result","i","length","entity","e","Error","JSON","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","db","documents","done","missing","document","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","property","path","matchingIndex","views","Object","schema","key","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,iCAAiC,WAAW;AAC5C;AACA;;;;;ACPA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;ACAA;AACA;AACA;AACA,uDAAuD,iBAAiB;AACxE;AACA,gDAAgD,aAAa;A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SAAS,CAAC,OAAO,CAAC,OAAO,CAAC;QAC5C,MAAMpF,UAAUoF,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC;QAE5C,4DAA4D;QAC5D,IAAIpF,QAAQ,MAAM,GAAG,GAAG;YACpB,OAAO;QACX;QAEA,IAAIqH,OAAO,QAAQA,IAAI,MAAM,KAAK,YAAY;YAC1C,OAAO;QACX;QAEA,IAAIA,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,KAAK,KAAKA,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ,IAAI,MAAM;YACvE,OAAO;QACX;QAEA,MAAM9B,WAAW8B,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ;QAE7C,MAAM,EAAElC,QAAQ,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAACI;QAE7C,IAAID,KAAK,KAAK,IAAI,MAAM;YACpB,OAAO;QACX;QAEA,MAAMnF,QAAQmF,KAAK,KAAK,CAACH,SAAS;QAElC,IAAIhF,SAAS,MAAM;YACf,OAAO;QACX;QAEA,OAAO;YACHgF;YACA,YAAY;gBAAC;oBAAEI;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;ACjrCgD"}
package/dist/index.js CHANGED
@@ -720,10 +720,24 @@ class PouchDbPlugin {
720
720
  }, done);
721
721
  }
722
722
  _validateSchemas(event) {
723
- for (const [, schema] of event.schemas){
723
+ for (const [schemaId, schema] of event.schemas){
724
+ // Only schemas this persist actually writes: a store may declare other collections,
725
+ // and an unused bad one should not block saves to the good ones.
726
+ if (event.operation.get(schemaId)?.hasItems !== true) {
727
+ continue;
728
+ }
724
729
  if (schema.idProperties.length > 1) {
725
730
  throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key");
726
731
  }
732
+ // An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an
733
+ // identity key under any other name is never filled in: every entity reads back with
734
+ // an undefined key and the change tracker merges them all into one. Corruption, not
735
+ // an error — so refuse the schema up front. A caller-supplied key (default/computed)
736
+ // is stored as an ordinary field and round-trips fine under any name.
737
+ const key = schema.idProperties[0];
738
+ if (key != null && key.isIdentity && key.name !== "_id") {
739
+ throw new Error(`PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` + `'${key.name}' as its identity key, which PouchDB cannot fill in. ` + `Declare the key as: _id: s.string().key().identity()`);
740
+ }
727
741
  }
728
742
  }
729
743
  _bulkPersist(event, done) {
@@ -896,6 +910,9 @@ class PouchDbPlugin {
896
910
  return;
897
911
  }
898
912
  try {
913
+ event.executedQueries.push({
914
+ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query`
915
+ });
899
916
  const translated = translator.translate(response.rows.map((w)=>w.doc));
900
917
  d(Result.success(translated));
901
918
  } catch (e) {
@@ -919,6 +936,9 @@ class PouchDbPlugin {
919
936
  include_docs: true
920
937
  }).then((response)=>{
921
938
  try {
939
+ event.executedQueries.push({
940
+ text: "allDocs({ include_docs: true }): full database scan, no index"
941
+ });
922
942
  const data = response.rows.map((w)=>w.doc);
923
943
  const translated = translator.translate(data);
924
944
  d(Result.success(translated));
@@ -941,6 +961,9 @@ class PouchDbPlugin {
941
961
  }).then((response)=>{
942
962
  const data = response.rows.map((w)=>w.doc);
943
963
  try {
964
+ event.executedQueries.push({
965
+ text: "allDocs({ include_docs: true }): full database scan, no index"
966
+ });
944
967
  const translated = translator.translate(data);
945
968
  d(Result.success(translated));
946
969
  } catch (e) {
@@ -962,6 +985,9 @@ class PouchDbPlugin {
962
985
  }
963
986
  const data = response.rows.map((w)=>w.value);
964
987
  try {
988
+ event.executedQueries.push({
989
+ text: "view query"
990
+ });
965
991
  const translated = translator.translate(data);
966
992
  d(Result.success(translated));
967
993
  } catch (e) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { CompiledSchema, InferType } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n private schema: CompiledSchema<TEntity>;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.schema = query.schema;\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const result: unknown[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const entity: any = data[i];\n\n // design docs can be included in the result, ignore them\n if (\"_id\" in entity && typeof entity._id === \"string\" && entity._id.startsWith(\"_design\")) {\n continue;\n }\n\n try {\n // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected\n result.push(this.schema.deserialize(entity as InferType<TEntity>));\n data[i] = null;\n } catch (e) {\n throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)\n }\n }\n\n return super.translate(result);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\" }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const property = index.properties[0];\n const path = property.getAssignmentPath({ parent: \"doc\" });\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [, schema] of event.schemas) {\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","result","i","length","entity","e","Error","JSON","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","db","documents","done","missing","document","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","property","path","matchingIndex","views","Object","schema","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;;;;;AAAA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;;;;;;;;;;;;;ACAyD;AAEwC;AAG1F,MAAME,0BAAgFD,cAAcA;IAE/F,OAAgC;IAChC,gBAAqD,KAAK;IAElE,YAAYE,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,MAAM,GAAGA,MAAM,MAAM;IAC9B;IAEA,QAAQC,IAAa,EAAE;QACnB,mCAAmC;QACnC,MAAMC,cAAc,IAAI,CAAC,kBAAkB;QAE3C,8DAA8D;QAC9D,OAAOA,YAAYD;IACvB;IAEQ,qBAAiD;QACrD,mCAAmC;QACnC,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM;YAC7B,OAAO,IAAI,CAAC,aAAa;QAC7B;QAEA,mCAAmC;QACnC,MAAME,UAAU,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QACvC,MAAMC,kBAAkBD,QAAQ,MAAM,CAACE,CAAAA,IAAKA,EAAE,MAAM,CAAC,MAAM,KAAK;QAEhE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB,CAACD,iBAAiB;QAE5D,OAAO,IAAI,CAAC,aAAa;IAC7B;IAEQ,iBAAiBD,OAAgD,EAAEG,KAAa,EAA8B;QAClH,0CAA0C;QAC1C,IAAIA,SAASH,QAAQ,MAAM,EAAE;YACzB,OAA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C,MAAM,EAAEjC,QAAQ,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAACI;QAE7C,IAAID,KAAK,KAAK,IAAI,MAAM;YACpB,OAAO;QACX;QAEA,MAAMnF,QAAQmF,KAAK,KAAK,CAACH,SAAS;QAElC,IAAIhF,SAAS,MAAM;YACf,OAAO;QACX;QAEA,OAAO;YACHgF;YACA,YAAY;gBAAC;oBAAEI;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;ACppCgD"}
1
+ {"version":3,"file":"index.js","sources":["webpack://@routier/pouchdb-plugin/webpack/runtime/define_property_getters","webpack://@routier/pouchdb-plugin/webpack/runtime/has_own_property","webpack://@routier/pouchdb-plugin/./src/PouchDbTranslator.ts","webpack://@routier/pouchdb-plugin/./src/PouchDbPlugin.ts","webpack://@routier/pouchdb-plugin/./src/index.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","import { assertIsArray } from \"@routier/core/assertions\";\nimport { Filter, ParamsFilter } from \"@routier/core/expressions\";\nimport { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from \"@routier/core/plugins\";\nimport { CompiledSchema, InferType } from \"@routier/core/schema\";\n\nexport class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {\n\n private schema: CompiledSchema<TEntity>;\n private cachedMatches: ((item: unknown) => boolean) | null = null;\n\n constructor(query: IQuery<TEntity, TShape>) {\n super(query);\n this.schema = query.schema;\n }\n\n matches(item: unknown) {\n // Get or build cached filter chain\n const filterChain = this.resolveFilterChain();\n\n // Execute the chain (no loops, just recursive function calls)\n return filterChain(item);\n }\n\n private resolveFilterChain(): (item: unknown) => boolean {\n // Return cached chain if available\n if (this.cachedMatches !== null) {\n return this.cachedMatches;\n }\n\n // Build and cache the filter chain\n const filters = this.query.options.get(\"filter\");\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n this.cachedMatches = this.buildFilterChain(databaseFilters, 0);\n\n return this.cachedMatches;\n }\n\n private buildFilterChain(filters: QueryCollectionItem<TShape, \"filter\">[], index: number): (item: unknown) => boolean {\n // Base case: no more filters, return true\n if (index >= filters.length) {\n return () => true;\n }\n\n // Get current filter function\n const currentFilter = this.evaluateFilter(filters[index].option);\n\n // Build the rest of the chain\n const nextFilter = this.buildFilterChain(filters, index + 1);\n\n // Return a function that checks current filter and calls next\n return (item: unknown) => {\n if (!currentFilter(item)) {\n return false; // Early termination\n }\n return nextFilter(item); // Recursive call to next filter\n };\n }\n\n private evaluateFilter(filter: QueryOption<TShape, \"filter\">): (item: unknown) => boolean {\n if (filter.value.params == null) {\n const selector = filter.value.filter as Filter<unknown>;\n return (item: unknown) => selector(item) !== false;\n }\n\n const selector = filter.value.filter as ParamsFilter<unknown, {}>;\n const params = filter.value.params;\n return (item: unknown) => selector([item, params]) !== false;\n }\n\n override translate(data: unknown) {\n assertIsArray(data);\n\n const result: unknown[] = [];\n\n for (let i = 0, length = data.length; i < length; i++) {\n const entity: any = data[i];\n\n // design docs can be included in the result, ignore them\n if (\"_id\" in entity && typeof entity._id === \"string\" && entity._id.startsWith(\"_design\")) {\n continue;\n }\n\n try {\n // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected\n result.push(this.schema.deserialize(entity as InferType<TEntity>));\n data[i] = null;\n } catch (e) {\n throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)\n }\n }\n\n return super.translate(result);\n }\n\n}","import PouchDB from 'pouchdb';\nimport { PouchDbTranslator } from './PouchDbTranslator';\nimport { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';\nimport { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';\nimport { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery, ITranslatedValue, joinInPlugin } from '@routier/core/plugins';\nimport { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';\nimport { assertIsNotNull } from '@routier/core/assertions';\nimport { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';\nimport { BulkPersistChanges, BulkPersistResult, ReadonlySchemaCollection, UnknownRecord } from '@routier/core';\n\nconst INDEX_NAME = \"routier_pdb_indexes\"\n\ntype PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {\n queryType?: \"default\" | \"memory-optimized\" | \"experimental\";\n sync?: PouchDB.Replication.SyncOptions & {\n remoteDb: string;\n onChange?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResult<{}>) => void;\n onError?: (schemas: ReadonlySchemaCollection, error?: any) => void;\n onComplete?: (schemas: ReadonlySchemaCollection, event: PouchDB.Replication.SyncResultComplete<{}>) => void;\n onPaused?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n onActive?: (schemas: ReadonlySchemaCollection) => void;\n onDenied?: (schemas: ReadonlySchemaCollection, event?: any) => void;\n auth?: {\n username: string;\n password: string;\n };\n headers?: { [key: string]: string };\n };\n}\n\nexport type PouchDbDesignDoc = {\n _id: string;\n language?: string;\n views?: {\n [viewName: string]: {\n map: string | Function;\n reduce?: string | Function;\n };\n };\n filters?: {\n [filterName: string]: string | Function;\n };\n validate_doc_update?: string | Function;\n options?: Record<string, any>;\n [key: string]: any; // allow other CouchDB features\n}\n\ntype MatchingIndex = {\n viewName: string,\n properties: {\n property: PropertyInfo<any>,\n value: unknown\n }[]\n}\n\nexport class PouchDbPlugin implements IDbPlugin {\n\n private readonly _name: string;\n private readonly _options?: PouchDBPluginOptions;\n\n /**\n * Per INSTANCE, all three of these. They used to be module-level, which made every\n * PouchDbPlugin in the process share one database's state regardless of its name:\n *\n * - the **queue** serialized work across unrelated databases, so a slow save against one\n * database blocked a read against another;\n * - the **index cache** was keyed by nothing at all, so the first database's design\n * document was reported as every database's;\n * - the **sync handle** lived under the literal key `\"sync\"`, so only the FIRST plugin in\n * a process could establish replication — every later one got back the first one's\n * handle, pointed at a different remote.\n *\n * A plugin instance is the natural scope: it owns exactly one database name.\n */\n private readonly queue = new SyncronousQueue();\n private indexCache: PouchDbDesignDoc | null = null;\n private syncHandle: PouchDB.Replication.Sync<{}> | null = null;\n\n /**\n * ONE local database handle for this plugin, shared by every operation and by `sync()`.\n *\n * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing\n * yet another one of its own. Two PouchDB objects over the same name only behave as one\n * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this\n * works in a browser, and the in-memory adapter does not, so under it a live replication\n * never observes the plugin's own writes and the plugin never observes what replication\n * pulls in. Replication and data access were effectively wired to two different databases\n * on any adapter without that broadcast.\n *\n * One handle removes the question, and removes the per-operation construction churn with\n * it. It is closed and cleared by `destroy()`.\n */\n private localDb: PouchDB.Database<any> | null = null;\n\n private database<TEntity>(): PouchDB.Database<TEntity> {\n if (this.localDb == null) {\n const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};\n this.localDb = new PouchDB(this._name, rest);\n }\n\n return this.localDb as PouchDB.Database<TEntity>;\n }\n\n constructor(name: string, options?: PouchDBPluginOptions) {\n this._name = name;\n this._options = options;\n }\n\n /**\n * See `IDbPlugin.databaseName`. The local database name — the same value two contexts\n * opening one PouchDB database supply, so they share subscription channels. Remote sync\n * targets are deliberately not part of it: two local databases replicating to one remote\n * are still two databases.\n */\n get databaseName(): string {\n return this._name;\n }\n\n sync(schemas: ReadonlySchemaCollection) {\n\n assertIsNotNull(this._options?.sync, \"Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor\");\n\n if (this.syncHandle == null) {\n // No placeholder write before the work. The previous shape assigned `{}` first\n // and only replaced it after `sync()` returned, so if constructing either\n // database threw, the cache kept the placeholder forever and every later call\n // returned an empty object cast as a Sync — no replication, no error, no way back\n // without restarting the process.\n // The plugin's own handle, not a second one over the same name: replication has\n // to observe the writes this plugin makes, and on an adapter that does not\n // broadcast changes between instances (the in-memory one, for example) a\n // separate object is a separate database in every way that matters here.\n const localDb = this.database();\n const remoteDb = new PouchDB(this._options.sync.remoteDb);\n\n // Set up sync\n const sync = localDb.sync(remoteDb, {\n ...this._options.sync\n });\n\n if (this._options.sync.onChange) {\n sync.on('change', (e) => this._options.sync.onChange(schemas, e));\n }\n\n if (this._options.sync.onActive) {\n sync.on('active', () => this._options.sync.onActive(schemas));\n }\n\n if (this._options.sync.onComplete) {\n sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));\n }\n\n if (this._options.sync.onDenied) {\n sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));\n }\n\n if (this._options.sync.onError) {\n sync.on('error', (e) => this._options.sync.onError(schemas, e));\n }\n\n if (this._options.sync.onPaused) {\n sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));\n }\n\n // Retained so destroy() can cancel it. An uncancelled sync keeps polling a\n // remote that the caller believes it has finished with, and holds both databases\n // open with it.\n this.syncHandle = sync;\n }\n\n return this.syncHandle;\n }\n\n /**\n * Fills in the `_rev` of any document about to be updated or removed that arrives without\n * one, in a single lookup.\n *\n * PouchDB is the only backend in this repository that needs a revision to change a row, and\n * it used to make that the CALLER's problem: a schema had to declare `_rev` and every\n * entity had to carry the current value. That is this plugin's write protocol leaking into\n * every schema written for it, and it made whole features unusable here — a generated\n * search-index row is built from the document being saved, so it has an id and never a\n * revision, and every edit to an indexed document failed with a conflict whose only\n * detail was `true`.\n *\n * A revision is a fact this database owns, so this is the layer that should look it up.\n * One `allDocs` for every id that needs one, only when at least one does, and never on the\n * path where every entity already carries its own. Nothing above has to know.\n *\n * A missing row resolves to no revision and is left alone: an update to a document that is\n * not there must still fail, and it fails the way it always did.\n */\n private _withRevisions(\n db: PouchDB.Database,\n documents: UnknownRecord[],\n done: (error: unknown | null) => void\n ) {\n const missing = documents\n .filter(document => document._rev == null && document._id != null)\n .map(document => String(document._id));\n\n if (missing.length === 0) {\n done(null);\n return;\n }\n\n db.allDocs({ keys: missing }).then(response => {\n const revisions = new Map<string, string>();\n\n for (const row of response?.rows ?? []) {\n const revision = (row as { value?: { rev?: string, deleted?: boolean } }).value;\n\n if (revision?.rev != null && revision.deleted !== true) {\n revisions.set(String(row.key), revision.rev);\n }\n }\n\n for (const document of documents) {\n\n if (document._rev == null) {\n const revision = revisions.get(String(document._id));\n\n if (revision != null) {\n document._rev = revision;\n }\n }\n }\n\n done(null);\n }).catch(error => done(error));\n }\n\n private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n // Do adds separate. Updates/Removes already have an id that we can reference\n // Default can do the same as updates/removes below since it has an id\n // Check again now to see if we have any identity schema changes\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const updatedDocuments = [...updates].map(w => w.change.entity);\n const errors: any[] = [];\n\n // Tombstones are built here rather than inline so a missing revision can be\n // resolved into them before the write.\n const tombstones = removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true } as UnknownRecord));\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments] as UnknownRecord[], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc && doc.error === true) {\n errors.push(doc); // send back the entire error\n continue;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n\n const remove = removes[removesIndex];\n\n const changesResult = result.resolve(remove.schemaId);\n\n changesResult.removes.push(remove.entity);\n }\n }\n }\n\n if (errors.length > 0) {\n d(Result.error(errors));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = identitySchemaIds.length; i < length; i++) {\n const schemaId = identitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {\n\n if (changes.aggregate.size === 0) {\n done(Result.success())\n return;\n }\n\n // Link each entity to a schema id below so we can easily look up the schema id for an entity\n const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];\n const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];\n const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];\n\n for (const [schemaId, schemaChanges] of changes) {\n\n if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {\n continue;\n }\n\n updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));\n adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));\n removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));\n }\n\n if (updates.length === 0 && removes.length === 0 && adds.length === 0) {\n done(Result.success())\n return;\n }\n\n this._doWork((db, d) => {\n try {\n\n const tombstones = removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true } as UnknownRecord));\n const updatedDocuments = updates.map(x => x.change.entity) as UnknownRecord[];\n\n this._withRevisions(db, [...tombstones, ...updatedDocuments], (revisionError) => {\n\n if (revisionError != null) {\n d(Result.error(revisionError));\n return;\n }\n\n db.bulkDocs([...tombstones, ...updatedDocuments], null, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n for (let i = 0, length = response.length; i < length; i++) {\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n const removesIndex = removes.findIndex(x => x.entity._id === doc.id);\n\n if (removesIndex !== -1) {\n const { schemaId } = removes[removesIndex]\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n\n schemaResult.removes.push(doc as any);\n continue;\n }\n\n const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);\n\n if (updatesIndex !== -1) {\n // Optimistically assume that the update worked as expected\n const update = updates[updatesIndex];\n\n const changesResult = result.resolve(update.schemaId);\n\n // Set the new rev\n (update.change.entity as UnknownRecord)._rev = doc.rev;\n\n changesResult.updates.push(update.change.entity);\n continue;\n }\n\n d(Result.error(new Error(\"Cannot classify resulting doc\")));\n return;\n }\n\n const pipeline = new WorkPipeline();\n\n for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {\n const schemaId = nonIdentitySchemaIds[i];\n const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);\n\n // Skip schemas with no adds\n if (schemaAdds.length === 0) {\n continue;\n }\n\n pipeline.pipe((d) => {\n const schemaResult = result.resolve(schemaId);\n\n assertIsNotNull(schemaResult);\n assertIsNotNull(schemaAdds);\n\n db.bulkDocs([...schemaAdds], null, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return;\n }\n\n // Starts EMPTY and is filled from the ok entries below.\n // Seeding it from every response entry and then pushing each\n // ok id again put every id in twice, so `_bulkGetAdditions`\n // asked for each document twice and the echo carried\n // duplicates into the change tracker.\n const ids: string[] = [];\n\n for (let i = 0, length = response.length; i < length; i++) {\n\n const doc = response[i];\n\n if (\"error\" in doc) {\n\n const reason = doc.reason ?? doc.error;\n\n d(Result.error(reason));\n return;\n }\n\n if (\"id\" in doc && \"ok\" in doc) {\n ids.push(doc.id);\n } else {\n d(Result.error(doc.error));\n return;\n }\n }\n\n this._bulkGetAdditions(ids, (bulkGetResponse) => {\n\n if (bulkGetResponse.ok !== Result.SUCCESS) {\n d(Result.error(bulkGetResponse));\n return;\n }\n\n for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {\n const docs = bulkGetResponse.data.results[i].docs;\n\n if (docs.length === 1) {\n const doc = docs[0];\n\n if (\"ok\" in doc) {\n schemaResult.adds.push(doc.ok as any);\n }\n }\n }\n\n d(Result.success());\n });\n });\n\n });\n }\n\n pipeline.filter((r) => {\n if (r.ok !== Result.SUCCESS) {\n d(r);\n return;\n }\n\n d(Result.success());\n });\n });\n });\n } catch (e) {\n d(Result.error(e));\n }\n }, done);\n }\n\n private _prepareProperties(...properties: PropertyInfo<any>[]) {\n\n properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));\n const paths = properties.map(w => w.getAssignmentPath({ parent: \"doc\" }));\n const viewName = `by_${paths.join(\"_\")}`;\n\n return {\n properties,\n paths,\n viewName\n }\n }\n\n private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {\n\n const indexes = event.operation.schema.getIndexes();\n\n if (indexes.length === 0) {\n done(Result.success(null));\n return;\n }\n\n if (this.indexCache != null) {\n done(Result.success(this.indexCache));\n return; // Already built\n }\n\n const ddoc: PouchDbDesignDoc = {\n _id: `_design/${INDEX_NAME}`,\n views: {}\n }\n\n for (let i = 0, length = indexes.length; i < length; i++) {\n const index = indexes[i];\n const { viewName, paths } = this._prepareProperties(...index.properties);\n\n if (index.properties.length === 1) {\n const property = index.properties[0];\n const path = property.getAssignmentPath({ parent: \"doc\" });\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${path}) {\n emit(${path});\n }\n }`\n }\n continue;\n }\n\n ddoc.views[viewName] = {\n map: `function(doc) {\n if (${paths.join(\" && \")}) {\n emit([${paths.join(\",\")}]);\n }\n }`\n }\n }\n\n this._doWork((db, d) => {\n // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below\n db.allDocs({\n startkey: '_design/',\n endkey: '_design0',\n include_docs: true\n }).then(response => {\n\n // if we have no indexes, let's create it\n if (response.rows.length === 0) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);\n\n // make sure we have the correct index created\n if (matchingIndex == null) {\n db.put(ddoc as UnknownRecord, {}, (e) => {\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n return;\n }\n\n assertIsNotNull(ddoc.views);\n assertIsNotNull(matchingIndex.doc);\n\n const views = Object.keys(ddoc.views)\n\n // make sure all of the views are in the document, if not update it\n if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {\n\n // need to get the rev\n db.get(ddoc._id, {}, (e, result) => {\n\n if (e != null) {\n d(Result.error(e));\n return;\n }\n\n (result as any).views = ddoc.views\n\n db.put(result as any, {}, (e) => {\n\n if (e) {\n d(Result.error(e));\n return;\n }\n\n this.indexCache = ddoc;\n\n d(Result.success(ddoc));\n });\n })\n return;\n }\n\n d(Result.success(ddoc));\n }).catch(e => {\n d(Result.error(e));\n });\n }, done)\n }\n\n // id should be a string here because this is only run on identity inserts\n private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {\n\n if (ids.length === 0) {\n done(Result.success({ results: [] }));\n return;\n }\n\n this._doWork((db, d) => {\n db.bulkGet<TEntity>({\n docs: ids.map(w => ({ id: w as string }))\n }, (error, response) => {\n\n if (error) {\n d(Result.error(error));\n return\n }\n\n d(Result.success(response));\n });\n }, done);\n }\n\n private _validateSchemas(event: DbPluginBulkPersistEvent) {\n for (const [schemaId, schema] of event.schemas) {\n\n // Only schemas this persist actually writes: a store may declare other collections,\n // and an unused bad one should not block saves to the good ones.\n if (event.operation.get(schemaId)?.hasItems !== true) {\n continue;\n }\n\n if (schema.idProperties.length > 1) {\n throw new Error(\"PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key\")\n }\n\n // An identity key is generated by PouchDB as '_id' and echoed back as '_id', so an\n // identity key under any other name is never filled in: every entity reads back with\n // an undefined key and the change tracker merges them all into one. Corruption, not\n // an error — so refuse the schema up front. A caller-supplied key (default/computed)\n // is stored as an ordinary field and round-trips fine under any name.\n const key = schema.idProperties[0];\n if (key != null && key.isIdentity && key.name !== \"_id\") {\n throw new Error(\n `PouchDB generates identity keys as '_id'. The schema for collection '${schema.collectionName}' uses ` +\n `'${key.name}' as its identity key, which PouchDB cannot fill in. ` +\n `Declare the key as: _id: s.string().key().identity()`\n );\n }\n }\n }\n\n private _bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n this._validateSchemas(event);\n\n const result = event.operation.toResult();\n const identitySchemaIds: SchemaId[] = [];\n const defaultSchemaIds: SchemaId[] = [];\n\n for (const [schemaId, schema] of event.schemas) {\n\n if (schema.hasIdentityKeys) {\n identitySchemaIds.push(schemaId);\n continue;\n }\n\n defaultSchemaIds.push(schemaId);\n }\n\n this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {\n\n if (identityResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, identityResult.error))\n return;\n }\n\n this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {\n\n if (defaultResult.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, defaultResult.error))\n return;\n }\n\n done(PluginEventResult.success(event.id, result))\n });\n\n });\n }\n\n private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {\n const db = this.database<TEntity>();\n\n work(db, (result) => {\n\n // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`\n // fired synchronously here and again from the close callback. A doubled callback\n // resolves a settled promise silently, but it also drives every pipeline stage\n // downstream twice — see known-defects #3's \"calls done exactly once\".\n if (shouldClose) {\n // The handle is shared, so closing it has to clear the cache too — the next\n // operation must open a fresh one rather than reuse a closed database.\n this.localDb = null;\n db.close(() => done(result));\n return;\n }\n\n done(result);\n })\n }\n\n destroy(_event: DbPluginEvent, done: (error?: any) => void): void {\n // Replication first. A live sync holds both the local and the remote database open\n // and keeps polling; destroying the local one underneath it leaves a replication\n // running against a database that no longer exists, which surfaces later as errors\n // from a plugin the caller believes it has finished with.\n if (this.syncHandle != null) {\n try {\n this.syncHandle.cancel();\n } catch {\n // An already-finished sync throws on cancel. Destroy's goal is that no\n // replication is running, and that is satisfied either way.\n }\n\n this.syncHandle = null;\n }\n\n // A destroyed database must not keep serving its cached design document to a plugin\n // that outlives it.\n this.indexCache = null;\n\n // `shouldClose: true`, so the handle this work opened is closed rather than left to\n // the garbage collector. It was false, which is what left destroy leaking the very\n // resource it was called to release.\n this._doWork((w, d) => {\n w.destroy(null, (e) => {\n if (e) {\n d(Result.error(e))\n return;\n }\n\n d(Result.success());\n });\n }, done, true);\n }\n\n\n bulkPersist(\n event: DbPluginBulkPersistEvent,\n done: PluginEventCallbackPartialResult<BulkPersistResult>) {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {\n d();\n done(r)\n })\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n\n const unitOfWork: SyncronousUnitOfWork = (d) => {\n const settle = (r: Parameters<typeof done>[0]) => {\n d();\n done(r);\n };\n\n // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of\n // work already holds the queue, so routing them through `query` would make them wait on\n // itself and the plugin would never answer. They are still serialized against every\n // other query, because this slot is held for both.\n if (event.operation.options.has(\"join\")) {\n joinInPlugin(event, (e, cb) => this._query(e, cb), settle as never);\n return;\n }\n\n this._query<TRoot, TShape>(event, settle);\n };\n\n this.queue.enqueue(unitOfWork.bind(this));\n }\n\n protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {\n done(null);\n }\n\n extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {\n // Recursively search for a comparator expression that matches the property\n if (expression.type === \"comparator\" && (expression as ComparatorExpression).comparator === \"equals\") {\n // Check left side is property, right side is value\n if (expression.left && expression.left.type === \"property\" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === \"value\") {\n return (expression.right as any).value;\n }\n // Or right side is property, left side is value\n if (expression.right && expression.right.type === \"property\" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === \"value\") {\n return (expression.left as any).value;\n }\n }\n // Recursively check left and right\n if (expression.left) {\n const left = this.extractEqualityValueForProperty(expression.left, prop);\n if (left !== undefined) return left;\n }\n if (expression.right) {\n const right = this.extractEqualityValueForProperty(expression.right, prop);\n if (right !== undefined) return right;\n }\n return undefined;\n }\n\n private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {\n const queryProperties = getProperties(expression);\n\n const { viewName } = this._prepareProperties(...queryProperties);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n const properties: MatchingIndex[\"properties\"] = [];\n\n for (const property of queryProperties) {\n const value = this.extractEqualityValueForProperty(expression, property);\n\n if (value === undefined) {\n return null\n }\n\n properties.push({\n property,\n value\n });\n }\n\n return {\n viewName,\n properties\n };\n }\n\n private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n const options: PouchDB.Query.Options<any, any> = {\n include_docs: true,\n };\n\n const values = matchingIndex.properties.map(x => x.value);\n\n if (values.some(x => x == null) == false) {\n\n if (values.length === 1) {\n options.key = values[0];\n } else {\n options.keys = values;\n }\n }\n\n w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n try {\n event.executedQueries.push({ text: `${INDEX_NAME}/${matchingIndex.viewName}: indexed view query` });\n\n const translated = translator.translate(response.rows.map(w => w.doc));\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n }, done);\n }\n\n private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const filters = event.operation.options.get(\"filter\")\n if (filters.length === 0) {\n this._queryWithNoFilters(event, done);\n return;\n }\n\n this._queryWithFilters(event, done);\n }\n\n private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n w.allDocs({\n include_docs: true\n }).then(response => {\n\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const data = response.rows.map(w => w.doc);\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n }, done);\n }\n\n private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<ITranslatedValue<TShape>>) {\n const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);\n this._doWork((w, d) => {\n\n if (this._name.startsWith(\"http\")) {\n // Cannot query remote databases using translator.matches, fallback to alldocs\n // Does not throw, will fail on the remote server\n w.allDocs({\n include_docs: true\n }).then(response => {\n const data = response.rows.map(w => w.doc);\n try {\n event.executedQueries.push({ text: \"allDocs({ include_docs: true }): full database scan, no index\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n }).catch(error => {\n d(Result.error(error));\n });\n return;\n }\n\n w.query<{}, any>((doc, emit) => {\n if (typeof doc === \"object\" && \"_id\" in doc && translator.matches(doc)) {\n emit(doc._id, doc);\n }\n }, (error, response) => {\n\n if (error != null) {\n d(Result.error(error));\n return;\n }\n\n const data = response.rows.map(w => w.value);\n\n try {\n event.executedQueries.push({ text: \"view query\" });\n\n const translated = translator.translate(data);\n d(Result.success(translated));\n } catch (e) {\n d(Result.error(e));\n }\n });\n\n }, done);\n }\n\n private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<ITranslatedValue<TShape>>): void {\n this.resolveIndexes(event, (r) => {\n if (r.ok !== Result.SUCCESS) {\n done(PluginEventResult.error(event.id, r.error))\n return;\n }\n\n const ddoc = r.data;\n\n if (ddoc == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);\n\n if (mapMatchingIndex != null) {\n this._queryIndex(event, mapMatchingIndex, done);\n return;\n }\n\n const expression = this._getExpressionFromQuery(event);\n\n if (Expression.isEmpty(expression)) {\n this._queryNoIndex(event, done);\n return;\n }\n\n const matchingIndex = this._findMatchingIndex(ddoc, expression);\n\n if (matchingIndex == null) {\n this._queryNoIndex(event, done);\n return;\n }\n\n this._queryIndex(event, matchingIndex, done);\n });\n }\n\n private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {\n const filters = event.operation.options.get(\"filter\");\n\n const databaseFilters = filters.filter(x => x.option.target === \"database\");\n\n if (databaseFilters.length === 0) {\n return Expression.EMPTY;\n }\n\n const expressions = databaseFilters.map(x => x.option.value.expression);\n\n return combineExpressions(...expressions);\n }\n\n private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {\n const map = event.operation.options.getLast(\"map\");\n const filters = event.operation.options.get(\"filter\");\n\n // we only want to look at the index if there are no filters\n if (filters.length > 0) {\n return null;\n }\n\n if (map == null || map.target !== \"database\") {\n return null;\n }\n\n if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {\n return null;\n }\n\n const property = map.value.fields[0].property;\n\n const { viewName } = this._prepareProperties(property);\n\n if (ddoc.views == null) {\n return null;\n }\n\n const index = ddoc.views[viewName];\n\n if (index == null) {\n return null;\n }\n\n return {\n viewName,\n properties: [{ property, value: null }]\n }\n }\n}","export { PouchDbPlugin } from './PouchDbPlugin';"],"names":["assertIsArray","JsonTranslator","PouchDbTranslator","query","item","filterChain","filters","databaseFilters","x","index","currentFilter","nextFilter","filter","selector","params","data","result","i","length","entity","e","Error","JSON","PouchDB","SyncronousQueue","WorkPipeline","joinInPlugin","PluginEventResult","Result","assertIsNotNull","combineExpressions","Expression","getProperties","INDEX_NAME","PouchDbPlugin","_sync","_queryType","rest","name","options","schemas","localDb","remoteDb","sync","db","documents","done","missing","document","String","response","revisions","Map","row","revision","error","identitySchemaIds","changes","updates","adds","removes","schemaId","schemaChanges","d","updatedDocuments","w","errors","tombstones","revisionError","doc","updatesIndex","update","changesResult","removesIndex","remove","pipeline","schemaAdds","schemaResult","ids","reason","bulkGetResponse","docs","r","nonIdentitySchemaIds","properties","a","b","undefined","paths","viewName","event","indexes","ddoc","property","path","matchingIndex","views","Object","schema","key","defaultSchemaIds","identityResult","defaultResult","work","shouldClose","_event","unitOfWork","settle","cb","_","__","expression","prop","left","right","queryProperties","value","translator","values","translated","emit","mapMatchingIndex","expressions","map"],"mappings":";;;;;;;;;;;AAAA;AACA;AACA;AACA,kDAAkD,wCAAwC;AAC1F;AACA;AACA,E;;;;ACNA,wF;;;;;;;;;;;;;;;;ACAyD;AAEwC;AAG1F,MAAME,0BAAgFD,cAAcA;IAE/F,OAAgC;IAChC,gBAAqD,KAAK;IAElE,YAAYE,KAA8B,CAAE;QACxC,KAAK,CAACA;QACN,IAAI,CAAC,MAAM,GAAGA,MAAM,MAAM;IAC9B;IAEA,QAAQC,IAAa,EAAE;QACnB,mCAAmC;QACnC,MAAMC,cAAc,IAAI,CAAC,kBAAkB;QAE3C,8DAA8D;QAC9D,OAAOA,YAAYD;IACvB;IAEQ,qBAAiD;QACrD,mCAAmC;QACnC,IAAI,IAAI,CAAC,aAAa,KAAK,MAAM;YAC7B,OAAO,IAAI,CAAC,aAAa;QAC7B;QAEA,mCAAmC;QACnC,MAAME,UAAU,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QACvC,MAAMC,kBAAkBD,QAAQ,MAAM,CAACE,CAAAA,IAAKA,EAAE,MAAM,CAAC,MAAM,KAAK;QAEhE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,gBAAgB,CAACD,iBAAiB;QAE5D,OAAO,IAAI,CAAC,aAAa;IAC7B;IAEQ,iBAAiBD,OAAgD,EAAEG,KAAa,EAA8B;QAClH,0CAA0C;QAC1C,IAAIA,SAASH,QAAQ,MAAM,EAAE;YACzB,OAAO,IAAM;QACjB;QAEA,8BAA8B;QAC9B,MAAMI,gBAAgB,IAAI,CAAC,cAAc,CAACJ,OAAO,CAACG,MAAM,CAAC,MAAM;QAE/D,8BAA8B;QAC9B,MAAME,aAAa,IAAI,CAAC,gBAAgB,CA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AKA,EAAE,MAAM,CAAC,KAAK,CAAC,UAAU;QAEtE,OAAOsB,kBAAkBA,IAAI4F;IACjC;IAEQ,wBAAoD9B,IAAsB,EAAEF,KAA0C,EAAwB;QAClJ,MAAMiC,MAAMjC,MAAM,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC;QAC5C,MAAMpF,UAAUoF,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC;QAE5C,4DAA4D;QAC5D,IAAIpF,QAAQ,MAAM,GAAG,GAAG;YACpB,OAAO;QACX;QAEA,IAAIqH,OAAO,QAAQA,IAAI,MAAM,KAAK,YAAY;YAC1C,OAAO;QACX;QAEA,IAAIA,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,KAAK,KAAKA,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ,IAAI,MAAM;YACvE,OAAO;QACX;QAEA,MAAM9B,WAAW8B,IAAI,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,QAAQ;QAE7C,MAAM,EAAElC,QAAQ,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAACI;QAE7C,IAAID,KAAK,KAAK,IAAI,MAAM;YACpB,OAAO;QACX;QAEA,MAAMnF,QAAQmF,KAAK,KAAK,CAACH,SAAS;QAElC,IAAIhF,SAAS,MAAM;YACf,OAAO;QACX;QAEA,OAAO;YACHgF;YACA,YAAY;gBAAC;oBAAEI;oBAAU,OAAO;gBAAK;aAAE;QAC3C;IACJ;AACJ;;;ACjrCgD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routier/pouchdb-plugin",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "main": "./dist/index.cjs",
5
5
  "types": "./dist/index.d.ts",
6
6
  "source": "./src/index.ts",
@@ -43,16 +43,16 @@
43
43
  ],
44
44
  "description": "PouchDB plugin for routier",
45
45
  "dependencies": {
46
- "events": "^3.3.0",
47
- "pouchdb": "^9.0.0"
46
+ "events": "^3.3.0"
48
47
  },
49
48
  "peerDependencies": {
50
- "@routier/core": ">=0.3.0"
49
+ "@routier/core": ">=0.4.0",
50
+ "pouchdb": ">=9.0.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@faker-js/faker": "^10.0.0",
54
- "@routier/core": "^0.3.0",
55
- "@routier/datastore": "^0.3.0",
54
+ "@routier/core": "^0.5.0",
55
+ "@routier/datastore": "^0.4.0",
56
56
  "@routier/memory-plugin": "file://../memory",
57
57
  "@routier/test-utils": "^0.3.0",
58
58
  "@rspack/cli": "^1.1.8",