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