@routier/pouchdb-plugin 0.1.0-rc.0 → 0.3.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/dist/index.cjs ADDED
@@ -0,0 +1,1072 @@
1
+ (() => {
2
+ "use strict";
3
+ // The require scope
4
+ var __webpack_require__ = {};
5
+
6
+ // webpack/runtime/compat_get_default_export
7
+ (() => {
8
+ // getDefaultExport function for compatibility with non-ESM modules
9
+ __webpack_require__.n = (module) => {
10
+ var getter = module && module.__esModule ?
11
+ () => (module['default']) :
12
+ () => (module);
13
+ __webpack_require__.d(getter, { a: getter });
14
+ return getter;
15
+ };
16
+
17
+ })();
18
+ // webpack/runtime/define_property_getters
19
+ (() => {
20
+ __webpack_require__.d = (exports, definition) => {
21
+ for(var key in definition) {
22
+ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
23
+ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
24
+ }
25
+ }
26
+ };
27
+ })();
28
+ // webpack/runtime/has_own_property
29
+ (() => {
30
+ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
31
+ })();
32
+ // webpack/runtime/make_namespace_object
33
+ (() => {
34
+ // define __esModule on exports
35
+ __webpack_require__.r = (exports) => {
36
+ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
37
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
38
+ }
39
+ Object.defineProperty(exports, '__esModule', { value: true });
40
+ };
41
+ })();
42
+ var __webpack_exports__ = {};
43
+ // ESM COMPAT FLAG
44
+ __webpack_require__.r(__webpack_exports__);
45
+
46
+ // EXPORTS
47
+ __webpack_require__.d(__webpack_exports__, {
48
+ PouchDbPlugin: () => (/* reexport */ PouchDbPlugin)
49
+ });
50
+
51
+ ;// CONCATENATED MODULE: external "pouchdb"
52
+ const external_pouchdb_namespaceObject = require("pouchdb");
53
+ var external_pouchdb_default = /*#__PURE__*/__webpack_require__.n(external_pouchdb_namespaceObject);
54
+ ;// CONCATENATED MODULE: external "@routier/core/assertions"
55
+ const assertions_namespaceObject = require("@routier/core/assertions");
56
+ ;// CONCATENATED MODULE: external "@routier/core/plugins"
57
+ const plugins_namespaceObject = require("@routier/core/plugins");
58
+ ;// CONCATENATED MODULE: ./src/PouchDbTranslator.ts
59
+
60
+
61
+ class PouchDbTranslator extends plugins_namespaceObject.JsonTranslator {
62
+ schema;
63
+ cachedMatches = null;
64
+ constructor(query){
65
+ super(query);
66
+ this.schema = query.schema;
67
+ }
68
+ matches(item) {
69
+ // Get or build cached filter chain
70
+ const filterChain = this.resolveFilterChain();
71
+ // Execute the chain (no loops, just recursive function calls)
72
+ return filterChain(item);
73
+ }
74
+ resolveFilterChain() {
75
+ // Return cached chain if available
76
+ if (this.cachedMatches !== null) {
77
+ return this.cachedMatches;
78
+ }
79
+ // Build and cache the filter chain
80
+ const filters = this.query.options.get("filter");
81
+ const databaseFilters = filters.filter((x)=>x.option.target === "database");
82
+ this.cachedMatches = this.buildFilterChain(databaseFilters, 0);
83
+ return this.cachedMatches;
84
+ }
85
+ buildFilterChain(filters, index) {
86
+ // Base case: no more filters, return true
87
+ if (index >= filters.length) {
88
+ return ()=>true;
89
+ }
90
+ // Get current filter function
91
+ const currentFilter = this.evaluateFilter(filters[index].option);
92
+ // Build the rest of the chain
93
+ const nextFilter = this.buildFilterChain(filters, index + 1);
94
+ // Return a function that checks current filter and calls next
95
+ return (item)=>{
96
+ if (!currentFilter(item)) {
97
+ return false; // Early termination
98
+ }
99
+ return nextFilter(item); // Recursive call to next filter
100
+ };
101
+ }
102
+ evaluateFilter(filter) {
103
+ if (filter.value.params == null) {
104
+ const selector = filter.value.filter;
105
+ return (item)=>selector(item) !== false;
106
+ }
107
+ const selector = filter.value.filter;
108
+ const params = filter.value.params;
109
+ return (item)=>selector([
110
+ item,
111
+ params
112
+ ]) !== false;
113
+ }
114
+ translate(data) {
115
+ (0,assertions_namespaceObject.assertIsArray)(data);
116
+ const result = [];
117
+ for(let i = 0, length = data.length; i < length; i++){
118
+ const entity = data[i];
119
+ // design docs can be included in the result, ignore them
120
+ if ("_id" in entity && typeof entity._id === "string" && entity._id.startsWith("_design")) {
121
+ continue;
122
+ }
123
+ try {
124
+ // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected
125
+ result.push(this.schema.deserialize(entity));
126
+ data[i] = null;
127
+ } catch (e) {
128
+ throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`);
129
+ }
130
+ }
131
+ return super.translate(result);
132
+ }
133
+ }
134
+
135
+ ;// CONCATENATED MODULE: external "@routier/core/pipeline"
136
+ const pipeline_namespaceObject = require("@routier/core/pipeline");
137
+ ;// CONCATENATED MODULE: external "@routier/core/results"
138
+ const results_namespaceObject = require("@routier/core/results");
139
+ ;// CONCATENATED MODULE: external "@routier/core/expressions"
140
+ const expressions_namespaceObject = require("@routier/core/expressions");
141
+ ;// CONCATENATED MODULE: ./src/PouchDbPlugin.ts
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+ const INDEX_NAME = "routier_pdb_indexes";
150
+ class PouchDbPlugin {
151
+ _name;
152
+ _options;
153
+ /**
154
+ * Per INSTANCE, all three of these. They used to be module-level, which made every
155
+ * PouchDbPlugin in the process share one database's state regardless of its name:
156
+ *
157
+ * - the **queue** serialized work across unrelated databases, so a slow save against one
158
+ * database blocked a read against another;
159
+ * - the **index cache** was keyed by nothing at all, so the first database's design
160
+ * document was reported as every database's;
161
+ * - the **sync handle** lived under the literal key `"sync"`, so only the FIRST plugin in
162
+ * a process could establish replication — every later one got back the first one's
163
+ * handle, pointed at a different remote.
164
+ *
165
+ * A plugin instance is the natural scope: it owns exactly one database name.
166
+ */ queue = new pipeline_namespaceObject.SyncronousQueue();
167
+ indexCache = null;
168
+ syncHandle = null;
169
+ /**
170
+ * ONE local database handle for this plugin, shared by every operation and by `sync()`.
171
+ *
172
+ * This used to be a fresh `new PouchDB(name)` per operation, with `sync()` constructing
173
+ * yet another one of its own. Two PouchDB objects over the same name only behave as one
174
+ * database when the ADAPTER broadcasts changes between them: IndexedDB does, so this
175
+ * works in a browser, and the in-memory adapter does not, so under it a live replication
176
+ * never observes the plugin's own writes and the plugin never observes what replication
177
+ * pulls in. Replication and data access were effectively wired to two different databases
178
+ * on any adapter without that broadcast.
179
+ *
180
+ * One handle removes the question, and removes the per-operation construction churn with
181
+ * it. It is closed and cleared by `destroy()`.
182
+ */ localDb = null;
183
+ database() {
184
+ if (this.localDb == null) {
185
+ const { sync: _sync, queryType: _queryType, ...rest } = this._options ?? {};
186
+ this.localDb = new (external_pouchdb_default())(this._name, rest);
187
+ }
188
+ return this.localDb;
189
+ }
190
+ constructor(name, options){
191
+ this._name = name;
192
+ this._options = options;
193
+ }
194
+ /**
195
+ * See `IDbPlugin.databaseName`. The local database name — the same value two contexts
196
+ * opening one PouchDB database supply, so they share subscription channels. Remote sync
197
+ * targets are deliberately not part of it: two local databases replicating to one remote
198
+ * are still two databases.
199
+ */ get databaseName() {
200
+ return this._name;
201
+ }
202
+ sync(schemas) {
203
+ (0,assertions_namespaceObject.assertIsNotNull)(this._options?.sync, "Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor");
204
+ if (this.syncHandle == null) {
205
+ // No placeholder write before the work. The previous shape assigned `{}` first
206
+ // and only replaced it after `sync()` returned, so if constructing either
207
+ // database threw, the cache kept the placeholder forever and every later call
208
+ // returned an empty object cast as a Sync — no replication, no error, no way back
209
+ // without restarting the process.
210
+ // The plugin's own handle, not a second one over the same name: replication has
211
+ // to observe the writes this plugin makes, and on an adapter that does not
212
+ // broadcast changes between instances (the in-memory one, for example) a
213
+ // separate object is a separate database in every way that matters here.
214
+ const localDb = this.database();
215
+ const remoteDb = new (external_pouchdb_default())(this._options.sync.remoteDb);
216
+ // Set up sync
217
+ const sync = localDb.sync(remoteDb, {
218
+ ...this._options.sync
219
+ });
220
+ if (this._options.sync.onChange) {
221
+ sync.on('change', (e)=>this._options.sync.onChange(schemas, e));
222
+ }
223
+ if (this._options.sync.onActive) {
224
+ sync.on('active', ()=>this._options.sync.onActive(schemas));
225
+ }
226
+ if (this._options.sync.onComplete) {
227
+ sync.on('complete', (e)=>this._options.sync.onComplete(schemas, e));
228
+ }
229
+ if (this._options.sync.onDenied) {
230
+ sync.on('denied', (e)=>this._options.sync.onDenied(schemas, e));
231
+ }
232
+ if (this._options.sync.onError) {
233
+ sync.on('error', (e)=>this._options.sync.onError(schemas, e));
234
+ }
235
+ if (this._options.sync.onPaused) {
236
+ sync.on('paused', (e)=>this._options.sync.onPaused(schemas, e));
237
+ }
238
+ // Retained so destroy() can cancel it. An uncancelled sync keeps polling a
239
+ // remote that the caller believes it has finished with, and holds both databases
240
+ // open with it.
241
+ this.syncHandle = sync;
242
+ }
243
+ return this.syncHandle;
244
+ }
245
+ /**
246
+ * Fills in the `_rev` of any document about to be updated or removed that arrives without
247
+ * one, in a single lookup.
248
+ *
249
+ * PouchDB is the only backend in this repository that needs a revision to change a row, and
250
+ * it used to make that the CALLER's problem: a schema had to declare `_rev` and every
251
+ * entity had to carry the current value. That is this plugin's write protocol leaking into
252
+ * every schema written for it, and it made whole features unusable here — a generated
253
+ * search-index row is built from the document being saved, so it has an id and never a
254
+ * revision, and every edit to an indexed document failed with a conflict whose only
255
+ * detail was `true`.
256
+ *
257
+ * A revision is a fact this database owns, so this is the layer that should look it up.
258
+ * One `allDocs` for every id that needs one, only when at least one does, and never on the
259
+ * path where every entity already carries its own. Nothing above has to know.
260
+ *
261
+ * A missing row resolves to no revision and is left alone: an update to a document that is
262
+ * not there must still fail, and it fails the way it always did.
263
+ */ _withRevisions(db, documents, done) {
264
+ const missing = documents.filter((document)=>document._rev == null && document._id != null).map((document)=>String(document._id));
265
+ if (missing.length === 0) {
266
+ done(null);
267
+ return;
268
+ }
269
+ db.allDocs({
270
+ keys: missing
271
+ }).then((response)=>{
272
+ const revisions = new Map();
273
+ for (const row of response?.rows ?? []){
274
+ const revision = row.value;
275
+ if (revision?.rev != null && revision.deleted !== true) {
276
+ revisions.set(String(row.key), revision.rev);
277
+ }
278
+ }
279
+ for (const document of documents){
280
+ if (document._rev == null) {
281
+ const revision = revisions.get(String(document._id));
282
+ if (revision != null) {
283
+ document._rev = revision;
284
+ }
285
+ }
286
+ }
287
+ done(null);
288
+ }).catch((error)=>done(error));
289
+ }
290
+ _identityBulkOperations(identitySchemaIds, changes, result, done) {
291
+ if (changes.aggregate.size === 0) {
292
+ done(results_namespaceObject.Result.success());
293
+ return;
294
+ }
295
+ // Link each entity to a schema id below so we can easily look up the schema id for an entity
296
+ const updates = [];
297
+ const adds = [];
298
+ const removes = [];
299
+ for (const [schemaId, schemaChanges] of changes){
300
+ if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {
301
+ continue;
302
+ }
303
+ updates.push(...schemaChanges.updates.map((x)=>({
304
+ change: x,
305
+ schemaId
306
+ })));
307
+ adds.push(...schemaChanges.adds.map((x)=>({
308
+ entity: x,
309
+ schemaId
310
+ })));
311
+ removes.push(...schemaChanges.removes.map((x)=>({
312
+ entity: x,
313
+ schemaId
314
+ })));
315
+ }
316
+ // Do adds separate. Updates/Removes already have an id that we can reference
317
+ // Default can do the same as updates/removes below since it has an id
318
+ // Check again now to see if we have any identity schema changes
319
+ if (updates.length === 0 && removes.length === 0 && adds.length === 0) {
320
+ done(results_namespaceObject.Result.success());
321
+ return;
322
+ }
323
+ this._doWork((db, d)=>{
324
+ try {
325
+ const updatedDocuments = [
326
+ ...updates
327
+ ].map((w)=>w.change.entity);
328
+ const errors = [];
329
+ // Tombstones are built here rather than inline so a missing revision can be
330
+ // resolved into them before the write.
331
+ const tombstones = removes.map((w)=>({
332
+ _id: w.entity._id,
333
+ _rev: w.entity._rev,
334
+ _deleted: true
335
+ }));
336
+ this._withRevisions(db, [
337
+ ...tombstones,
338
+ ...updatedDocuments
339
+ ], (revisionError)=>{
340
+ if (revisionError != null) {
341
+ d(results_namespaceObject.Result.error(revisionError));
342
+ return;
343
+ }
344
+ db.bulkDocs([
345
+ ...tombstones,
346
+ ...updatedDocuments
347
+ ], null, (error, response)=>{
348
+ if (error) {
349
+ d(results_namespaceObject.Result.error(error));
350
+ return;
351
+ }
352
+ for(let i = 0, length = response.length; i < length; i++){
353
+ const doc = response[i];
354
+ if ("error" in doc && doc.error === true) {
355
+ errors.push(doc); // send back the entire error
356
+ continue;
357
+ }
358
+ if ("id" in doc && "ok" in doc) {
359
+ const updatesIndex = updates.findIndex((x)=>x.change.entity._id === doc.id);
360
+ if (updatesIndex !== -1) {
361
+ // Optimistically assume that the update worked as expected
362
+ const update = updates[updatesIndex];
363
+ const changesResult = result.resolve(update.schemaId);
364
+ // Set the new rev
365
+ update.change.entity._rev = doc.rev;
366
+ changesResult.updates.push(update.change.entity);
367
+ continue;
368
+ }
369
+ const removesIndex = removes.findIndex((x)=>x.entity._id === doc.id);
370
+ if (removesIndex !== -1) {
371
+ const remove = removes[removesIndex];
372
+ const changesResult = result.resolve(remove.schemaId);
373
+ changesResult.removes.push(remove.entity);
374
+ }
375
+ }
376
+ }
377
+ if (errors.length > 0) {
378
+ d(results_namespaceObject.Result.error(errors));
379
+ return;
380
+ }
381
+ const pipeline = new pipeline_namespaceObject.WorkPipeline();
382
+ for(let i = 0, length = identitySchemaIds.length; i < length; i++){
383
+ const schemaId = identitySchemaIds[i];
384
+ const schemaAdds = adds.filter((x)=>x.schemaId === schemaId).map((x)=>x.entity);
385
+ // Skip schemas with no adds
386
+ if (schemaAdds.length === 0) {
387
+ continue;
388
+ }
389
+ pipeline.pipe((d)=>{
390
+ const schemaResult = result.resolve(schemaId);
391
+ (0,assertions_namespaceObject.assertIsNotNull)(schemaResult);
392
+ (0,assertions_namespaceObject.assertIsNotNull)(schemaAdds);
393
+ db.bulkDocs([
394
+ ...schemaAdds
395
+ ], null, (error, response)=>{
396
+ if (error) {
397
+ d(results_namespaceObject.Result.error(error));
398
+ return;
399
+ }
400
+ // Starts EMPTY and is filled from the ok entries below.
401
+ // Seeding it from every response entry and then pushing each
402
+ // ok id again put every id in twice, so `_bulkGetAdditions`
403
+ // asked for each document twice and the echo carried
404
+ // duplicates into the change tracker.
405
+ const ids = [];
406
+ for(let i = 0, length = response.length; i < length; i++){
407
+ const doc = response[i];
408
+ if ("error" in doc) {
409
+ const reason = doc.reason ?? doc.error;
410
+ d(results_namespaceObject.Result.error(reason));
411
+ return;
412
+ }
413
+ if ("id" in doc && "ok" in doc) {
414
+ ids.push(doc.id);
415
+ } else {
416
+ d(results_namespaceObject.Result.error(doc.error));
417
+ return;
418
+ }
419
+ }
420
+ this._bulkGetAdditions(ids, (bulkGetResponse)=>{
421
+ if (bulkGetResponse.ok !== results_namespaceObject.Result.SUCCESS) {
422
+ d(results_namespaceObject.Result.error(bulkGetResponse));
423
+ return;
424
+ }
425
+ for(let i = 0, length = bulkGetResponse.data.results.length; i < length; i++){
426
+ const docs = bulkGetResponse.data.results[i].docs;
427
+ if (docs.length === 1) {
428
+ const doc = docs[0];
429
+ if ("ok" in doc) {
430
+ schemaResult.adds.push(doc.ok);
431
+ }
432
+ }
433
+ }
434
+ d(results_namespaceObject.Result.success());
435
+ });
436
+ });
437
+ });
438
+ }
439
+ pipeline.filter((r)=>{
440
+ if (r.ok !== results_namespaceObject.Result.SUCCESS) {
441
+ d(r);
442
+ return;
443
+ }
444
+ d(results_namespaceObject.Result.success());
445
+ });
446
+ });
447
+ });
448
+ } catch (e) {
449
+ d(results_namespaceObject.Result.error(e));
450
+ }
451
+ }, done);
452
+ }
453
+ _defaultBulkOperations(nonIdentitySchemaIds, changes, result, done) {
454
+ if (changes.aggregate.size === 0) {
455
+ done(results_namespaceObject.Result.success());
456
+ return;
457
+ }
458
+ // Link each entity to a schema id below so we can easily look up the schema id for an entity
459
+ const updates = [];
460
+ const adds = [];
461
+ const removes = [];
462
+ for (const [schemaId, schemaChanges] of changes){
463
+ if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {
464
+ continue;
465
+ }
466
+ updates.push(...schemaChanges.updates.map((x)=>({
467
+ change: x,
468
+ schemaId
469
+ })));
470
+ adds.push(...schemaChanges.adds.map((x)=>({
471
+ entity: x,
472
+ schemaId
473
+ })));
474
+ removes.push(...schemaChanges.removes.map((x)=>({
475
+ entity: x,
476
+ schemaId
477
+ })));
478
+ }
479
+ if (updates.length === 0 && removes.length === 0 && adds.length === 0) {
480
+ done(results_namespaceObject.Result.success());
481
+ return;
482
+ }
483
+ this._doWork((db, d)=>{
484
+ try {
485
+ const tombstones = removes.map((x)=>({
486
+ _id: x.entity._id,
487
+ _rev: x.entity._rev,
488
+ _deleted: true
489
+ }));
490
+ const updatedDocuments = updates.map((x)=>x.change.entity);
491
+ this._withRevisions(db, [
492
+ ...tombstones,
493
+ ...updatedDocuments
494
+ ], (revisionError)=>{
495
+ if (revisionError != null) {
496
+ d(results_namespaceObject.Result.error(revisionError));
497
+ return;
498
+ }
499
+ db.bulkDocs([
500
+ ...tombstones,
501
+ ...updatedDocuments
502
+ ], null, (error, response)=>{
503
+ if (error != null) {
504
+ d(results_namespaceObject.Result.error(error));
505
+ return;
506
+ }
507
+ for(let i = 0, length = response.length; i < length; i++){
508
+ const doc = response[i];
509
+ if ("error" in doc) {
510
+ const reason = doc.reason ?? doc.error;
511
+ d(results_namespaceObject.Result.error(reason));
512
+ return;
513
+ }
514
+ const removesIndex = removes.findIndex((x)=>x.entity._id === doc.id);
515
+ if (removesIndex !== -1) {
516
+ const { schemaId } = removes[removesIndex];
517
+ const schemaResult = result.resolve(schemaId);
518
+ (0,assertions_namespaceObject.assertIsNotNull)(schemaResult);
519
+ schemaResult.removes.push(doc);
520
+ continue;
521
+ }
522
+ const updatesIndex = updates.findIndex((x)=>x.change.entity._id === doc.id);
523
+ if (updatesIndex !== -1) {
524
+ // Optimistically assume that the update worked as expected
525
+ const update = updates[updatesIndex];
526
+ const changesResult = result.resolve(update.schemaId);
527
+ // Set the new rev
528
+ update.change.entity._rev = doc.rev;
529
+ changesResult.updates.push(update.change.entity);
530
+ continue;
531
+ }
532
+ d(results_namespaceObject.Result.error(new Error("Cannot classify resulting doc")));
533
+ return;
534
+ }
535
+ const pipeline = new pipeline_namespaceObject.WorkPipeline();
536
+ for(let i = 0, length = nonIdentitySchemaIds.length; i < length; i++){
537
+ const schemaId = nonIdentitySchemaIds[i];
538
+ const schemaAdds = adds.filter((x)=>x.schemaId === schemaId).map((x)=>x.entity);
539
+ // Skip schemas with no adds
540
+ if (schemaAdds.length === 0) {
541
+ continue;
542
+ }
543
+ pipeline.pipe((d)=>{
544
+ const schemaResult = result.resolve(schemaId);
545
+ (0,assertions_namespaceObject.assertIsNotNull)(schemaResult);
546
+ (0,assertions_namespaceObject.assertIsNotNull)(schemaAdds);
547
+ db.bulkDocs([
548
+ ...schemaAdds
549
+ ], null, (error, response)=>{
550
+ if (error) {
551
+ d(results_namespaceObject.Result.error(error));
552
+ return;
553
+ }
554
+ // Starts EMPTY and is filled from the ok entries below.
555
+ // Seeding it from every response entry and then pushing each
556
+ // ok id again put every id in twice, so `_bulkGetAdditions`
557
+ // asked for each document twice and the echo carried
558
+ // duplicates into the change tracker.
559
+ const ids = [];
560
+ for(let i = 0, length = response.length; i < length; i++){
561
+ const doc = response[i];
562
+ if ("error" in doc) {
563
+ const reason = doc.reason ?? doc.error;
564
+ d(results_namespaceObject.Result.error(reason));
565
+ return;
566
+ }
567
+ if ("id" in doc && "ok" in doc) {
568
+ ids.push(doc.id);
569
+ } else {
570
+ d(results_namespaceObject.Result.error(doc.error));
571
+ return;
572
+ }
573
+ }
574
+ this._bulkGetAdditions(ids, (bulkGetResponse)=>{
575
+ if (bulkGetResponse.ok !== results_namespaceObject.Result.SUCCESS) {
576
+ d(results_namespaceObject.Result.error(bulkGetResponse));
577
+ return;
578
+ }
579
+ for(let i = 0, length = bulkGetResponse.data.results.length; i < length; i++){
580
+ const docs = bulkGetResponse.data.results[i].docs;
581
+ if (docs.length === 1) {
582
+ const doc = docs[0];
583
+ if ("ok" in doc) {
584
+ schemaResult.adds.push(doc.ok);
585
+ }
586
+ }
587
+ }
588
+ d(results_namespaceObject.Result.success());
589
+ });
590
+ });
591
+ });
592
+ }
593
+ pipeline.filter((r)=>{
594
+ if (r.ok !== results_namespaceObject.Result.SUCCESS) {
595
+ d(r);
596
+ return;
597
+ }
598
+ d(results_namespaceObject.Result.success());
599
+ });
600
+ });
601
+ });
602
+ } catch (e) {
603
+ d(results_namespaceObject.Result.error(e));
604
+ }
605
+ }, done);
606
+ }
607
+ _prepareProperties(...properties) {
608
+ properties.sort((a, b)=>a.name.localeCompare(b.name, undefined, {
609
+ sensitivity: 'base'
610
+ }));
611
+ const paths = properties.map((w)=>w.getAssignmentPath({
612
+ parent: "doc"
613
+ }));
614
+ const viewName = `by_${paths.join("_")}`;
615
+ return {
616
+ properties,
617
+ paths,
618
+ viewName
619
+ };
620
+ }
621
+ resolveIndexes(event, done) {
622
+ const indexes = event.operation.schema.getIndexes();
623
+ if (indexes.length === 0) {
624
+ done(results_namespaceObject.Result.success(null));
625
+ return;
626
+ }
627
+ if (this.indexCache != null) {
628
+ done(results_namespaceObject.Result.success(this.indexCache));
629
+ return; // Already built
630
+ }
631
+ const ddoc = {
632
+ _id: `_design/${INDEX_NAME}`,
633
+ views: {}
634
+ };
635
+ for(let i = 0, length = indexes.length; i < length; i++){
636
+ const index = indexes[i];
637
+ const { viewName, paths } = this._prepareProperties(...index.properties);
638
+ if (index.properties.length === 1) {
639
+ const property = index.properties[0];
640
+ const path = property.getAssignmentPath({
641
+ parent: "doc"
642
+ });
643
+ ddoc.views[viewName] = {
644
+ map: `function(doc) {
645
+ if (${path}) {
646
+ emit(${path});
647
+ }
648
+ }`
649
+ };
650
+ continue;
651
+ }
652
+ ddoc.views[viewName] = {
653
+ map: `function(doc) {
654
+ if (${paths.join(" && ")}) {
655
+ emit([${paths.join(",")}]);
656
+ }
657
+ }`
658
+ };
659
+ }
660
+ this._doWork((db, d)=>{
661
+ // 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
662
+ db.allDocs({
663
+ startkey: '_design/',
664
+ endkey: '_design0',
665
+ include_docs: true
666
+ }).then((response)=>{
667
+ // if we have no indexes, let's create it
668
+ if (response.rows.length === 0) {
669
+ db.put(ddoc, {}, (e)=>{
670
+ if (e) {
671
+ d(results_namespaceObject.Result.error(e));
672
+ return;
673
+ }
674
+ this.indexCache = ddoc;
675
+ d(results_namespaceObject.Result.success(ddoc));
676
+ });
677
+ return;
678
+ }
679
+ const matchingIndex = response.rows.find((x)=>x.id === `_design/${INDEX_NAME}`);
680
+ // make sure we have the correct index created
681
+ if (matchingIndex == null) {
682
+ db.put(ddoc, {}, (e)=>{
683
+ if (e) {
684
+ d(results_namespaceObject.Result.error(e));
685
+ return;
686
+ }
687
+ this.indexCache = ddoc;
688
+ d(results_namespaceObject.Result.success(ddoc));
689
+ });
690
+ return;
691
+ }
692
+ (0,assertions_namespaceObject.assertIsNotNull)(ddoc.views);
693
+ (0,assertions_namespaceObject.assertIsNotNull)(matchingIndex.doc);
694
+ const views = Object.keys(ddoc.views);
695
+ // make sure all of the views are in the document, if not update it
696
+ if (views.some((x)=>matchingIndex.doc.views[x] == null)) {
697
+ // need to get the rev
698
+ db.get(ddoc._id, {}, (e, result)=>{
699
+ if (e != null) {
700
+ d(results_namespaceObject.Result.error(e));
701
+ return;
702
+ }
703
+ result.views = ddoc.views;
704
+ db.put(result, {}, (e)=>{
705
+ if (e) {
706
+ d(results_namespaceObject.Result.error(e));
707
+ return;
708
+ }
709
+ this.indexCache = ddoc;
710
+ d(results_namespaceObject.Result.success(ddoc));
711
+ });
712
+ });
713
+ return;
714
+ }
715
+ d(results_namespaceObject.Result.success(ddoc));
716
+ }).catch((e)=>{
717
+ d(results_namespaceObject.Result.error(e));
718
+ });
719
+ }, done);
720
+ }
721
+ // id should be a string here because this is only run on identity inserts
722
+ _bulkGetAdditions(ids, done) {
723
+ if (ids.length === 0) {
724
+ done(results_namespaceObject.Result.success({
725
+ results: []
726
+ }));
727
+ return;
728
+ }
729
+ this._doWork((db, d)=>{
730
+ db.bulkGet({
731
+ docs: ids.map((w)=>({
732
+ id: w
733
+ }))
734
+ }, (error, response)=>{
735
+ if (error) {
736
+ d(results_namespaceObject.Result.error(error));
737
+ return;
738
+ }
739
+ d(results_namespaceObject.Result.success(response));
740
+ });
741
+ }, done);
742
+ }
743
+ _validateSchemas(event) {
744
+ for (const [, schema] of event.schemas){
745
+ if (schema.idProperties.length > 1) {
746
+ throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key");
747
+ }
748
+ }
749
+ }
750
+ _bulkPersist(event, done) {
751
+ this._validateSchemas(event);
752
+ const result = event.operation.toResult();
753
+ const identitySchemaIds = [];
754
+ const defaultSchemaIds = [];
755
+ for (const [schemaId, schema] of event.schemas){
756
+ if (schema.hasIdentityKeys) {
757
+ identitySchemaIds.push(schemaId);
758
+ continue;
759
+ }
760
+ defaultSchemaIds.push(schemaId);
761
+ }
762
+ this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult)=>{
763
+ if (identityResult.ok !== results_namespaceObject.Result.SUCCESS) {
764
+ done(results_namespaceObject.PluginEventResult.error(event.id, identityResult.error));
765
+ return;
766
+ }
767
+ this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult)=>{
768
+ if (defaultResult.ok !== results_namespaceObject.Result.SUCCESS) {
769
+ done(results_namespaceObject.PluginEventResult.error(event.id, defaultResult.error));
770
+ return;
771
+ }
772
+ done(results_namespaceObject.PluginEventResult.success(event.id, result));
773
+ });
774
+ });
775
+ }
776
+ _doWork(work, done, shouldClose = false) {
777
+ const db = this.database();
778
+ work(db, (result)=>{
779
+ // The `return` is the fix. Without it, `shouldClose` ran BOTH branches: `done`
780
+ // fired synchronously here and again from the close callback. A doubled callback
781
+ // resolves a settled promise silently, but it also drives every pipeline stage
782
+ // downstream twice — see known-defects #3's "calls done exactly once".
783
+ if (shouldClose) {
784
+ // The handle is shared, so closing it has to clear the cache too — the next
785
+ // operation must open a fresh one rather than reuse a closed database.
786
+ this.localDb = null;
787
+ db.close(()=>done(result));
788
+ return;
789
+ }
790
+ done(result);
791
+ });
792
+ }
793
+ destroy(_event, done) {
794
+ // Replication first. A live sync holds both the local and the remote database open
795
+ // and keeps polling; destroying the local one underneath it leaves a replication
796
+ // running against a database that no longer exists, which surfaces later as errors
797
+ // from a plugin the caller believes it has finished with.
798
+ if (this.syncHandle != null) {
799
+ try {
800
+ this.syncHandle.cancel();
801
+ } catch {
802
+ // An already-finished sync throws on cancel. Destroy's goal is that no
803
+ // replication is running, and that is satisfied either way.
804
+ }
805
+ this.syncHandle = null;
806
+ }
807
+ // A destroyed database must not keep serving its cached design document to a plugin
808
+ // that outlives it.
809
+ this.indexCache = null;
810
+ // `shouldClose: true`, so the handle this work opened is closed rather than left to
811
+ // the garbage collector. It was false, which is what left destroy leaking the very
812
+ // resource it was called to release.
813
+ this._doWork((w, d)=>{
814
+ w.destroy(null, (e)=>{
815
+ if (e) {
816
+ d(results_namespaceObject.Result.error(e));
817
+ return;
818
+ }
819
+ d(results_namespaceObject.Result.success());
820
+ });
821
+ }, done, true);
822
+ }
823
+ bulkPersist(event, done) {
824
+ const unitOfWork = (d)=>this._bulkPersist(event, (r)=>{
825
+ d();
826
+ done(r);
827
+ });
828
+ this.queue.enqueue(unitOfWork.bind(this));
829
+ }
830
+ query(event, done) {
831
+ const unitOfWork = (d)=>{
832
+ const settle = (r)=>{
833
+ d();
834
+ done(r);
835
+ };
836
+ // A join is two reads through `_query` — the UN-QUEUED path — on purpose: this unit of
837
+ // work already holds the queue, so routing them through `query` would make them wait on
838
+ // itself and the plugin would never answer. They are still serialized against every
839
+ // other query, because this slot is held for both.
840
+ if (event.operation.options.has("join")) {
841
+ (0,plugins_namespaceObject.joinInPlugin)(event, (e, cb)=>this._query(e, cb), settle);
842
+ return;
843
+ }
844
+ this._query(event, settle);
845
+ };
846
+ this.queue.enqueue(unitOfWork.bind(this));
847
+ }
848
+ onGetIndex(_, __, done) {
849
+ done(null);
850
+ }
851
+ extractEqualityValueForProperty(expression, prop) {
852
+ // Recursively search for a comparator expression that matches the property
853
+ if (expression.type === "comparator" && expression.comparator === "equals") {
854
+ // Check left side is property, right side is value
855
+ if (expression.left && expression.left.type === "property" && expression.left.property.name === prop.name && expression.right && expression.right.type === "value") {
856
+ return expression.right.value;
857
+ }
858
+ // Or right side is property, left side is value
859
+ if (expression.right && expression.right.type === "property" && expression.right.property.name === prop.name && expression.left && expression.left.type === "value") {
860
+ return expression.left.value;
861
+ }
862
+ }
863
+ // Recursively check left and right
864
+ if (expression.left) {
865
+ const left = this.extractEqualityValueForProperty(expression.left, prop);
866
+ if (left !== undefined) return left;
867
+ }
868
+ if (expression.right) {
869
+ const right = this.extractEqualityValueForProperty(expression.right, prop);
870
+ if (right !== undefined) return right;
871
+ }
872
+ return undefined;
873
+ }
874
+ _findMatchingIndex(ddoc, expression) {
875
+ const queryProperties = (0,expressions_namespaceObject.getProperties)(expression);
876
+ const { viewName } = this._prepareProperties(...queryProperties);
877
+ if (ddoc.views == null) {
878
+ return null;
879
+ }
880
+ const index = ddoc.views[viewName];
881
+ if (index == null) {
882
+ return null;
883
+ }
884
+ const properties = [];
885
+ for (const property of queryProperties){
886
+ const value = this.extractEqualityValueForProperty(expression, property);
887
+ if (value === undefined) {
888
+ return null;
889
+ }
890
+ properties.push({
891
+ property,
892
+ value
893
+ });
894
+ }
895
+ return {
896
+ viewName,
897
+ properties
898
+ };
899
+ }
900
+ _queryIndex(event, matchingIndex, done) {
901
+ const translator = new PouchDbTranslator(event.operation);
902
+ this._doWork((w, d)=>{
903
+ const options = {
904
+ include_docs: true
905
+ };
906
+ const values = matchingIndex.properties.map((x)=>x.value);
907
+ if (values.some((x)=>x == null) == false) {
908
+ if (values.length === 1) {
909
+ options.key = values[0];
910
+ } else {
911
+ options.keys = values;
912
+ }
913
+ }
914
+ w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response)=>{
915
+ if (error != null) {
916
+ d(results_namespaceObject.Result.error(error));
917
+ return;
918
+ }
919
+ try {
920
+ const translated = translator.translate(response.rows.map((w)=>w.doc));
921
+ d(results_namespaceObject.Result.success(translated));
922
+ } catch (e) {
923
+ d(results_namespaceObject.Result.error(e));
924
+ }
925
+ });
926
+ }, done);
927
+ }
928
+ _queryNoIndex(event, done) {
929
+ const filters = event.operation.options.get("filter");
930
+ if (filters.length === 0) {
931
+ this._queryWithNoFilters(event, done);
932
+ return;
933
+ }
934
+ this._queryWithFilters(event, done);
935
+ }
936
+ _queryWithNoFilters(event, done) {
937
+ const translator = new PouchDbTranslator(event.operation);
938
+ this._doWork((w, d)=>{
939
+ w.allDocs({
940
+ include_docs: true
941
+ }).then((response)=>{
942
+ try {
943
+ const data = response.rows.map((w)=>w.doc);
944
+ const translated = translator.translate(data);
945
+ d(results_namespaceObject.Result.success(translated));
946
+ } catch (e) {
947
+ d(results_namespaceObject.Result.error(e));
948
+ }
949
+ }).catch((error)=>{
950
+ d(results_namespaceObject.Result.error(error));
951
+ });
952
+ }, done);
953
+ }
954
+ _queryWithFilters(event, done) {
955
+ const translator = new PouchDbTranslator(event.operation);
956
+ this._doWork((w, d)=>{
957
+ if (this._name.startsWith("http")) {
958
+ // Cannot query remote databases using translator.matches, fallback to alldocs
959
+ // Does not throw, will fail on the remote server
960
+ w.allDocs({
961
+ include_docs: true
962
+ }).then((response)=>{
963
+ const data = response.rows.map((w)=>w.doc);
964
+ try {
965
+ const translated = translator.translate(data);
966
+ d(results_namespaceObject.Result.success(translated));
967
+ } catch (e) {
968
+ d(results_namespaceObject.Result.error(e));
969
+ }
970
+ }).catch((error)=>{
971
+ d(results_namespaceObject.Result.error(error));
972
+ });
973
+ return;
974
+ }
975
+ w.query((doc, emit)=>{
976
+ if (typeof doc === "object" && "_id" in doc && translator.matches(doc)) {
977
+ emit(doc._id, doc);
978
+ }
979
+ }, (error, response)=>{
980
+ if (error != null) {
981
+ d(results_namespaceObject.Result.error(error));
982
+ return;
983
+ }
984
+ const data = response.rows.map((w)=>w.value);
985
+ try {
986
+ const translated = translator.translate(data);
987
+ d(results_namespaceObject.Result.success(translated));
988
+ } catch (e) {
989
+ d(results_namespaceObject.Result.error(e));
990
+ }
991
+ });
992
+ }, done);
993
+ }
994
+ _query(event, done) {
995
+ this.resolveIndexes(event, (r)=>{
996
+ if (r.ok !== results_namespaceObject.Result.SUCCESS) {
997
+ done(results_namespaceObject.PluginEventResult.error(event.id, r.error));
998
+ return;
999
+ }
1000
+ const ddoc = r.data;
1001
+ if (ddoc == null) {
1002
+ this._queryNoIndex(event, done);
1003
+ return;
1004
+ }
1005
+ const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);
1006
+ if (mapMatchingIndex != null) {
1007
+ this._queryIndex(event, mapMatchingIndex, done);
1008
+ return;
1009
+ }
1010
+ const expression = this._getExpressionFromQuery(event);
1011
+ if (expressions_namespaceObject.Expression.isEmpty(expression)) {
1012
+ this._queryNoIndex(event, done);
1013
+ return;
1014
+ }
1015
+ const matchingIndex = this._findMatchingIndex(ddoc, expression);
1016
+ if (matchingIndex == null) {
1017
+ this._queryNoIndex(event, done);
1018
+ return;
1019
+ }
1020
+ this._queryIndex(event, matchingIndex, done);
1021
+ });
1022
+ }
1023
+ _getExpressionFromQuery(event) {
1024
+ const filters = event.operation.options.get("filter");
1025
+ const databaseFilters = filters.filter((x)=>x.option.target === "database");
1026
+ if (databaseFilters.length === 0) {
1027
+ return expressions_namespaceObject.Expression.EMPTY;
1028
+ }
1029
+ const expressions = databaseFilters.map((x)=>x.option.value.expression);
1030
+ return (0,expressions_namespaceObject.combineExpressions)(...expressions);
1031
+ }
1032
+ findMatchingIndexForMap(ddoc, event) {
1033
+ const map = event.operation.options.getLast("map");
1034
+ const filters = event.operation.options.get("filter");
1035
+ // we only want to look at the index if there are no filters
1036
+ if (filters.length > 0) {
1037
+ return null;
1038
+ }
1039
+ if (map == null || map.target !== "database") {
1040
+ return null;
1041
+ }
1042
+ if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {
1043
+ return null;
1044
+ }
1045
+ const property = map.value.fields[0].property;
1046
+ const { viewName } = this._prepareProperties(property);
1047
+ if (ddoc.views == null) {
1048
+ return null;
1049
+ }
1050
+ const index = ddoc.views[viewName];
1051
+ if (index == null) {
1052
+ return null;
1053
+ }
1054
+ return {
1055
+ viewName,
1056
+ properties: [
1057
+ {
1058
+ property,
1059
+ value: null
1060
+ }
1061
+ ]
1062
+ };
1063
+ }
1064
+ }
1065
+
1066
+ ;// CONCATENATED MODULE: ./src/index.ts
1067
+
1068
+
1069
+ module.exports = __webpack_exports__;
1070
+ })()
1071
+ ;
1072
+ //# sourceMappingURL=index.cjs.map